List of usage examples for org.apache.commons.codec.binary StringUtils getBytesUtf8
public static byte[] getBytesUtf8(final String string)
From source file:mvm.rya.indexing.accumulo.temporal.TemporalInstantRfc3339.java
@Override public byte[] getAsKeyBytes() { return StringUtils.getBytesUtf8(getAsKeyString()); }
From source file:mvm.rya.indexing.accumulo.temporal.TemporalInstantTest.java
@Test public void zoneTestTest() throws Exception { final String ZONETestDateInBRST = "2014-12-31T23:59:59-02:00"; // arbitrary zone, BRST=Brazil, better if not local. final String ZONETestDateInZulu = "2015-01-01T01:59:59Z"; final String ZONETestDateInET = "2014-12-31T20:59:59-05:00"; TemporalInstant instant = new TemporalInstantRfc3339(DateTime.parse(ZONETestDateInBRST)); Assert.assertEquals("Test our test Zulu, ET strings.", ZONETestDateInET, DateTime.parse(ZONETestDateInZulu) .withZone(DateTimeZone.forID("-05:00")).toString(ISODateTimeFormat.dateTimeNoMillis())); Assert.assertEquals("Test our test BRST,Zulu strings.", ZONETestDateInZulu, DateTime.parse(ZONETestDateInBRST).withZone(DateTimeZone.UTC) .toString(ISODateTimeFormat.dateTimeNoMillis())); Assert.assertTrue("Key must be normalized to time zone Zulu: " + instant.getAsKeyString(), instant.getAsKeyString().endsWith("Z")); Assert.assertEquals("Key must be normalized from BRST -02:00", ZONETestDateInZulu, instant.getAsKeyString());//w w w .j a va 2 s.c om Assert.assertArrayEquals(StringUtils.getBytesUtf8(instant.getAsKeyString()), instant.getAsKeyBytes()); Assert.assertTrue("Ignore original time zone.", !ZONETestDateInBRST.equals(instant.getAsReadable(DateTimeZone.forID("-07:00")))); Assert.assertEquals("Use original time zone.", ZONETestDateInBRST, instant.getAsDateTime().toString(TemporalInstantRfc3339.FORMATTER)); Assert.assertEquals("Time at specified time zone.", ZONETestDateInET, instant.getAsReadable(DateTimeZone.forID("-05:00"))); instant = new TemporalInstantRfc3339(DateTime.parse(ZONETestDateInZulu)); Assert.assertEquals("expect a time with specified time zone.", ZONETestDateInET, instant.getAsReadable(DateTimeZone.forID("-05:00"))); }
From source file:at.gv.egovernment.moa.id.protocols.stork2.MandateRetrievalRequest.java
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { Logger.debug("Entering AttributeRequest for MandateProvider"); httpResp.reset();//from w ww .j av a 2 s. com this.representingIdentityLink = authData.getIdentityLink(); this.QAALevel = translateQAALevel(authData.getQAALevel()); // preparing original content and removing sensitive data from it this.originalContent = authData.getMISMandate().getMandate(); // TODO ERROR //Logger.debug("Original content " + StringUtils.newStringUtf8(authData.getMISMandate().getMandate())); String originalMandate = StringUtils.newStringUtf8(authData.getMISMandate().getMandate()).replaceAll( "<pd:Value>.*?==</pd:Value><pd:Type>urn:publicid:gv.at:baseid</pd:Type>", "<pd:Value></pd:Value><pd:Type></pd:Type>"); ; Logger.debug("Removing personal identification value and type from original mandate "); originalContent = StringUtils.getBytesUtf8(originalMandate); OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() .getOnlineApplicationParameter(req.getOAURL()); if (oaParam == null) throw new AuthenticationException("stork.12", new Object[] { req.getOAURL() }); MOASTORKResponse moaStorkResponse = new MOASTORKResponse(); STORKAttrQueryResponse attrResponse = new STORKAttrQueryResponse(); this.authData = authData; if ((req instanceof MOASTORKRequest)) { this.moaStorkRequest = (MOASTORKRequest) req; } else { Logger.error("Internal error - did not receive MOASTORKRequest as expected"); throw new MOAIDException("stork.16", new Object[] {}); // TODO } if (!(moaStorkRequest.isAttrRequest() || moaStorkRequest.getStorkAttrQueryRequest() == null)) { Logger.error("Did not receive attribute request as expected"); throw new MOAIDException("stork.16", new Object[] {}); // TODO } MandateContainer mandateContainer = null; try { mandateContainer = new CorporateBodyMandateContainer( new String(authData.getMISMandate().getMandate(), "UTF-8")); } catch (Exception ex) { try { mandateContainer = new PhyPersonMandateContainer( new String(authData.getMISMandate().getMandate(), "UTF-8")); } catch (Exception ex2) { Logger.error("Could not extract data and create mandate container."); throw new MOAIDException("stork.16", new Object[] {}); // TODO } } IPersonalAttributeList sourceAttributeList = moaStorkRequest.getStorkAttrQueryRequest() .getPersonalAttributeList(); IPersonalAttributeList attributeList = new PersonalAttributeList(); for (PersonalAttribute currentAttribute : sourceAttributeList) { Logger.debug("Evaluating currentattribute " + currentAttribute.getName()); if (currentAttribute.getName().equals("mandateContent")) { MandateContentType mandateContent = getMandateContent(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, mandateContent)); } else if (currentAttribute.getName().equals("representative")) { // TODO CHECK IN DETAIL RepresentationPersonType representative = getRepresentative(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, representative)); //attributeList.add(getRepresentative(mandateContainer, currentAttribute)); } else if (currentAttribute.getName().equals("represented")) { //attributeList.add(getRepresented(mandateContainer, currentAttribute)); RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, represented)); } else if (currentAttribute.getName().equals("mandate")) { //attributeList.add(getMandateType(mandateContainer, currentAttribute)); MandateType mandateType = getMandateType(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, mandateType)); } else if (currentAttribute.getName().equals("legalName")) { String legalName = getLegalName(mandateContainer, currentAttribute); if (legalName.length() > 0) { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.AVAILABLE.value())); } else { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.NOT_AVAILABLE.value())); } } else if (currentAttribute.getName().equals("eLPIdentifier")) { String eLPIdentifier = geteLPIdentifier(mandateContainer, currentAttribute); if (eLPIdentifier.length() > 0) { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.AVAILABLE.value())); } else { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.NOT_AVAILABLE.value())); } } else if (currentAttribute.getName().equals("type")) { String type = getCompanyType(mandateContainer, currentAttribute); if (type.length() > 0) { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.AVAILABLE.value())); } else { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.NOT_AVAILABLE.value())); } } else if (currentAttribute.getName().equals("status")) { String status = getCompanyStatus(mandateContainer, currentAttribute); if (status.length() > 0) { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.AVAILABLE.value())); } else { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.NOT_AVAILABLE.value())); } } else if (currentAttribute.getName().equals("translatableType")) { String translatableType = getCompanyTranslatableType(mandateContainer, currentAttribute); if (translatableType.length() > 0) { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.AVAILABLE.value())); } else { attributeList .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.NOT_AVAILABLE.value())); } } } // if (attrResponse.getPersonalAttributeList().size() == 0) { // Logger.error("AttributeList empty - could not retrieve attributes"); // throw new MOAIDException("stork.16", new Object[]{}); // TODO MESSAGE // } attrResponse.setPersonalAttributeList(attributeList); moaStorkResponse.setSTORKAttrResponse(attrResponse); Logger.debug("Attributes retrieved: " + moaStorkResponse.getStorkAttrQueryResponse().getPersonalAttributeList().size() + " for SP country " + attrResponse.getCountry()); // Prepare extended attributes Logger.debug("Preparing data container"); // create fresh container DataContainer container = new DataContainer(); // - fill in the request we extracted above container.setRequest(moaStorkRequest); // - fill in the partial response created above container.setResponse(moaStorkResponse); container.setRemoteAddress(httpReq.getRemoteAddr()); Logger.debug("Data container prepared"); // ask for consent if necessary if (oaParam.isRequireConsentForStorkAttributes()) new ConsentEvaluator().requestConsent(container, httpResp, oaParam); else new ConsentEvaluator().generateSTORKResponse(httpResp, container); return null; }
From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerTest.java
@Test(expected = RuntimeException.class) public void testInvalidType() { mockery.checking(new Expectations() { {/*from ww w. jav a 2 s . c om*/ } }); EventConsumer consumer = injector.getInstance(EventConsumer.class); consumer.consume(MSG_TYPE, "MY\nCREATE\n" + Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8("random string\nfor test"))); mockery.assertIsSatisfied(); }
From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerTest.java
@Test(expected = RuntimeException.class) public void testInvalidEventType() { mockery.checking(new Expectations() { {//w w w.j a v a 2 s . c o m } }); EventConsumer consumer = injector.getInstance(EventConsumer.class); consumer.consume(MSG_TYPE, "CONTENT\nCREATER\n" + Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8("random string\nfor test"))); mockery.assertIsSatisfied(); }
From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerTest.java
@Test public void testContentConsumption() { mockery.checking(new Expectations() { {//from ww w . j a v a 2 s. c om exactly(1).of(workspaceApi).createWorkspaceId(EventPublisherTest.WORSPACE_NS, EventPublisherTest.WORKSPACE_NAME); final WorkspaceId wId = mockery.mock(WorkspaceId.class); will(returnValue(wId)); exactly(1).of(contentLoader).createContentId(with(wId), with(new BaseMatcher<byte[]>() { public boolean matches(Object item) { return Arrays.equals(StringUtils.getBytesUtf8(EventPublisherTest.CONTENT_ID), (byte[]) item); } public void describeTo(Description description) { } })); final ContentId contentId = mockery.mock(ContentId.class); will(returnValue(contentId)); exactly(1).of(contentId).getContent(); final Content content = mockery.mock(Content.class); will(returnValue(content)); exactly(1).of(eventRegistrar).createEvent(EventType.CREATE, Type.CONTENT, content); final Event<Content> event = mockery.mock(Event.class); will(returnValue(event)); exactly(1).of(contentListener).notify(event); } }); EventConsumer consumer = injector.getInstance(EventConsumer.class); consumer.consume(MSG_TYPE, EventPublisherTest.getContentMsg()); mockery.assertIsSatisfied(); }
From source file:hws.core.JobMaster.java
public void onContainersAllocated(List<Container> containers) { FileSystem fs = null;//from w w w . j av a 2 s . co m try { fs = FileSystem.get(getConfiguration()); } catch (IOException e) { Logger.severe(e.toString()); } for (Container container : containers) { try { //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/home/yarn/rcor/yarn/app-master-log.out"))); Logger.info("Selecting instance to container: " + container.getId().toString()); //dado o container, escolher a instancia que tem dado de entrada mais perto daquele container InstanceInfo instanceInfo = null; if (instances.get(modulePipeline.get(currentModuleIndex).filterInfo().name()) .instancesBuilt() >= modulePipeline.get(currentModuleIndex).numFilterInstances()) { currentModuleIndex++; } if (currentModuleIndex < modulePipeline.size()) { instanceInfo = instances.get(modulePipeline.get(currentModuleIndex).filterInfo().name()) .build(); } else break; String instanceInfoBase64 = Base64 .encodeBase64String(StringUtils.getBytesUtf8(Json.dumps(instanceInfo))) .replaceAll("\\s", ""); // Launch container by create ContainerLaunchContext ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class); ctx.setCommands(Collections.singletonList( "$JAVA_HOME/bin/java -Xmx256M hws.core.InstanceDriver --load " + instanceInfoBase64 + " -aid " + this.appIdStr + " -cid " + container.getId().toString() + " " + this.zksArgs + " 1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout" + " 2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr")); Logger.info("Listing YARN-Watershed files for app-id: " + this.appIdStr); RemoteIterator<LocatedFileStatus> files = fs.listFiles(new Path("hdfs:///hws/bin/"), false); Map<String, LocalResource> resources = new HashMap<String, LocalResource>(); Logger.info("Setup YARN-Watershed files as resources"); while (files.hasNext()) { LocatedFileStatus fileStatus = files.next(); // Setup jar for ApplicationMaster LocalResource containerJar = Records.newRecord(LocalResource.class); ContainerUtils.setupContainerJar(fs, fileStatus.getPath(), containerJar); resources.put(fileStatus.getPath().getName(), containerJar); } Logger.info("Listing application files for app-id: " + this.appIdStr); files = fs.listFiles(new Path("hdfs:///hws/apps/" + this.appIdStr + "/"), false); Logger.info("Setup application files as resources"); while (files.hasNext()) { LocatedFileStatus fileStatus = files.next(); // Setup jar for ApplicationMaster LocalResource containerJar = Records.newRecord(LocalResource.class); ContainerUtils.setupContainerJar(fs, fileStatus.getPath(), containerJar); resources.put(fileStatus.getPath().getName(), containerJar); } Logger.info("container resource setup"); ctx.setLocalResources(resources); Logger.info("Environment setup"); // Setup CLASSPATH for ApplicationMaster Map<String, String> containerEnv = new HashMap<String, String>(); ContainerUtils.setupContainerEnv(containerEnv, getConfiguration()); ctx.setEnvironment(containerEnv); Logger.info("Starting containers"); Logger.info("[AM] Launching container " + container.getId()); nmClient.startContainer(container, ctx); Logger.info("Container started!"); /*String znode = "/hadoop-watershed/"+this.appIdStr+"/"+instanceInfo.filterInfo().name()+"/"+instanceInfo.instanceId(); out.println("Saving instance znode: "+znode); out.flush(); zk.createPersistent(znode, ""); zk.createPersistent(znode+"/host", container.getNodeId().getHost()); out.println("saved location: "+container.getNodeId().getHost()); out.flush(); */ if (instances.get(modulePipeline.get(currentModuleIndex).filterInfo().name()) .instancesBuilt() >= modulePipeline.get(currentModuleIndex).numFilterInstances()) { Logger.info("Starting via ZooKeeper filter: " + instanceInfo.filterInfo().name()); zk.createPersistent("/hadoop-watershed/" + this.appIdStr + "/" + instanceInfo.filterInfo().name() + "/start", ""); } //out.close(); } catch (Exception e) { Logger.severe("[AM] Error launching container " + container.getId() + " " + e); } } try { fs.close(); } catch (IOException e) { Logger.severe(e.toString()); } }
From source file:com.aoppp.gatewaysdk.internal.hw.DigestUtils2.java
/** * Calculates the MD2 digest and returns the value as a 16 element <code>byte[]</code>. * * @param data// w ww . j a va 2 s . co m * Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)} * @return MD2 digest * @since 1.7 */ public static byte[] md2(final String data) { return md2(StringUtils.getBytesUtf8(data)); }
From source file:karma.oss.zookeeper.queue.ZkMessageQueue.java
/** * Get first available (that is un-claimed) element from the ordered child list. Then get the child's data from * zookeeper// w ww. j ava 2 s. c om * @param orderedChildren * List of ordered children from zookeeper * @param markClaimed * Whether to claim this child. If true, the child will not be available in the next read until * put back by calling putbackElement() * @return * Bytes of available element, Optional.absent() otherwise * @throws KeeperException * @throws InterruptedException */ private Optional<Element<byte[]>> getFirstAvailableElement(NavigableMap<Long, String> orderedChildren, boolean markClaimed) throws KeeperException, InterruptedException { boolean hasUnClaimedElements = false; TreeMap<Long, String> claimedChildren = orderedClaimedChildren(null); for (Entry<Long, String> entry : orderedChildren.entrySet()) { // skip children already claimed if (claimedChildren.containsKey(entry.getKey())) { LOG.debug("Element already claimed: " + entry.getValue(), "; skipping"); continue; } hasUnClaimedElements = true; final String elementId = entry.getValue(); try { final String claimPath = claimDir + "/" + elementId; while (markClaimed) { try { final byte[] hostNameBytes = StringUtils.getBytesUtf8(getLocalHostName()); zookeeperRef.get().create(claimPath, hostNameBytes, acl, CreateMode.EPHEMERAL); LOG.info("Element claimed: " + entry.getValue()); break; } catch (KeeperException.NodeExistsException e) { LOG.info("Node at path: " + claimPath + " already exists. Trying different node."); throw e; // will be caught by the outer loop. } catch (KeeperException.NoNodeException e) { createDir(); } } final String path = dir + "/" + elementId; byte[] data = zookeeperRef.get().getData(path, false, null); return Optional.of(Element.create(elementId, data)); } catch (KeeperException.NodeExistsException e) { // Another client claimed the node first. // Refresh claimed children claimedChildren = orderedClaimedChildren(null); } } if (!hasUnClaimedElements) { throw new NoSuchElementException("No unclaimed element found"); } return Optional.absent(); }
From source file:com.smartitengineering.cms.spi.impl.events.EventPublisherTest.java
public static String getContentMsg() { final byte[] contentId = StringUtils.getBytesUtf8(new StringBuilder(WORSPACE_NS).append('\n') .append(WORKSPACE_NAME).append('\n').append(CONTENT_ID).toString()); final String msgContent = new StringBuilder("CONTENT\nCREATE\n") .append(Base64.encodeBase64URLSafeString(contentId)).toString(); return msgContent; }