Java tutorial
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.somewhere.general; import java.util.Objects; import java.util.Optional; import org.apache.commons.rdf.api.IRI; import org.apache.commons.rdf.api.Literal; public class LiteralImpl implements Literal { private final String lex; private final IRI datatype; private final Optional<String> lang; /* package */ LiteralImpl(String lex, IRI datatype, String lang) { this.lex = lex; this.datatype = datatype; if (lang != null) validateLang(lang); this.lang = Optional.ofNullable(lang); } private static void validateLang(String languageTag) { if (languageTag.contains(" ")) throw new IllegalArgumentException(); } private static String QUOTE = "\""; @Override public String ntriplesString() { StringBuilder sb = new StringBuilder(); sb.append(QUOTE); // Escape special characters sb.append(getLexicalForm().replace("\\", "\\\\"). // escaped to \\ replace("\"", "\\\""). // escaped to \" replace("\r", "\\r"). // escaped to \r replace("\n", "\\n")); // escaped to \n sb.append(QUOTE); // getLanguageTag().ifPresent(s -> sb.append("@" + s)); if (getLanguageTag().isPresent()) { sb.append("@"); sb.append(getLanguageTag().get()); } else if (!getDatatype().equals(C.xsdString)) { sb.append("^^"); sb.append(getDatatype().ntriplesString()); } return sb.toString(); } @Override public String getLexicalForm() { return lex; } @Override public IRI getDatatype() { return datatype; } @Override public Optional<String> getLanguageTag() { return lang; } @Override public int hashCode() { return Objects.hash(getLexicalForm(), getDatatype(), getLanguageTag()); } @Override public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (!(other instanceof Literal)) return false; Literal literal = (Literal) other; return getLexicalForm().equals(literal.getLexicalForm()) && getLanguageTag().equals(literal.getLanguageTag()) && getDatatype().equals(literal.getDatatype()); } }