List of usage examples for org.apache.commons.codec.binary StringUtils newStringUtf8
public static String newStringUtf8(final byte[] bytes)
String
by decoding the specified array of bytes using the UTF-8 charset. From source file:com.kolich.blog.entities.html.Utf8TextEntity.java
public Utf8TextEntity(final TextEntityType type, final int status, final byte[] body) { this(type, status, StringUtils.newStringUtf8(body)); }
From source file:com.twosigma.beakerx.chart.serializer.RastersSerializer.java
private String Bytes2Base64(byte[] bytes, String format) { StringBuilder sb = new StringBuilder(); if (format != null) { sb.append("data:image/").append(format).append(";base64,"); } else {// w w w .ja v a2 s. c o m sb.append("data:image/png;base64,"); } sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false))); return sb.toString(); }
From source file:com.tasktop.c2c.server.internal.profile.crypto.OpenSSHPublicKeyReader.java
public String computeEncodedKeyText(SshPublicKey key) { try {/* w ww .j a v a 2 s.c om*/ BigInteger exp = ((RSAPublicKey) key.getPublicKey()).getPublicExponent(); BigInteger mod = ((RSAPublicKey) key.getPublicKey()).getModulus(); Rfc4253Writer writer = new Rfc4253Writer(); writer.writeBytes(FORMAT); writer.writeMpint(exp); writer.writeMpint(mod); return "ssh-rsa " + StringUtils.newStringUtf8(Base64.encodeBase64(writer.getBytes())); } catch (Exception e) { return null; } }
From source file:com.vmware.identity.wstrust.client.impl.RequestBuilderHelper.java
/** * Create and return the JAXB representation of a <wst:BinaryExchange> * element, populated with the base64-encoded form of the given binary data. * This is a helper method to be used by this class' concrete descendants. * * @param wstFactory// w w w.j a v a2s . c om * The factory to use for JAXB object creation. * @param data * The data to populate the created element with. * @return The object representation of a <wst:BinaryExchange> element. The * created element will always have encoding type = base64 and value * type = spnego. */ protected final BinaryExchangeType createBinaryExchangeElement(ObjectFactory wstFactory, byte[] data) { BinaryExchangeType xchg = wstFactory.createBinaryExchangeType(); xchg.setEncodingType(Constants.ENCODING_TYPE_BASE64); xchg.setValueType(Constants.BINARY_EXCHANGE_TYPE_SPNEGO); xchg.setValue(StringUtils.newStringUtf8(Base64.encodeBase64(data, false /* * non * - * chunked */))); return xchg; }
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();/*www . j a va 2s . c om*/ 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:apim.restful.importexport.utils.AuthenticatorUtil.java
/** * Checks whether user has provided non blank username and password for authentication * * @param headers Http Headers of the request * @return boolean Whether a user name and password has been provided for authentication * @throws APIExportException If an error occurs while extracting username and password from * the header */// w ww. ja va 2 s. c o m private static boolean isValidCredentials(HttpHeaders headers) throws APIExportException { //Fetch authorization header final List<String> authorization = headers.getRequestHeader(AUTHORIZATION_PROPERTY); //If no authorization information present; block access if (authorization == null || authorization.isEmpty()) { return false; } //Get encoded username and password final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", ""); //Decode username and password String usernameAndPassword; usernameAndPassword = StringUtils.newStringUtf8(Base64.decodeBase64(encodedUserPassword.getBytes())); if (usernameAndPassword != null) { //Split username and password tokens final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); if (tokenizer.hasMoreTokens()) { username = tokenizer.nextToken(); } if (tokenizer.hasMoreTokens()) { password = tokenizer.nextToken(); } if (username != null && password != null) { return true; } } return false; }
From source file:ch.imvs.sdes4j.srtp.SrtpKeyParam.java
@Override public String encode() { StringBuilder sb = new StringBuilder(); sb.append(keyMethod);//from w w w. j a va2s .com sb.append(':'); sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(key, false))); if (lifetime > 0) { sb.append('|'); sb.append(lifetime); } if (mkiLength > 0) { sb.append('|'); sb.append(mki); sb.append(':'); sb.append(mkiLength); } return sb.toString(); }
From source file:com.dinochiesa.edgecallouts.Base64.java
public ExecutionResult execute(final MessageContext msgCtxt, final ExecutionContext execContext) { try {// w ww . j av a 2 s. co m Base64Action action = getAction(msgCtxt); InputStream content = msgCtxt.getMessage().getContentAsStream(); int lineLength = getLineLength(msgCtxt, -1); InputStream is = new Base64InputStream(content, (action == Base64Action.Encode), lineLength, linebreak); byte[] bytes = IOUtils.toByteArray(is); boolean isBase64 = org.apache.commons.codec.binary.Base64.isBase64(bytes); if (isBase64) { msgCtxt.setVariable(varName("action"), action.name().toLowerCase()); boolean wantStringDefault = (action == Base64Action.Encode); boolean wantString = getStringOutput(msgCtxt, wantStringDefault); if (wantString) { msgCtxt.setVariable(varName("wantString"), wantString); String encoded = StringUtils.newStringUtf8(bytes); msgCtxt.setVariable(varName("result"), encoded); } else { String mimeType = getMimeType(msgCtxt); if (mimeType != null) { msgCtxt.setVariable(varName("mimeType"), mimeType); } msgCtxt.setVariable(varName("result"), bytes); } return ExecutionResult.SUCCESS; } else { msgCtxt.setVariable(varName("error"), "not Base64"); return ExecutionResult.ABORT; } } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); String error = e.toString(); msgCtxt.setVariable(varName("exception"), error); int ch = error.lastIndexOf(':'); if (ch >= 0) { msgCtxt.setVariable(varName("error"), error.substring(ch + 2).trim()); } else { msgCtxt.setVariable(varName("error"), error); } msgCtxt.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(e)); return ExecutionResult.ABORT; } }
From source file:com.smartitengineering.cms.spi.impl.content.VelocityGeneratorTest.java
@Test public void testVelocityRepGeneration() throws IOException { TypeRepresentationGenerator generator = new VelocityRepresentationGenerator(); final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class); WorkspaceAPIImpl impl = new WorkspaceAPIImpl() { @Override/*from w w w . jav a2s.com*/ public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) { return template; } }; impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.VELOCITY, generator)); RepresentationProvider provider = new RepresentationProviderImpl(); final WorkspaceAPI api = impl; registerBeanFactory(api); final Content content = mockery.mock(Content.class); final Field field = mockery.mock(Field.class); final FieldValue value = mockery.mock(FieldValue.class); final Map<String, Field> fieldMap = mockery.mock(Map.class); final ContentType type = mockery.mock(ContentType.class); final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap"); final RepresentationDef def = mockery.mock(RepresentationDef.class); mockery.checking(new Expectations() { { exactly(1).of(template).getTemplateType(); will(returnValue(TemplateType.VELOCITY)); exactly(1).of(template).getTemplate(); will(returnValue(IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream("scripts/velocity/test-template.vm")))); exactly(1).of(template).getName(); will(returnValue(REP_NAME)); exactly(1).of(value).getValue(); will(returnValue(CONTENT)); exactly(1).of(field).getValue(); will(returnValue(value)); exactly(1).of(fieldMap).get(with(Expectations.<String>anything())); will(returnValue(field)); exactly(1).of(content).getFields(); will(returnValue(fieldMap)); exactly(1).of(content).getContentDefinition(); will(returnValue(type)); final ContentId contentId = mockery.mock(ContentId.class); exactly(2).of(content).getContentId(); will(returnValue(contentId)); final WorkspaceId wId = mockery.mock(WorkspaceId.class); exactly(1).of(contentId).getWorkspaceId(); will(returnValue(wId)); exactly(2).of(type).getRepresentationDefs(); will(returnValue(reps)); exactly(2).of(reps).get(with(REP_NAME)); will(returnValue(def)); exactly(1).of(def).getParameters(); will(returnValue(Collections.emptyMap())); exactly(1).of(def).getMIMEType(); will(returnValue(GroovyGeneratorTest.MIME_TYPE)); final ResourceUri rUri = mockery.mock(ResourceUri.class); exactly(1).of(def).getResourceUri(); will(returnValue(rUri)); exactly(1).of(rUri).getValue(); will(returnValue("iUri")); } }); Representation representation = provider.getRepresentation(REP_NAME, type, content); Assert.assertNotNull(representation); Assert.assertEquals(REP_NAME, representation.getName()); Assert.assertEquals(CONTENT, StringUtils.newStringUtf8(representation.getRepresentation())); Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType()); }
From source file:hws.core.ExecutorThread.java
public void run(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, ParseException { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("app-id").withDescription("String of the Application Id") .hasArg().withArgName("AppId").create("aid")); options.addOption(OptionBuilder.withLongOpt("container-id").withDescription("String of the Container Id") .hasArg().withArgName("ContainerId").create("cid")); options.addOption(OptionBuilder.withLongOpt("load").withDescription("load module instance").hasArg() .withArgName("Json-Base64").create()); options.addOption(OptionBuilder.withLongOpt("zk-servers").withDescription("List of the ZooKeeper servers") .hasArgs().withArgName("zkAddrs").create("zks")); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); String appIdStr = null;/*from w ww . j a v a2 s .c om*/ String containerIdStr = null; String instanceInfoBase64 = null; String instanceInfoJson = null; InstanceInfo instanceInfo = null; if (cmd.hasOption("aid")) { appIdStr = cmd.getOptionValue("aid"); } if (cmd.hasOption("cid")) { containerIdStr = cmd.getOptionValue("cid"); } String zksArgs = ""; String[] zkServers = null; if (cmd.hasOption("zks")) { zksArgs = "-zks"; zkServers = cmd.getOptionValues("zks"); for (String zks : zkServers) { zksArgs += " " + zks; } } //Logger setup Configuration conf = new Configuration(); FileSystem fileSystem = FileSystem.get(conf); FSDataOutputStream writer = fileSystem .create(new Path("hdfs:///hws/apps/" + appIdStr + "/logs/" + containerIdStr + ".log")); Logger.addOutputStream(writer); Logger.info("Processing Instance"); if (cmd.hasOption("load")) { instanceInfoBase64 = cmd.getOptionValue("load"); instanceInfoJson = StringUtils.newStringUtf8(Base64.decodeBase64(instanceInfoBase64)); instanceInfo = Json.loads(instanceInfoJson, InstanceInfo.class); } Logger.info("Instance info: " + instanceInfoJson); this.latch = new CountDownLatch(instanceInfo.inputChannels().keySet().size()); Logger.info("Latch Countdowns: " + instanceInfo.inputChannels().keySet().size()); ZkClient zk = new ZkClient(zkServers[0]); //TODO select a ZooKeeper server Logger.info("Load Instance " + instanceInfo.instanceId()); loadInstance(instanceInfo, zk, "/hadoop-watershed/" + appIdStr + "/"); IZkChildListener producersHaltedListener = createProducersHaltedListener(); String znode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/halted"; Logger.info("halting znode: " + znode); zk.subscribeChildChanges(znode, producersHaltedListener); ExecutorService serverExecutor = Executors.newCachedThreadPool(); //wait for a start command from the ApplicationMaster via ZooKeeper znode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/start"; Logger.info("starting znode: " + znode); zk.waitUntilExists(znode, TimeUnit.MILLISECONDS, 250); Logger.info("Exists: " + zk.exists(znode)); /* while(!zk.waitUntilExists(znode,TimeUnit.MILLISECONDS, 500)){ //out.println("TIMEOUT waiting for start znode: "+znode); //out.flush(); }*/ //start and execute this instance Logger.info("Starting Instance"); startExecutors(serverExecutor); Logger.info("Instance STARTED"); Logger.info("Waiting TERMINATION"); try { this.latch.await(); //await the input threads to finish } catch (InterruptedException e) { // handle Logger.severe("Waiting ERROR: " + e.getMessage()); } Logger.info("Finishing Instance"); finishExecutors(); Logger.info("FINISHED Instance " + instanceInfo.instanceId()); String finishZnode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/finish/" + instanceInfo.instanceId(); zk.createPersistent(finishZnode, ""); }