static { objectMapper = new ObjectMapper(); // ignore unknown json properties objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // allow unquoted control characters objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); }
@Override public void onEvalStart() { super.onEvalStart(); initalizeData(); try { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a")); mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true); mapper.configure(SerializationConfig.Feature.WRAP_EXCEPTIONS, true); mapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false); mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true); SimpleModule module = new SimpleModule("DataProxy", new Version(1, 0, 0, null)); module.addSerializer(DataProxy.class, new DataProxySerializer(DataProxy.class)); mapper.registerModule(module); JsonFactory jsonFactory = mapper.getJsonFactory(); writer = jsonFactory.createJsonGenerator(context.getWriter()); writer.setPrettyPrinter(new DefaultPrettyPrinter()); writer.writeStartObject(); } catch (IOException ex) { throw new OseeCoreException(ex); } }
public JsonOutputter() { mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); mapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); }
@Override public Map<String, String> saveOrUpdataReturnCasecadeID( String objectType, HttpServletRequest request) throws Exception { Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request); Object targetObject = Class.forName(objectType).newInstance(); String jsonString = map.get(this.getType(objectType).getSimpleName()); String cascadeTypes = map.get("cascadeType"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Class<?> clazz = this.getType(objectType); targetObject = mapper.readValue(jsonString, clazz); Serializable id = this.commDao.saveOrUpdata(objectType, targetObject); Object target = this.findById(objectType, id.toString()); Map<String, String> returenIDs = new HashMap<String, String>(); returenIDs.put("id", id.toString()); if (cascadeTypes != null) { String[] s = cascadeTypes.split(","); for (int i = 0; i < s.length; i++) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, s[i]); Method method = pd.getReadMethod(); Object childTarget = method.invoke(target); PropertyDescriptor pdID = BeanUtils.getPropertyDescriptor(pd.getPropertyType(), "id"); String childTargetID = pdID.getReadMethod().invoke(childTarget).toString(); returenIDs.put(s[i], childTargetID); } } return returenIDs; }
static { PRETTY_JSON_OBJECT_MAPPER.configure(Feature.INDENT_OUTPUT, true); PRETTY_JSON_OBJECT_MAPPER.configure(Feature.SORT_PROPERTIES_ALPHABETICALLY, true); PRETTY_JSON_OBJECT_MAPPER .getSerializationConfig() .setSerializationInclusion(Inclusion.NON_NULL); try { ERROR_RESULT_JAXB_CONTEXT = JAXBContext.newInstance(ErrorResult.class); XML_DATATYPE_FACTORY = DatatypeFactory.newInstance(); MIMETYPES_FILETYPE_MAP.addMimeTypes( Constants.JSON_CONTENT_TYPE + " json\n" + Constants.XML_CONTENT_TYPE + " xml\n" + Constants.TEXT_CONTENT_TYPE + " txt\n" + Constants.PDF_CONTENT_TYPE + " pdf\n" + Constants.ZIP_CONTENT_TYPE + " zip"); } catch (final Exception e) { throw new IllegalStateException(e); } DEFAULT_FILE_EXTENSIONS.put(Constants.JSON_CONTENT_TYPE, "json"); DEFAULT_FILE_EXTENSIONS.put(Constants.XML_CONTENT_TYPE, "xml"); DEFAULT_FILE_EXTENSIONS.put(Constants.TEXT_CONTENT_TYPE, "txt"); DEFAULT_FILE_EXTENSIONS.put(Constants.PDF_CONTENT_TYPE, "pdf"); DEFAULT_FILE_EXTENSIONS.put(Constants.ZIP_CONTENT_TYPE, "zip"); }
private SessionUpdate getSessionUpdateFrom(String message) { try { switch (connection.getApiLevel()) { case v1: mapper.configure(Feature.UNWRAP_ROOT_VALUE, false); Update update = mapper.readValue(message, Update.class); if (update.getType().equals("playing") && update.getChildren().size() > 0) { return update.getChildren().get(0); } break; case v2: mapper.configure(Feature.UNWRAP_ROOT_VALUE, true); NotificationContainer notificationContainer = mapper.readValue(message, NotificationContainer.class); if (notificationContainer.getStateNotifications().size() > 0) { return notificationContainer.getStateNotifications().get(0); } break; } } catch (JsonParseException e) { logger.error("Error parsing JSON", e); } catch (JsonMappingException e) { logger.error("Error mapping JSON", e); } catch (IOException e) { logger.error("An I/O error occured while decoding JSON", e); } return null; }
@Override public ObjectMapper get() { final ObjectMapper mapper = new ObjectMapper(jsonFactory); // Set the features for (Map.Entry<Enum<?>, Boolean> entry : featureMap.entrySet()) { final Enum<?> key = entry.getKey(); if (key instanceof JsonGenerator.Feature) { mapper.configure(((JsonGenerator.Feature) key), entry.getValue()); } else if (key instanceof JsonParser.Feature) { mapper.configure(((JsonParser.Feature) key), entry.getValue()); } else if (key instanceof SerializationConfig.Feature) { mapper.configure(((SerializationConfig.Feature) key), entry.getValue()); } else if (key instanceof DeserializationConfig.Feature) { mapper.configure(((DeserializationConfig.Feature) key), entry.getValue()); } else { throw new IllegalArgumentException("Can not configure ObjectMapper with " + key.name()); } } for (Module module : modules) { mapper.registerModule(module); } // by default, don't serialize null values. mapper.setSerializationInclusion(Inclusion.NON_NULL); return mapper; }
JSONDeserializer() { mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationConfig.Feature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); mapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, true); mapper.configure(DeserializationConfig.Feature.AUTO_DETECT_SETTERS, true); mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); }
public JSONSerializer() { mapper = new ObjectMapper(); // can reuse, share globally mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(); prettyPrinter.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter()); mapper.prettyPrintingWriter(prettyPrinter); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); }
static { m.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); m.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); m.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); m.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); m.setDateFormat(new LocalStdDateFormat()); // m.registerModule(new WithingsModule()); }
@Provides @Singleton public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); mapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true); mapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, true); return mapper; }
@Override public Object readFrom( Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { ObjectMapper objectMapper = locateMapper(type, mediaType); objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false); return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); }
public ConnectorStore() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(UpdateInfo.class, new UpdateInfoSerializer()); gson = gsonBuilder.create(); mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); }
public ObjectMapper getMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); return mapper; }
protected void initializeWithConfigPath(String configPath) { final ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); final File configFile = new File(configPath); this.setApiConfig(readApiConfiguration(configPath, mapper, configFile)); this.setCodeGenRulesProvider(readRulesProviderConfig(configPath, mapper, configFile)); this.setLanguageConfig( initializeLangConfig(readLanguageConfiguration(configPath, mapper, configFile))); }
public static ObjectMapper getObjectMapper() { if (om == null) { om = new ObjectMapper(); om.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false); om.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL); } return om; }
public void run() { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); User user = mapper.readValue(userStr, User.class); sqlwritter.insertUserTable( user.getUser_id(), user.getName(), user.getReview_count(), user.getAverage_stars(), user.getYelpYear(), user.getYelpMonth(), user.getFans(), user.getType()); Class cls = user.getClass(); Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); Object value = fields[i].get(user); if (fields[i].getName().equals("votes")) { // System.out.println("The field:" + fields[i].getName() ); // System.out.println("The value:" + ((votes) value).getFunny()); // System.out.println("The value:" + ((votes) value).getUseful()); // System.out.println("The value:" + ((votes) value).getCool()); sqlwritter.insertUserVotesTable( user.getUser_id(), ((votes) value).getFunny(), ((votes) value).getUseful(), ((votes) value).getCool()); } if (fields[i].getName().equals("friends")) { // System.out.println("i:" + i + "The field:" + fields[i].getName() ); for (String s : (String[]) value) { // System.out.println("The value: " + s); s.replace('\'', '/'); sqlwritter.insertFriendsTable(user.getUser_id(), s); } } if (fields[i].getName().equals("elite")) { for (Integer year : (int[]) value) { sqlwritter.insertEliteTable(user.getUser_id(), year); } } // System.out.println("i:" + i + "The field:" + fields[i].getName() ); // System.out.println("The value:" + value); } sqlwritter.closeConnection(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { sqlwritter.closeConnection(); } }
public void respond() { String json; ObjectMapper mapper = null; boolean isJsonResponse = !aljeersResponse.isRespondRawString(); if (isJsonResponse) { mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false); } if (req.isDebug()) { resp.setContentType("text/plain"); if (isJsonResponse) { mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); } } else { String ct = aljeersResponse.getContentType(); resp.setContentType((ct != null) ? ct : "application/json"); } for (String headerName : aljeersResponse.getHeaders().keySet()) { Object headerValue = aljeersResponse.getHeaders().get(headerName); resp.setHeader(headerName, (headerValue != null) ? headerValue.toString() : null); } try { resp.setStatus(aljeersResponse.getStatus()); if (aljeersResponse.getBody() != null && aljeersResponse.getStatus() != HttpServletResponse.SC_NO_CONTENT) { if (isJsonResponse) { Object serializeMe = (req.isDebug()) ? aljeersResponse : aljeersResponse.getBody(); json = mapper.writeValueAsString(serializeMe).trim(); resp.getOutputStream().print(json); } else { resp.getOutputStream().print(aljeersResponse.getBody().toString()); } } } catch (IOException e) { e.printStackTrace(); } }
/** Converts the JSON string to a typed object (or Map/List if Object.class is passed in) */ public static <T> T fromJSON(String value, Class<T> type) { ObjectMapper mapper = new ObjectMapper(); try { mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(value, type); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
/** * Initialises the database. */ static { try { ObjectMapper om = new ObjectMapper(); om.configure( JsonParser.Feature.ALLOW_COMMENTS, true ); String jsonText = Resources.loadResourceAsString( DATABASE_NAME ); // workaround for bug #779, see http://jira.codehaus.org/browse/JACKSON-779 database = om.readTree( jsonText ); } catch ( Exception e ) { throw new ExceptionInInitializerError( e ); } }
public JsonContext() { ObjectMapper mapper = getObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper .getSerializationConfig() .addMixInAnnotations(ProtocolObject.class, StyxClassIdJsonMixIn.class); SimpleModule module = new SimpleModule("ProtocolDeserializer Module", new Version(1, 0, 0, null)); module.addDeserializer( HashMapMessage.class, new StdDeserializer<HashMapMessage>(HashMapMessage.class) { @Override @SuppressWarnings("unchecked") public HashMapMessage deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); ObjectNode root = (ObjectNode) mapper.readTree(jp); HashMapMessage s = new HashMapMessage(); if (hasProtocolObjectData(root)) { /* * We have a data node with a classId which makes us comfortable * this is a protocol object. So 1) remove the data; 2) find object * class from classId; 3) create object; and 4) put back again... */ JsonNode node = root.remove("data"); int classId = node.get("classId").asInt(); Class<? extends ProtocolObject> cl = factory.create(classId).getClass(); ProtocolObject p = mapper.readValue(node, cl); s.setData(p); } /* * Read the remainder as an ordinary map and put all into the * server messages */ HashMap<String, ?> values = mapper.readValue(root, HashMap.class); s.putAll(values); return s; } // --- PRIVATE METHODS --- // /* * Return true if the object has a data field which has a "classId" field */ private boolean hasProtocolObjectData(ObjectNode root) { JsonNode dataNode = root.get("data"); JsonNode idNode = (dataNode == null ? null : dataNode.get(CLASS_ID_PROPERTY)); return idNode != null; } }); mapper.registerModule(module); }
@Override public Serializable save(String objectType, HttpServletRequest request) throws Exception { Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request); Object targetObject = Class.forName(objectType).newInstance(); String jsonString = map.get(this.getType(objectType).getSimpleName()); System.out.println(jsonString); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); Class<?> clazz = this.getType(objectType); targetObject = mapper.readValue(jsonString, clazz); return this.commDao.save(objectType, targetObject); }
/** @param args */ public static void main(String[] args) { logger.info("Teste para simular a conversao de objetos Java para o formato json."); // Jackson Object Mapper // ObjectMapper mapper = new ObjectMapper(); // configura a formatacao do json para impressao com identacao mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); // // Cria os Objetos e Popula manualmente // // ISBN List<Isbn> isbn = new ArrayList<Isbn>(); isbn.add(new Isbn("0-00-225010-1")); isbn.add(new Isbn("0-00-649035-2")); // Autores List<Author> authors = new ArrayList(); authors.add(new Author("Cornwell", "Bernard", 68, Sex.MALE)); // Generos List<Genre> genres = new ArrayList(); genres.add(new Genre("Historical Fantasy")); genres.add(new Genre("Fantasy")); // Livro // Book book = new Book(); book.setTitle("Sharpe's Tiger"); book.setYear(1997); book.setISBN(isbn); book.setAuthors(authors); book.setGenres(genres); try { String jsonFormatted = mapper.writeValueAsString(book); logger.debug(jsonFormatted); } catch (JsonGenerationException e) { logger.error(e); } catch (JsonMappingException e) { logger.error(e); } catch (IOException e) { logger.error(e); } }
public static <T> T toObject(String content, Class<T> valueType) { if (objectMapper == null) { objectMapper = new ObjectMapper(); objectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); } try { return objectMapper.readValue(content, valueType); } catch (Exception e) { e.printStackTrace(); } return null; }
public MarketBtce(Currency cur1, Currency cur2) throws ExchangeError { super(cur1, cur2, "btce"); // JSON mapper inialisation mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationConfig.Feature.USE_BIG_DECIMAL_FOR_FLOATS, false); // Ajout d'un deserializer d'ordre customis� pour passer de "[ prix, amount ]" dans le json � // "new Order(prix,amount,Type.XXX) en java" SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null)); testModule.addDeserializer(Order.class, new OrderDeserializer()); mapper.registerModule(testModule); // Ajout d'un deserializer des types customis� pour passer de "ask"(resp. "bid") dans le json � // "Type.ASK" (resp. "Type.BID") en java testModule = new SimpleModule("MyModule2", new Version(1, 0, 0, null)); testModule.addDeserializer(Type.class, new TypeDeserializer(true)); mapper.registerModule(testModule); // Verification si la pair <cur1, cur2> est accepte par l'exchange URL fee_url; Fee f; try { fee_url = new URL( "https://btc-e.com/api/2/" + cur1.name().toLowerCase() + "_" + cur2.name().toLowerCase() + "/fee"); String is = Util.getData(fee_url); f = mapper.readValue(is, Fee.class); Assert.checkPrecond( f.error == null, "BTC-E n'autorise pas la pair: <" + cur1.name() + "," + cur2.name() + ">"); // On set les frais de transaction maintenant qu'on est sur que Btc-e autorise la paire // <cur1,cur2> fee_percent = Op.mult(f.trade, new Decimal("0.01")); } catch (JsonParseException e) { e.printStackTrace(); throw new ExchangeError("JsonParseException: Erreur jackson"); } catch (JsonMappingException e) { e.printStackTrace(); throw new ExchangeError("JsonMappingException: Erreur jackson"); } catch (IOException e) { e.printStackTrace(); throw new ExchangeError("IOException: Erreur jackson"); } }
@RequestMapping( method = RequestMethod.GET, value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicRecurrentJourney/{clientId}") public @ResponseBody BasicRecurrentJourney getRecurrentJourney( HttpServletRequest request, HttpServletResponse response, HttpSession session, @PathVariable String clientId) throws InvocationException { try { User user = getUser(request); String userId = getUserId(user); if (userId == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } DomainObject obj = getObjectByClientId( clientId, "smartcampus.services.journeyplanner.RecurrentJourneyObject"); if (obj == null) { return null; } if (checkUser(obj, userId) == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Map<String, Object> content = obj.getContent(); RecurrentJourney recurrent = mapper.convertValue(content.get("data"), RecurrentJourney.class); BasicRecurrentJourney recurrentJourney = new BasicRecurrentJourney(); String objectClientId = (String) content.get("clientId"); if (!clientId.equals(objectClientId)) { response.setStatus(HttpServletResponse.SC_CONFLICT); return null; } recurrentJourney.setData(recurrent); recurrentJourney.setClientId(clientId); recurrentJourney.setName((String) obj.getContent().get("name")); recurrentJourney.setMonitor((Boolean) obj.getContent().get("monitor")); recurrentJourney.setUser((String) obj.getContent().get("userId")); return recurrentJourney; } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return null; }
@Test public void toJSONAliasViewExclusive() throws IOException { Handlebars handlebars = new Handlebars(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.DEFAULT_VIEW_INCLUSION, false); handlebars.registerHelper("@json", new JSONHelper(mapper).viewAlias("myView", Public.class)); Template template = handlebars.compile("{{@json this view=\"myView\"}}"); CharSequence result = template.apply(new Blog("First Post", "...")); assertEquals("{\"title\":\"First Post\"}", result); }
@Test(expected = HandlebarsException.class) public void jsonViewNotFound() throws IOException { Handlebars handlebars = new Handlebars(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.DEFAULT_VIEW_INCLUSION, false); handlebars.registerHelper("@json", new JSONHelper(mapper)); Template template = handlebars.compile("{{@json this view=\"missing.ViewClass\"}}"); CharSequence result = template.apply(new Blog("First Post", "...")); assertEquals("{\"title\":\"First Post\"}", result); }
public static void main(String[] args) throws IOException { ResourceSet r = new ResourceSet(); r.setName("test name"); r.setIconUri("http://icon.com"); final ObjectMapper mapper = ServerUtil.createJsonMapper(); mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true); final String json = mapper.writeValueAsString(r); System.out.println(json); final String j = "{\"resourceSetStatus\":{\"_id\":1364301527462,\"_rev\":1,\"status\":\"created\"}}"; // final String j = "{\"_id\":1364301527462,\"_rev\":1,\"status\":\"created\"}"; final ResourceSetStatus newR = TUma.readJsonValue(j, ResourceSetStatus.class); System.out.println(); }
/** * Constructs a new Swift {@link UnderFileSystem}. * * @param uri the {@link AlluxioURI} for this UFS */ public SwiftUnderFileSystem(AlluxioURI uri) { super(uri); String containerName = uri.getHost(); LOG.debug("Constructor init: {}", containerName); AccountConfig config = new AccountConfig(); if (Configuration.containsKey(Constants.SWIFT_API_KEY)) { config.setPassword(Configuration.get(Constants.SWIFT_API_KEY)); } else if (Configuration.containsKey(Constants.SWIFT_PASSWORD_KEY)) { config.setPassword(Configuration.get(Constants.SWIFT_PASSWORD_KEY)); } config.setAuthUrl(Configuration.get(Constants.SWIFT_AUTH_URL_KEY)); String authMethod = Configuration.get(Constants.SWIFT_AUTH_METHOD_KEY); if (authMethod != null) { config.setUsername(Configuration.get(Constants.SWIFT_USER_KEY)); config.setTenantName(Configuration.get(Constants.SWIFT_TENANT_KEY)); switch (authMethod) { case Constants.SWIFT_AUTH_KEYSTONE: config.setAuthenticationMethod(AuthenticationMethod.KEYSTONE); break; case Constants.SWIFT_AUTH_SWIFTAUTH: // swiftauth authenticates directly against swift // note: this method is supported in swift object storage api v1 config.setAuthenticationMethod(AuthenticationMethod.BASIC); break; default: config.setAuthenticationMethod(AuthenticationMethod.TEMPAUTH); // tempauth requires authentication header to be of the form tenant:user. // JOSS however generates header of the form user:tenant. // To resolve this, we switch user with tenant config.setTenantName(Configuration.get(Constants.SWIFT_USER_KEY)); config.setUsername(Configuration.get(Constants.SWIFT_TENANT_KEY)); } } ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true); mContainerName = containerName; mAccount = new AccountFactory(config).createAccount(); // Do not allow container cache to avoid stale directory listings mAccount.setAllowContainerCaching(false); mAccess = mAccount.authenticate(); Container container = mAccount.getContainer(containerName); if (!container.exists()) { container.create(); } mContainerPrefix = Constants.HEADER_SWIFT + mContainerName + PATH_SEPARATOR; }