index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/template/ExpandedTemplate.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.template;
import jqiita.tag.Tag;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ExpandedTemplate implements Serializable {
private String expandedBody;
private List<Tag> expandedTags;
private String expandedTitle;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/template/ExpandedTemplates.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.template;
import retrofit.http.Body;
import retrofit.http.POST;
public interface ExpandedTemplates {
/**
* @see <a href="http://qiita.com/api/v2/docs#post-/api/v2/expanded_templates">API SPEC</a>
*/
@POST("/expanded_templates")
ExpandedTemplate create(@Body TemplateRequest request);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/template/Template.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.template;
import jqiita.tag.Tag;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class Template implements Serializable {
private String body;
private String id;
private String name;
private String expandedBody;
private List<Tag> expandedTags;
private String expandedTitle;
private List<Tag> tags;
private String title;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/template/TemplateRequest.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.template;
import jqiita.tag.Tag;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class TemplateRequest implements Serializable {
private final String body;
private final String name;
private final List<Tag> tags;
private final String title;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/template/Templates.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.template;
import retrofit.http.*;
import java.util.List;
public interface Templates {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/templates">API SPEC</a>
*/
@GET("/templates")
List<Template> list();
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/templates">API SPEC</a>
*/
@GET("/templates")
List<Template> list(@Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/templates/:id">API SPEC</a>
*/
@GET("/templates/{id}")
Template get(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#delete-/api/v2/templates/:id">API SPEC</a>
*/
@DELETE("/templates/{id}")
Void delete(@Path("id") String id);
/**
* @see <a href="http://qiita.com/api/v2/docs#post-/api/v2/templates">API SPEC</a>
*/
@POST("/templates")
Template create(@Body TemplateRequest request);
/**
* @see <a href="http://qiita.com/api/v2/docs#patch-/api/v2/templates/:id">API SPEC</a>
*/
@POST("/templates/{id}")
@Headers("X-Http-Method-Override: PATCH")
Template update(@Path("id") String id, @Body TemplateRequest request);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/AuthenticatedUser.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import retrofit.http.GET;
public interface AuthenticatedUser {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/authenticated_user">API SPEC</a>
*/
@GET("/authenticated_user")
User get();
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/Followees.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface Followees {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/followees">API SPEC</a>
*/
@GET("/users/{user_id}/followees")
List<User> listByUserId(@Path("user_id") String userId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/followees">API SPEC</a>
*/
@GET("/users/{user_id}/followees")
List<User> listByUserId(@Path("user_id") String userId, @Query("page") int page, @Query("per_page") int perPage);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/Followers.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface Followers {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/followers">API SPEC</a>
*/
@GET("/users/{user_id}/followers")
List<User> listByUserId(@Path("user_id") String userId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:user_id/followers">API SPEC</a>
*/
@GET("/users/{user_id}/followers")
List<User> listByUserId(@Path("user_id") String userId, @Query("page") int page, @Query("per_page") int perPage);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/Stockers.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface Stockers {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items/:item_id/stockers">API SPEC</a>
*/
@GET("/items/{item_id}/stockers")
List<User> listByItemId(@Path("item_id") String itemId);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/items/:item_id/stockers">API SPEC</a>
*/
@GET("/items/{item_id}/stockers")
List<User> listByItemId(@Path("item_id") String itemId, @Query("page") int page, @Query("per_page") int perPage);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/User.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private String description;
private String facebookId;
private int followeesCount;
private int followersCount;
private String githubLoginName;
private String id;
private String linkedinId;
private String location;
private String name;
private String organization;
private String profileImageUrl;
private String twitterScreenName;
private String websiteUrl;
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/user/Users.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.user;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
import java.util.List;
public interface Users {
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users">API SPEC</a>
*/
@GET("/users")
List<User> list();
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users">API SPEC</a>
*/
@GET("/users")
List<User> list(@Query("page") int page, @Query("per_page") int perPage);
/**
* @see <a href="http://qiita.com/api/v2/docs#get-/api/v2/users/:id">API SPEC</a>
*/
@GET("/users/{id}")
User get(@Path("id") String id);
}
|
0 | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita | java-sources/am/ik/jqiita/jqiita/0.8.1/jqiita/util/QiitaOptional.java | /*
* Copyright (C) 2014 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 jqiita.util;
import jqiita.exception.QiitaNotFoundException;
import java.util.Optional;
import java.util.function.Supplier;
public class QiitaOptional {
public static <T> Optional<T> get(Supplier<T> supplier) {
try {
return Optional.of(supplier.get());
} catch (QiitaNotFoundException ok) {
return Optional.empty();
}
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/Json.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public final class Json {
public static JsonNode parse(String json) {
return new JsonParser(new JsonLexer(json)).parse();
}
public static String stringify(JsonNode json) {
return json == null ? "null" : json.toString();
}
public static String stringify(JsonArray json) {
return json == null ? "null" : json.toString();
}
public static String stringify(JsonObject json) {
return json == null ? "null" : json.toString();
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonArray.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class JsonArray {
private final List<JsonNode> values;
public JsonArray() {
this.values = new ArrayList<>();
}
public JsonArray add(JsonNode value) {
this.values.add(value);
return this;
}
public JsonNode get(int index) {
return this.values.get(index);
}
public int size() {
return this.values.size();
}
public List<JsonNode> values() {
return Collections.unmodifiableList(this.values);
}
public JsonNode toNode() {
return new JsonNode(this);
}
@Override
public String toString() {
return Objects.toString(this.values);
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonLexer.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class JsonLexer implements Iterator<Token>, Iterable<Token> {
private final String input;
private int position;
public JsonLexer(String input) {
this.input = input;
this.position = 0;
}
public Token nextToken() {
Character current;
do {
current = this.consume();
if (current == null) {
return new Token(TokenType.EOF, "");
}
} while (Character.isWhitespace(current));
if (current == '{') {
return new Token(TokenType.LEFT_BRACE, "{");
}
else if (current == '}') {
return new Token(TokenType.RIGHT_BRACE, "}");
}
else if (current == '[') {
return new Token(TokenType.LEFT_BRACKET, "[");
}
else if (current == ']') {
return new Token(TokenType.RIGHT_BRACKET, "]");
}
else if (current == ':') {
return new Token(TokenType.COLON, ":");
}
else if (current == ',') {
return new Token(TokenType.COMMA, ",");
}
else if (current == '"') {
return this.stringToken();
}
else if (Character.isDigit(current) || current == '-') {
return this.numberToken(current);
}
else if (Character.isLetter(current)) {
return this.literalToken(current);
}
throw new JsonLexerException("Invalid Character: " + current);
}
private char current() {
return this.input.charAt(this.position);
}
private boolean isEof() {
return this.position >= this.input.length();
}
private Character consume() {
if (this.isEof()) {
return null;
}
final char current = this.current();
this.position++;
return current;
}
private Token stringToken() {
final StringBuilder sb = new StringBuilder();
Character current = this.consume();
while (current != null) {
if (current == '"') {
return new Token(TokenType.STRING, sb.toString());
}
if (current != '\\') {
sb.append(current);
}
else {
final Character next = this.consume();
if (next == null) {
throw new JsonLexerException("Unterminated string: " + sb);
}
switch (next) {
case '"':
case '\\':
case '/':
sb.append(next);
break;
case 'f':
sb.append('\f');
break;
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
default:
sb.append('\\').append(next);
}
}
current = this.consume();
}
throw new JsonLexerException("Unterminated string: " + sb);
}
private Token numberToken(char c) {
final StringBuilder sb = new StringBuilder();
sb.append(c);
while (!this.isEof()) {
final char current = this.current();
if (Character.isDigit(current) || current == '.') {
sb.append(this.consume());
}
else {
break;
}
}
final String number = sb.toString();
if (number.contains(".")) {
return new Token(TokenType.FLOAT, number);
}
else {
return new Token(TokenType.INT, number);
}
}
private Token literalToken(char c) {
final StringBuilder sb = new StringBuilder();
sb.append(c);
while (!this.isEof()) {
final char current = this.current();
if (Character.isLetter(current)) {
sb.append(this.consume());
}
else {
break;
}
}
final String literal = sb.toString();
switch (literal) {
case "true":
case "false":
return new Token(TokenType.BOOLEAN, literal);
case "null":
return new Token(TokenType.NULL, literal);
default:
throw new JsonLexerException("Invalid literal: " + literal);
}
}
@Override
public boolean hasNext() {
return !this.isEof();
}
@Override
public Token next() {
if (this.isEof()) {
throw new NoSuchElementException("EOF");
}
return this.nextToken();
}
@Override
public Iterator<Token> iterator() {
return this;
}
public Stream<Token> stream() {
return StreamSupport.stream(this.spliterator(), false);
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonLexerException.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public class JsonLexerException extends RuntimeException {
public JsonLexerException(String message) {
super(message);
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonNode.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
import java.util.Objects;
import java.util.Optional;
public class JsonNode {
private final Object value;
public JsonNode(Object value) {
this.value = value;
}
public Object value() {
return this.value;
}
public boolean isNull() {
return this.value == null;
}
public Optional<Object> optional() {
return Optional.ofNullable(this.value);
}
public boolean isBoolean() {
return this.value instanceof Boolean;
}
public boolean isString() {
return this.value instanceof String;
}
public boolean isNumber() {
return this.value instanceof Integer || this.value instanceof Float;
}
public boolean isInteger() {
return this.value instanceof Integer;
}
public boolean isFloat() {
return this.value instanceof Float;
}
public boolean isArray() {
return this.value instanceof JsonArray;
}
public boolean isObject() {
return this.value instanceof JsonObject;
}
public Boolean asBoolean() {
if (this.value == null) {
return null;
}
if (isBoolean()) {
return (Boolean) this.value;
}
throw new IllegalStateException("Value is not a boolean");
}
public String asString() {
if (this.value == null) {
return null;
}
if (isString()) {
return (String) this.value;
}
throw new IllegalStateException("Value is not a string");
}
public Number asNumber() {
if (this.value == null) {
return null;
}
if (isNumber()) {
return (Number) this.value;
}
throw new IllegalStateException("Value is not a number");
}
public Integer asInteger() {
if (this.value == null) {
return null;
}
if (isInteger()) {
return (Integer) this.value;
}
throw new IllegalStateException("Value is not an integer");
}
public Float asFloat() {
if (this.value == null) {
return null;
}
if (isFloat()) {
return (Float) this.value;
}
throw new IllegalStateException("Value is not a float");
}
public JsonArray asArray() {
if (this.value == null) {
return null;
}
if (isArray()) {
return (JsonArray) this.value;
}
throw new IllegalStateException("Value is not an array");
}
public JsonObject asObject() {
if (this.value == null) {
return null;
}
if (isObject()) {
return (JsonObject) this.value;
}
throw new IllegalStateException("Value is not an object");
}
@Override
public String toString() {
if (this.value == null) {
return "null";
}
if (isString()) {
return "\"" + stringify((String) this.value) + "\"";
}
return Objects.toString(this.value);
}
private static String stringify(String value) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
switch (c) {
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '\\':
case '"':
case '/':
sb.append('\\').append(c);
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonObject.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class JsonObject {
private final Map<String, JsonNode> properties;
public JsonObject() {
this.properties = new LinkedHashMap<>();
}
public JsonObject put(String key, JsonNode value) {
this.properties.put(key, value);
return this;
}
public JsonObject put(String key, JsonArray value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonObject put(String key, JsonObject value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonObject put(String key, String value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonObject put(String key, int value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonObject put(String key, float value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonObject put(String key, boolean value) {
this.properties.put(key, new JsonNode(value));
return this;
}
public JsonNode get(String key) {
final JsonNode value = this.properties.get(key);
if (value == null) {
return new JsonNode(null);
}
return value;
}
public boolean containsKey(String key) {
return this.properties.containsKey(key);
}
public Set<String> keySet() {
return this.properties.keySet();
}
public int size() {
return this.properties.size();
}
public boolean isEmpty() {
return this.properties.isEmpty();
}
public Map<String, JsonNode> asMap() {
return Collections.unmodifiableMap(this.properties);
}
public JsonNode toNode() {
return new JsonNode(this);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{");
final int size = this.properties.size();
int i = 0;
for (Entry<String, JsonNode> entry : this.properties.entrySet()) {
String k = entry.getKey();
JsonNode v = entry.getValue();
sb.append("\"").append(k).append("\"").append(":").append(v);
if (++i != size) {
sb.append(",");
}
}
sb.replace(sb.length(), sb.length(), "}");
return sb.toString();
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonParseException.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public class JsonParseException extends RuntimeException {
public JsonParseException(String message) {
super(message);
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/JsonParser.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public class JsonParser {
private final JsonLexer lexer;
private Token currentToken;
public JsonParser(JsonLexer lexer) {
this.lexer = lexer;
this.currentToken = lexer.nextToken();
}
public JsonNode parse() {
return parseValue();
}
private JsonObject parseObject() {
final JsonObject jsonObject = new JsonObject();
consumeToken(TokenType.LEFT_BRACE);
while (this.currentToken.type() != TokenType.RIGHT_BRACE) {
final Token token = consumeToken(TokenType.STRING);
final String key = token.value();
consumeToken(TokenType.COLON);
final JsonNode value = parseValue();
jsonObject.put(key, value);
if (this.currentToken.type() == TokenType.COMMA) {
consumeToken(TokenType.COMMA);
}
}
consumeToken(TokenType.RIGHT_BRACE);
return jsonObject;
}
private JsonArray parseArray() {
final JsonArray jsonArray = new JsonArray();
consumeToken(TokenType.LEFT_BRACKET);
while (this.currentToken.type() != TokenType.RIGHT_BRACKET) {
final JsonNode value = parseValue();
jsonArray.add(value);
if (this.currentToken.type() == TokenType.COMMA) {
consumeToken(TokenType.COMMA);
}
}
consumeToken(TokenType.RIGHT_BRACKET);
return jsonArray;
}
private JsonNode parseValue() {
final TokenType type = this.currentToken.type();
switch (type) {
case LEFT_BRACE:
return new JsonNode(parseObject());
case LEFT_BRACKET:
return new JsonNode(parseArray());
case STRING:
final String stringValue = this.currentToken.value();
consumeToken(TokenType.STRING);
return new JsonNode(stringValue);
case INT:
final int intValue = Integer.parseInt(this.currentToken.value());
consumeToken(TokenType.INT);
return new JsonNode(intValue);
case FLOAT:
final float floatValue = Float.parseFloat(this.currentToken.value());
consumeToken(TokenType.FLOAT);
return new JsonNode(floatValue);
case BOOLEAN:
// TODO: `Boolean.parseBoolean` doesn't work with teavm-wasi 0.2.7
final boolean booleanValue = "true".equals(this.currentToken.value());
consumeToken(TokenType.BOOLEAN);
return new JsonNode(booleanValue);
case NULL:
consumeToken(TokenType.NULL);
return new JsonNode(null);
default:
throw new JsonParseException("Unexpected token: " + this.currentToken.type());
}
}
private Token consumeToken(TokenType expectedType) {
final Token token = this.currentToken;
if (this.currentToken.type() == expectedType) {
this.currentToken = this.lexer.nextToken();
}
else {
throw new JsonParseException("Token mismatch. Expected: " + expectedType + ", found: " + this.currentToken.type());
}
return token;
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/Token.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public class Token {
private final TokenType type;
private final String value;
public Token(TokenType type, String value) {
this.type = type;
this.value = value;
}
public TokenType type() {
return type;
}
public String value() {
return value;
}
@Override
public String toString() {
return "Token{" +
"type=" + type +
", value='" + value + '\'' +
'}';
}
}
|
0 | java-sources/am/ik/json/tiny-json/0.1.2/am/ik | java-sources/am/ik/json/tiny-json/0.1.2/am/ik/json/TokenType.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.json;
public enum TokenType {
LEFT_BRACE,
RIGHT_BRACE,
LEFT_BRACKET,
RIGHT_BRACKET,
COLON,
COMMA,
STRING,
INT,
FLOAT,
BOOLEAN,
NULL,
EOF
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/LTSV.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j;
/**
* public interface to manipulate LTSV file.
*
* <h2>Simple Usage</h2>
* <pre>
* <code>
* Map<String, String> line = LTSV.parser().parseLine("hoge:foo\tbar:baz\n"); => {"hoge" : "foo", "bar" : "baz"}
* String line = LTSV.formatter().formatLine(line) => "hoge:foo\tbar:baz"
* // Vise versa
* Map<String, String> line = LTSV.parser().ignores("hoge").parseLine("hoge:foo\tbar:baz\n"); => {"bar" : "baz"}
* // Only want certain fields?
* Map<String, String> line = LTSV.parser().wants("hoge").parseLine("hoge:foo\tbar:baz\n"); => {"hoge" : "foo"}
*
* List<Map<String, String>> lines = LTSV.parser().parseLines("test.ltsv");
* LTSV.formatter.formatLines(lines, "foo.ltsv");
* </code>
* <h2>Read Stream</h2>
* <pre>
* <code>
* try (LTSVIterator iterator = LTSV.parser().iterator("test.ltsv")) {
* while (iterator.hasNext()) {
* Map<String, String> line = iterator.next();
* }
* }
* </code>
* </pre>
* </pre>
*
* @author making
*
*/
public final class LTSV {
/**
* TAB.
*/
public static final String TAB = "\t";
/**
* LF.
*/
public static final char LF = '\n';
/**
* CR.
*/
public static final char CR = '\r';
/**
* separator of LTSV
*/
public static final String SEPARATOR = ":";
/**
* default charset to read/write ltsv file.
*/
public static final String DEFAULT_CHARSET = "UTF-8";
/**
* constructor
*/
private LTSV() {
}
/**
* create {@link LTSVParser}
*
* @return parser
*/
public static LTSVParser parser() {
return new LTSVParser();
}
/**
* create {@link LTSVFormatter}
*
* @return formatter
*/
public static LTSVFormatter formatter() {
return new LTSVFormatter();
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/LTSVFormatter.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import am.ik.ltsv4j.exception.LTSVIOException;
/**
* @author making
*
*/
public class LTSVFormatter {
/**
*
*/
LTSVFormatter() {
}
/**
* @param line
* @return
*/
public String formatLine(Map<String, String> line) {
if (line == null) {
return "";
}
StringBuilder sb = new StringBuilder();
int i = 0;
for (Entry<String, String> e : line.entrySet()) {
sb.append(e.getKey()).append(LTSV.SEPARATOR).append(e.getValue());
if (++i < line.size()) {
sb.append(LTSV.TAB);
}
}
return sb.toString();
}
/**
* @param lines
* @param filepath
*/
public void formatLines(List<Map<String, String>> lines, String filepath) {
this.formatLines(lines, filepath, LTSV.DEFAULT_CHARSET);
}
public void formatLines(List<Map<String, String>> lines, String filepath,
String charsetName) {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(
filepath), charsetName)) {
this.formatLines(lines, writer);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param lines
* @param file
*/
public void formatLines(List<Map<String, String>> lines, File file) {
try (FileWriter writer = new FileWriter(file)) {
this.formatLines(lines, writer);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param lines
* @param outputStream
*/
public void formatLines(List<Map<String, String>> lines,
OutputStream outputStream) {
try (Writer writer = new OutputStreamWriter(outputStream)) {
this.formatLines(lines, writer);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param lines
* @param writer
*/
public void formatLines(List<Map<String, String>> lines, Writer writer) {
try (PrintWriter pw = new PrintWriter(new BufferedWriter(writer))) {
for (Map<String, String> line : lines) {
pw.println(formatLine(line));
}
}
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/LTSVIterator.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import am.ik.ltsv4j.exception.LTSVIOException;
/**
* @author making
*
*/
public class LTSVIterator implements Iterator<Map<String, String>>,
AutoCloseable {
private final BufferedReader bufferedReader;
private final LTSVParser parser;
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final Queue<Map<String, String>> nextQueue = new LinkedList<>();
LTSVIterator(BufferedReader bufferedReader, LTSVParser parser) {
this.bufferedReader = bufferedReader;
this.parser = parser;
}
@Override
public void close() throws LTSVIOException {
if (!isClosed.getAndSet(true)) {
synchronized (bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
}
}
@Override
public boolean hasNext() {
if (isClosed.get()) {
return false;
}
synchronized (bufferedReader) {
if (!nextQueue.isEmpty()) {
return true;
}
try {
String line = bufferedReader.readLine();
boolean hasNext = line != null;
if (hasNext) {
Map<String, String> next = parser.parseLine(line);
nextQueue.add(next);
}
return hasNext;
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
}
@Override
public Map<String, String> next() {
synchronized (bufferedReader) {
try {
Map<String, String> next;
if (nextQueue.isEmpty()) {
String line = bufferedReader.readLine();
next = parser.parseLine(line);
} else {
next = nextQueue.poll();
}
return next;
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/LTSVParser.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import am.ik.ltsv4j.exception.LTSVIOException;
import am.ik.ltsv4j.exception.LTSVParseException;
/**
* Parser for LTSV file.
*
* @author making
*
*/
public class LTSVParser {
/**
* separator pattern.
*/
private static final Pattern SEPARATOR_PATTERN = Pattern
.compile(LTSV.SEPARATOR);
private static final Pattern LABEL_PATTERN = Pattern
.compile("[0-9A-Za-z_\\.\\-]+");
private static final Pattern FIELD_PATTERN = Pattern
.compile("[\u0001-\u0008\u000b\u000c\u000e-\u00ff]*");
/**
* interface to create map which is an implementation of LTSV line
*/
public static interface MapFactory {
Map<String, String> createMap();
}
/**
*
*/
private static final MapFactory DFAULT_MAP_FACTORY = new MapFactory() {
@Override
public Map<String, String> createMap() {
return new LinkedHashMap<>();
}
};
/**
*
*/
private Set<String> wants;
/**
*
*/
private Set<String> ignores;
/**
*
*/
private MapFactory mapFactory = DFAULT_MAP_FACTORY;
/**
*
*/
private boolean isStrict = false;
/**
*
*/
LTSVParser() {
}
/**
* @param wants
* @return
*/
public LTSVParser wants(String... wants) {
this.wants = new HashSet<>(Arrays.asList(wants));
return this;
}
/**
* @param ignores
* @return
*/
public LTSVParser ignores(String... ignores) {
this.ignores = new HashSet<>(Arrays.asList(ignores));
return this;
}
/**
* @param mapFactory
* @return
*/
public LTSVParser mapFactory(MapFactory mapFactory) {
this.mapFactory = mapFactory;
return this;
}
/**
* @return
*/
public LTSVParser strict() {
this.isStrict = true;
return this;
}
/**
* @param reader
* @return
*/
public List<Map<String, String>> parseLines(Reader reader) {
List<Map<String, String>> result = new ArrayList<>();
try (LTSVIterator iterator = this.iterator(reader)) {
while (iterator.hasNext()) {
result.add(iterator.next());
}
}
return result;
}
/**
* @param in
* @return
*/
public List<Map<String, String>> parseLines(InputStream in) {
try (Reader reader = new InputStreamReader(in)) {
return this.parseLines(reader);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param file
* @return
*/
public List<Map<String, String>> parseLines(File file) {
try (FileReader reader = new FileReader(file)) {
return this.parseLines(reader);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param filePath
* @return
*/
public List<Map<String, String>> parseLines(String filePath) {
return parseLines(filePath, LTSV.DEFAULT_CHARSET);
}
/**
* @param filePath
* @param charsetName
* @return
*/
public List<Map<String, String>> parseLines(String filePath,
String charsetName) {
try (Reader reader = new InputStreamReader(
new FileInputStream(filePath), charsetName)) {
return this.parseLines(reader);
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param line
* @return
*/
public Map<String, String> parseLine(String line) {
if (line == null) {
throw new LTSVParseException("line must not be null.");
}
StringTokenizer tokenizer = new StringTokenizer(chomp(line), LTSV.TAB);
Map<String, String> result = mapFactory.createMap();
while (tokenizer.hasMoreTokens()) {
String labeledField = tokenizer.nextToken();
String[] values = SEPARATOR_PATTERN.split(labeledField, 2);
if (values.length != 2) {
throw new LTSVParseException("label and field (" + labeledField
+ ") are not separated by " + LTSV.SEPARATOR);
}
String label = values[0];
String field = values[1];
if (isStrict) {
validateLabel(label);
validateField(field);
}
if ((ignores != null && ignores.contains(label))
|| (wants != null && !wants.contains(label))) {
continue;
}
result.put(label, field);
}
return Collections.unmodifiableMap(result);
}
/**
* @param field
*/
private void validateField(String field) {
if (!FIELD_PATTERN.matcher(field).matches()) {
throw new LTSVParseException("field(" + field + ") is not valid.");
}
}
/**
* @param label
*/
private void validateLabel(String label) {
if (!LABEL_PATTERN.matcher(label).matches()) {
throw new LTSVParseException("field(" + label + ") is not valid.");
}
}
/**
* @param reader
* @return
*/
public LTSVIterator iterator(final Reader reader) {
return new LTSVIterator(new BufferedReader(reader), LTSVParser.this);
}
/**
* @param in
* @return
*/
public LTSVIterator iterator(InputStream in) {
return iterator(new InputStreamReader(in));
}
/**
* @param filePath
* @return
*/
public LTSVIterator iterator(String filePath) {
return iterator(filePath, LTSV.DEFAULT_CHARSET);
}
/**
* @param filePath
* @param charsetName
* @return
*/
public LTSVIterator iterator(String filePath, String charsetName) {
try {
return iterator(new InputStreamReader(
new FileInputStream(filePath), charsetName));
} catch (IOException e) {
throw new LTSVIOException(e);
}
}
/**
* @param str
* @return
*/
private static String chomp(String str) {
if (str == null || str.isEmpty()) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
if (ch == LTSV.CR || ch == LTSV.LF) {
return "";
}
return str;
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == LTSV.LF) {
if (str.charAt(lastIdx - 1) == LTSV.CR) {
lastIdx--;
}
} else if (last != LTSV.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/package-info.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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.
*/
/**
* core package for LTSV4J
*/
package am.ik.ltsv4j; |
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/exception/LTSVException.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j.exception;
@SuppressWarnings("serial")
public class LTSVException extends RuntimeException {
public LTSVException() {
super();
}
public LTSVException(String message, Throwable cause) {
super(message, cause);
}
public LTSVException(String message) {
super(message);
}
public LTSVException(Throwable cause) {
super(cause);
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/exception/LTSVIOException.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j.exception;
@SuppressWarnings("serial")
public class LTSVIOException extends LTSVException {
public LTSVIOException() {
super();
}
public LTSVIOException(String message, Throwable cause) {
super(message, cause);
}
public LTSVIOException(Throwable cause) {
super(cause);
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/exception/LTSVParseException.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.ltsv4j.exception;
@SuppressWarnings("serial")
public class LTSVParseException extends LTSVException {
public LTSVParseException() {
super();
}
public LTSVParseException(String message, Throwable cause) {
super(message, cause);
}
public LTSVParseException(String message) {
super(message);
}
public LTSVParseException(Throwable cause) {
super(cause);
}
}
|
0 | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j | java-sources/am/ik/ltsv4j/ltsv4j/0.9.0/am/ik/ltsv4j/exception/package-info.java | /*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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.
*/
/**
* Exception package for LTSV4J
*/
package am.ik.ltsv4j.exception; |
0 | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik/marked4j/Marked.java | /*
* Copyright (C) 2014-2019 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.marked4j;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class Marked implements Closeable {
private final boolean autoToc;
private final V8 v8;
private final V8Object marked;
public Marked(boolean gfm, boolean tables, boolean breaks, boolean pedantic,
boolean sanitize, boolean smartLists, boolean smartypants, String langPrefix,
boolean enableHeadingIdUriEncoding, boolean autoToc) {
this(autoToc);
try (ReleasableWrapper<V8Array> parameters = new ReleasableWrapper<>(new V8Array(this.v8));
ReleasableWrapper<V8Object> options = new ReleasableWrapper<>(new V8Object(this.v8)
.add("gfm", gfm)
.add("tables", tables)
.add("breaks", breaks)
.add("pedantic", pedantic)
.add("sanitize", sanitize)
.add("smartLists", smartLists)
.add("smartypants", smartypants)
.add("langPrefix", langPrefix))
) {
parameters.unwrap().push(options.unwrap());
this.marked.executeFunction("setOptions", parameters.unwrap());
}
if (enableHeadingIdUriEncoding) {
this.marked.executeFunction("enableHeadingIdUriEncoding", null);
}
}
public Marked(boolean autoToc) {
this.autoToc = autoToc;
this.v8 = V8.createV8Runtime();
try (InputStream marked = Marked.class.getClassLoader()
.getResourceAsStream("META-INF/resources/assets/marked/lib/marked.js");
InputStream lib = Marked.class.getClassLoader()
.getResourceAsStream("lib.js")) {
String js = copyToString(marked, StandardCharsets.UTF_8);
String script = copyToString(lib, StandardCharsets.UTF_8);
this.marked = this.v8.executeObjectScript(js + ";" + script);
} catch (IOException e) {
throw new IllegalStateException("marked.js is not found.", e);
}
}
public Marked() {
this(false);
}
@Override
public void close() {
if (this.marked != null) {
this.marked.release();
}
if (this.v8 != null) {
this.v8.release();
}
}
private String invoke(String function, String markdownText) {
try (ReleasableWrapper<V8Array> parameters = new ReleasableWrapper<>(new V8Array(this.v8));
) {
parameters.unwrap().push(markdownText);
return this.marked.executeStringFunction(function, parameters.unwrap());
}
}
public String marked(String markdownText) {
if (this.autoToc && markdownText.contains("<!-- toc -->")) {
markdownText = this.insertToc(markdownText);
}
return this.invoke("marked", markdownText);
}
public String toc(String markdownText) {
return this.invoke("toc", markdownText);
}
public String insertToc(String markdownText) {
return this.invoke("insertToc", markdownText);
}
private static String copyToString(InputStream in, Charset charset)
throws IOException {
StringBuilder out = new StringBuilder();
try (InputStreamReader reader = new InputStreamReader(in, charset);) {
char[] buffer = new char[4096];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, bytesRead);
}
return out.toString();
}
}
}
|
0 | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik/marked4j/MarkedBuilder.java | /*
* Copyright (C) 2014-2017 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.marked4j;
public class MarkedBuilder {
/**
* Enable GitHub flavored markdown.
*/
private boolean gfm = true;
/**
* Enable GFM tables. This option requires the gfm option to be true.
*/
private boolean tables = true;
/**
* Enable GFM line breaks. This option requires the gfm option to be true.
*/
private boolean breaks = false;
/**
* Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the
* original markdown bugs or poor behavior.
*/
private boolean pedantic = false;
/**
* Sanitize the output. Ignore any HTML that has been input.
*/
private boolean sanitize = false;
/**
* Use smarter list behavior than the original markdown. May eventually be default
* with the old behavior moved into pedantic.
*/
private boolean smartLists = true;
/**
* Use "smart" typograhic punctuation for things like quotes and dashes.
*/
private boolean smartypants = false;
/**
* Set the prefix for code block classes. Default: lang-
*/
private String langPrefix = "lang-";
private boolean enableHeadingIdUriEncoding = false;
private boolean autoToc = false;
/**
* Constructor.
*/
public MarkedBuilder() {
}
public MarkedBuilder gfm(boolean gfm) {
this.gfm = gfm;
return this;
}
public MarkedBuilder tables(boolean tables) {
this.tables = tables;
return this;
}
public MarkedBuilder breaks(boolean breaks) {
this.breaks = breaks;
return this;
}
public MarkedBuilder pedantic(boolean pedantic) {
this.pedantic = pedantic;
return this;
}
public MarkedBuilder sanitize(boolean sanitize) {
this.sanitize = sanitize;
return this;
}
public MarkedBuilder smartLists(boolean smartLists) {
this.smartLists = smartLists;
return this;
}
public MarkedBuilder smartypants(boolean smartypants) {
this.smartypants = smartypants;
return this;
}
public MarkedBuilder langPrefix(String langPrefix) {
this.langPrefix = langPrefix;
return this;
}
public MarkedBuilder enableHeadingIdUriEncoding(boolean enableHeadingIdUriEncoding) {
this.enableHeadingIdUriEncoding = enableHeadingIdUriEncoding;
return this;
}
public MarkedBuilder autoToc(boolean autoToc) {
this.autoToc = autoToc;
return this;
}
public Marked build() {
if (tables && !gfm) {
throw new IllegalStateException(
"'tables' option requires the 'gfm' option to be true.");
}
if (breaks && !gfm) {
throw new IllegalStateException(
"'breaks' option requires the 'gfm' option to be true.");
}
return new Marked(gfm, tables, breaks, pedantic, sanitize, smartLists,
smartypants, langPrefix, enableHeadingIdUriEncoding, autoToc);
}
}
|
0 | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik/marked4j/ReleasableWrapper.java | /*
* Copyright (C) 2014-2019 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.marked4j;
import com.eclipsesource.v8.Releasable;
import java.io.Closeable;
class ReleasableWrapper<T extends Releasable> implements Closeable {
private final T target;
ReleasableWrapper(T target) {
this.target = target;
}
final T unwrap() {
return this.target;
}
@Override
public final void close() {
this.target.release();
}
}
|
0 | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik | java-sources/am/ik/marked4j/marked4j/0.11.0/am/ik/marked4j/package-info.java | /*
* Copyright (C) 2014-2017 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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.
*/
/*
* Copyright (C) 2013 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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.
*/
/**
* core package for Marked4J
*/
package am.ik.marked4j; |
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/CursorPage.java | package am.ik.pagination;
import java.util.List;
import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonIgnore;
public record CursorPage<T, C>(List<T> content, int size, @JsonIgnore Function<T, C> toCursor, boolean hasPrevious,
boolean hasNext) {
public C tail() {
if (this.content.isEmpty()) {
return null;
}
return toCursor.apply(this.content.get(0));
}
public C head() {
if (this.content.isEmpty()) {
return null;
}
int size = this.content.size();
return toCursor.apply(this.content.get(size - 1));
}
}
|
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/CursorPageRequest.java | package am.ik.pagination;
import java.util.Optional;
public record CursorPageRequest<C>(C cursor, int pageSize, Navigation navigation) {
public Optional<C> cursorOptional() {
return Optional.ofNullable(this.cursor);
}
public enum Navigation {
NEXT, PREVIOUS;
public boolean isNext() {
return this == NEXT;
}
}
}
|
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/OffsetPage.java | package am.ik.pagination;
import java.util.List;
public record OffsetPage<T>(List<T> content, int size, int number, long totalElements) {
public long totalPages() {
return this.size == 0 ? 1 : (int) Math.ceil((double) this.totalElements / (double) this.size);
}
public boolean hasNext() {
return this.number + 1 < this.totalPages();
}
public boolean hasPrevious() {
return this.number > 0;
}
}
|
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/OffsetPageRequest.java | package am.ik.pagination;
public record OffsetPageRequest(int pageNumber, int pageSize) {
public int offset() {
return this.pageNumber * this.pageSize;
}
}
|
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/web/CursorPageRequestHandlerMethodArgumentResolver.java | package am.ik.pagination.web;
import java.util.function.Consumer;
import java.util.function.Function;
import am.ik.pagination.CursorPageRequest;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
public class CursorPageRequestHandlerMethodArgumentResolver<T> implements HandlerMethodArgumentResolver {
private final CursorPageRequestProperties<T> properties;
public CursorPageRequestHandlerMethodArgumentResolver(CursorPageRequestProperties<T> properties) {
this.properties = properties;
}
public CursorPageRequestHandlerMethodArgumentResolver(Function<String, T> paramToCursor,
Consumer<CursorPageRequestProperties.Builder<T>> consumer) {
final CursorPageRequestProperties.Builder<T> builder = CursorPageRequestProperties.builder(paramToCursor);
consumer.accept(builder);
this.properties = builder.build();
}
public CursorPageRequestHandlerMethodArgumentResolver(Function<String, T> paramToCursor) {
this(paramToCursor, __ -> {
});
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return CursorPageRequest.class.equals(parameter.getParameterType());
}
@Override
@NonNull
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
int size = this.properties.sizeDefault();
T cursor = null;
CursorPageRequest.Navigation navigation = this.properties.navigationDefault();
final String cursorParameter = webRequest.getParameter(this.properties.cursorParameterName());
if (StringUtils.hasText(cursorParameter)) {
cursor = this.properties.paramToCursor().apply(cursorParameter);
}
final String sizeParameter = webRequest.getParameter(this.properties.sizeParameterName());
if (sizeParameter != null) {
size = Integer.parseInt(sizeParameter);
}
final String navigationParameter = webRequest.getParameter(this.properties.navigationParameterName());
if (navigationParameter != null) {
navigation = CursorPageRequest.Navigation.valueOf(navigationParameter.toUpperCase());
}
return new CursorPageRequest<>(cursor, Math.max(1, Math.min(size, this.properties.sizeMax())), navigation);
}
} |
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/web/CursorPageRequestProperties.java | package am.ik.pagination.web;
import java.util.function.Function;
import am.ik.pagination.CursorPageRequest;
public record CursorPageRequestProperties<T>(Function<String, T> paramToCursor, String cursorParameterName,
String sizeParameterName, String navigationParameterName, int sizeDefault, int sizeMax,
CursorPageRequest.Navigation navigationDefault) {
public static <T> Builder<T> builder(Function<String, T> paramToCursor) {
return new Builder<>(paramToCursor);
}
public static class Builder<T> {
private final Function<String, T> paramToCursor;
private String cursorParameterName = "cursor";
private String sizeParameterName = "size";
private String navigationParameterName = "navigation";
private int sizeDefault = 20;
private int sizeMax = 200;
private CursorPageRequest.Navigation navigationDefault = CursorPageRequest.Navigation.NEXT;
public Builder(Function<String, T> paramToCursor) {
this.paramToCursor = paramToCursor;
}
public Builder<T> withCursorParameterName(String cursorParameterName) {
this.cursorParameterName = cursorParameterName;
return this;
}
public Builder<T> withSizeParameterName(String sizeParameterName) {
this.sizeParameterName = sizeParameterName;
return this;
}
public Builder<T> withSizeDefault(int sizeDefault) {
this.sizeDefault = sizeDefault;
return this;
}
public Builder<T> withSizeMax(int sizeMax) {
this.sizeMax = sizeMax;
return this;
}
public Builder<T> withNavigationParameterName(String navigationParameterName) {
this.navigationParameterName = navigationParameterName;
return this;
}
public Builder<T> withNavigationDefault(CursorPageRequest.Navigation navigationDefault) {
this.navigationDefault = navigationDefault;
return this;
}
public CursorPageRequestProperties<T> build() {
return new CursorPageRequestProperties<>(paramToCursor, cursorParameterName, sizeParameterName,
navigationParameterName, sizeDefault, sizeMax, navigationDefault);
}
}
}
|
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/web/OffsetPageRequestHandlerMethodArgumentResolver.java | package am.ik.pagination.web;
import java.util.function.Consumer;
import am.ik.pagination.OffsetPageRequest;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
public class OffsetPageRequestHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
private final OffsetPageRequestProperties properties;
public OffsetPageRequestHandlerMethodArgumentResolver(OffsetPageRequestProperties properties) {
this.properties = properties;
}
public OffsetPageRequestHandlerMethodArgumentResolver(Consumer<OffsetPageRequestProperties.Builder> consumer) {
final OffsetPageRequestProperties.Builder builder = OffsetPageRequestProperties.builder();
consumer.accept(builder);
this.properties = builder.build();
}
public OffsetPageRequestHandlerMethodArgumentResolver() {
this(__ -> {
});
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return OffsetPageRequest.class.equals(parameter.getParameterType());
}
@Override
@NonNull
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
int page = this.properties.pageDefault();
int size = this.properties.sizeDefault();
final String pageParameter = webRequest.getParameter(this.properties.pageParameterName());
if (pageParameter != null) {
page = Integer.parseInt(pageParameter);
}
final String sizeParameter = webRequest.getParameter(this.properties.sizeParameterName());
if (sizeParameter != null) {
size = Integer.parseInt(sizeParameter);
}
return new OffsetPageRequest(Math.max(0, page), Math.max(1, Math.min(size, this.properties.sizeMax())));
}
} |
0 | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination | java-sources/am/ik/pagination/pagination/0.2.0/am/ik/pagination/web/OffsetPageRequestProperties.java | package am.ik.pagination.web;
public record OffsetPageRequestProperties(String pageParameterName, String sizeParameterName, int pageDefault,
int sizeDefault, int sizeMax) {
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String pageParameterName = "page";
private String sizeParameterName = "size";
private int pageDefault = 0;
private int sizeDefault = 20;
private int sizeMax = 200;
public Builder withPageParameterName(String pageParameterName) {
this.pageParameterName = pageParameterName;
return this;
}
public Builder withSizeParameterName(String sizeParameterName) {
this.sizeParameterName = sizeParameterName;
return this;
}
public Builder withPageDefault(int pageDefault) {
this.pageDefault = pageDefault;
return this;
}
public Builder withSizeDefault(int sizeDefault) {
this.sizeDefault = sizeDefault;
return this;
}
public Builder withSizeMax(int sizeMax) {
this.sizeMax = sizeMax;
return this;
}
public OffsetPageRequestProperties build() {
return new OffsetPageRequestProperties(pageParameterName, sizeParameterName, pageDefault, sizeDefault,
sizeMax);
}
}
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/Query.java | package am.ik.query;
import am.ik.query.ast.AndNode;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.NodeVisitor;
import am.ik.query.ast.NotNode;
import am.ik.query.ast.OrNode;
import am.ik.query.ast.PhraseNode;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.ast.WildcardNode;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Represents a parsed search query with its AST structure. Provides fluent API for query
* manipulation and traversal.
*
* @author Toshiaki Maki
*/
public final class Query {
private final String originalQuery;
private final Node rootNode;
public Query(String originalQuery, Node rootNode) {
this.originalQuery = Objects.requireNonNull(originalQuery, "originalQuery must not be null");
this.rootNode = Objects.requireNonNull(rootNode, "rootNode must not be null");
}
/**
* Gets the original query string.
* @return the original query string
*/
public String originalQuery() {
return originalQuery;
}
/**
* Gets the root node of the AST.
* @return the root node
*/
public Node rootNode() {
return rootNode;
}
/**
* Accepts a visitor to traverse the query AST.
* @param visitor the visitor to accept
* @param <T> the return type of the visitor
* @return the result of the visitor
*/
public <T> T accept(NodeVisitor<T> visitor) {
return rootNode.accept(visitor);
}
/**
* Walks through all nodes in the query AST.
* @param consumer the consumer to apply to each node
*/
public void walk(Consumer<Node> consumer) {
rootNode.walk(consumer);
}
/**
* Transforms this query using the given transformer function.
* @param transformer the query transformer function
* @return the transformed query
*/
public Query transform(Function<Query, Query> transformer) {
return transformer.apply(this);
}
/**
* Converts this query back to a string representation.
* @return the string representation of the query
*/
@Override
public String toString() {
return this.rootNode().accept(new SerializerVisitor());
}
/**
* Extracts all tokens of the specified type.
* @param tokenType the token type to extract
* @return list of matching tokens
*/
public List<Token> extractTokens(TokenType tokenType) {
List<Token> tokens = new ArrayList<>();
extractTokensWithContext(rootNode, tokenType, tokens, false);
return tokens;
}
private static void extractTokensWithContext(Node node, TokenType tokenType, List<Token> tokens,
boolean insideNot) {
if (node instanceof NotNode notNode) {
// Mark that we're inside a NOT node
extractTokensWithContext(notNode.child(), tokenType, tokens, true);
}
else if (node.isLeaf()) {
switch (tokenType) {
case KEYWORD:
if (!insideNot && node instanceof TokenNode tokenNode && tokenNode.type() == TokenType.KEYWORD) {
tokens.add(tokenNode.token());
}
break;
case PHRASE:
if (!insideNot && node instanceof PhraseNode phraseNode) {
tokens.add(phraseNode.token());
}
break;
case EXCLUDE:
if (insideNot) {
if (node instanceof TokenNode tokenNode) {
tokens.add(new Token(TokenType.EXCLUDE, tokenNode.value()));
}
else if (node instanceof PhraseNode phraseNode) {
tokens.add(new Token(TokenType.EXCLUDE, phraseNode.phrase()));
}
}
break;
case WILDCARD:
if (!insideNot && node instanceof WildcardNode wildcardNode) {
tokens.add(new Token(TokenType.WILDCARD, wildcardNode.pattern()));
}
break;
default:
if (!insideNot && node instanceof TokenNode tokenNode && tokenNode.type() == tokenType) {
tokens.add(tokenNode.token());
}
}
}
else {
// Recurse for non-leaf nodes
for (Node child : node.children()) {
extractTokensWithContext(child, tokenType, tokens, insideNot);
}
}
}
/**
* Extracts all keywords from the query.
* @return list of keyword tokens
*/
public List<String> extractKeywords() {
return extractTokens(TokenType.KEYWORD).stream().map(Token::value).toList();
}
/**
* Extracts all phrases from the query.
* @return list of phrase tokens
*/
public List<String> extractPhrases() {
return extractTokens(TokenType.PHRASE).stream().map(Token::value).toList();
}
/**
* Extracts all excluded terms from the query.
* @return list of excluded terms
*/
public List<String> extractExclusions() {
return extractTokens(TokenType.EXCLUDE).stream().map(Token::value).toList();
}
/**
* Extracts all wildcard patterns from the query.
* @return list of wildcard patterns
*/
public List<String> extractWildcards() {
return extractTokens(TokenType.WILDCARD).stream().map(Token::value).toList();
}
/**
* Extracts all field queries from the query.
* @return map of field names to their values
*/
public Map<String, List<String>> extractFields() {
Map<String, List<String>> fields = new HashMap<>();
rootNode.walk(node -> {
if (node instanceof FieldNode fieldNode) {
fields.computeIfAbsent(fieldNode.field(), k -> new ArrayList<>()).add(fieldNode.fieldValue());
}
});
return fields;
}
/**
* Checks if the query is empty (contains no meaningful tokens).
* @return true if the query is empty
*/
public boolean isEmpty() {
final boolean[] hasContent = { false };
rootNode.walk(node -> {
if (!hasContent[0]) {
if (node instanceof TokenNode tokenNode) {
TokenType type = tokenNode.type();
if (type.isContent() || type == TokenType.EXCLUDE) {
hasContent[0] = true;
}
}
else if (node instanceof PhraseNode || node instanceof FieldNode || node instanceof WildcardNode
|| node instanceof FuzzyNode || node instanceof RangeNode || node instanceof NotNode) {
hasContent[0] = true;
}
}
});
return !hasContent[0];
}
/**
* Counts nodes of a specific type.
* @param nodeClass the node class to count
* @return the count
*/
private int countNodesOfType(Class<? extends Node> nodeClass) {
final int[] count = { 0 };
rootNode.walk(node -> {
if (nodeClass.isInstance(node)) {
count[0]++;
}
});
return count[0];
}
/**
* Finds all nodes of a specific type.
* @param nodeClass the node class to find
* @param <T> the node type
* @return list of matching nodes
*/
@SuppressWarnings("unchecked")
public <T extends Node> List<T> findNodes(Class<T> nodeClass) {
List<T> nodes = new ArrayList<>();
rootNode.walk(node -> {
if (nodeClass.isInstance(node)) {
nodes.add((T) node);
}
});
return nodes;
}
/**
* Counts nodes of a specific type (public version).
* @param nodeClass the node class to count
* @return the count
*/
public int countNodes(Class<? extends Node> nodeClass) {
return countNodesOfType(nodeClass);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Query query))
return false;
return Objects.equals(originalQuery, query.originalQuery) && Objects.equals(rootNode, query.rootNode);
}
@Override
public int hashCode() {
return Objects.hash(originalQuery, rootNode);
}
private static class SerializerVisitor implements NodeVisitor<String> {
@Override
public String visitToken(TokenNode node) {
switch (node.type()) {
case EXCLUDE:
return "-" + node.value();
case REQUIRED:
return "+" + node.value();
default:
return node.value();
}
}
@Override
public String visitRoot(RootNode node) {
return String.join(" ", node.children().stream().map(child -> child.accept(this)).toList());
}
@Override
public String visitAnd(AndNode node) {
String content = String.join(" AND ", node.children().stream().map(child -> child.accept(this)).toList());
return node.parent() != null ? "(" + content + ")" : content;
}
@Override
public String visitOr(OrNode node) {
String content = String.join(" OR ", node.children().stream().map(child -> child.accept(this)).toList());
return node.parent() != null ? "(" + content + ")" : content;
}
@Override
public String visitNot(NotNode node) {
String child = node.child().accept(this);
if (node.child() instanceof TokenNode) {
return "-" + child;
}
return "NOT " + child;
}
@Override
public String visitField(FieldNode node) {
String value = node.fieldValue();
// Quote value if it contains spaces
if (value.contains(" ")) {
value = "\"" + value + "\"";
}
return node.field() + ":" + value;
}
@Override
public String visitPhrase(PhraseNode node) {
return "\"" + node.phrase() + "\"";
}
@Override
public String visitWildcard(WildcardNode node) {
return node.pattern();
}
@Override
public String visitFuzzy(FuzzyNode node) {
return node.term() + "~" + (node.maxEdits() != 2 ? node.maxEdits() : "");
}
@Override
public String visitRange(RangeNode node) {
String startBracket = node.includeStart() ? "[" : "{";
String endBracket = node.includeEnd() ? "]" : "}";
String range = startBracket + node.start() + " TO " + node.end() + endBracket;
return node.field() != null ? node.field() + ":" + range : range;
}
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/AndNode.java | package am.ik.query.ast;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents an AND operation node in the query AST. All children must match for this
* node to match.
*
* @author Toshiaki Maki
*/
public final class AndNode implements Node {
private final List<Node> children;
private Node parent;
public AndNode(List<Node> children) {
this.children = List.copyOf(Objects.requireNonNull(children, "children must not be null"));
this.children.forEach(child -> child.setParent(this));
}
@Override
public String value() {
return "AND";
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitAnd(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
children.forEach(child -> child.walk(consumer));
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public List<Node> children() {
return children;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AndNode andNode))
return false;
return Objects.equals(children, andNode.children);
}
@Override
public int hashCode() {
return Objects.hash(children);
}
@Override
public String toString() {
return "AndNode{children=" + children + '}';
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/BaseNodeVisitor.java | package am.ik.query.ast;
/**
* Base implementation of NodeVisitor with default behavior. Subclasses can override only
* the methods they need.
*
* @param <T> the return type of visit operations
* @author Toshiaki Maki
*/
public abstract class BaseNodeVisitor<T> implements NodeVisitor<T> {
protected abstract T defaultValue();
@Override
public T visitToken(TokenNode node) {
return defaultValue();
}
@Override
public T visitRoot(RootNode node) {
for (Node child : node.children()) {
child.accept(this);
}
return defaultValue();
}
@Override
public T visitAnd(AndNode node) {
for (Node child : node.children()) {
child.accept(this);
}
return defaultValue();
}
@Override
public T visitOr(OrNode node) {
for (Node child : node.children()) {
child.accept(this);
}
return defaultValue();
}
@Override
public T visitNot(NotNode node) {
node.child().accept(this);
return defaultValue();
}
@Override
public T visitField(FieldNode node) {
return defaultValue();
}
@Override
public T visitPhrase(PhraseNode node) {
return defaultValue();
}
@Override
public T visitWildcard(WildcardNode node) {
return defaultValue();
}
@Override
public T visitFuzzy(FuzzyNode node) {
return defaultValue();
}
@Override
public T visitRange(RangeNode node) {
return defaultValue();
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/FieldNode.java | package am.ik.query.ast;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a field query node in the AST. Format: field:value
*
* @author Toshiaki Maki
*/
public final class FieldNode implements Node {
private final String field;
private final String value;
private final Token token;
private Node parent;
public FieldNode(String field, String value, Token token) {
this.field = Objects.requireNonNull(field, "field must not be null");
this.value = Objects.requireNonNull(value, "value must not be null");
this.token = Objects.requireNonNull(token, "token must not be null");
}
public FieldNode(String field, String value) {
this(field, value, new Token(TokenType.FIELD, field + ":" + value));
}
@Override
public String value() {
return field + ":" + value;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitField(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public String field() {
return field;
}
public String fieldValue() {
return value;
}
public Token token() {
return token;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof FieldNode fieldNode))
return false;
return Objects.equals(field, fieldNode.field) && Objects.equals(value, fieldNode.value);
}
@Override
public int hashCode() {
return Objects.hash(field, value);
}
@Override
public String toString() {
return "FieldNode{field='" + field + "', value='" + value + "'}";
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/FuzzyNode.java | package am.ik.query.ast;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a fuzzy query node in the AST. Fuzzy queries match terms within a certain
* edit distance.
*
* @author Toshiaki Maki
*/
public final class FuzzyNode implements Node {
private final String term;
private final int maxEdits;
private final Token token;
private Node parent;
public FuzzyNode(String term, int maxEdits, Token token) {
this.term = Objects.requireNonNull(term, "term must not be null");
if (maxEdits < 0 || maxEdits > 2) {
throw new IllegalArgumentException("maxEdits must be between 0 and 2");
}
this.maxEdits = maxEdits;
this.token = Objects.requireNonNull(token, "token must not be null");
}
public FuzzyNode(String term, int maxEdits) {
this(term, maxEdits, new Token(TokenType.FUZZY, term + "~" + maxEdits));
}
public FuzzyNode(String term) {
this(term, 2);
}
@Override
public String value() {
return term + "~" + maxEdits;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitFuzzy(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public String term() {
return term;
}
public int maxEdits() {
return maxEdits;
}
public Token token() {
return token;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof FuzzyNode fuzzyNode))
return false;
return maxEdits == fuzzyNode.maxEdits && Objects.equals(term, fuzzyNode.term);
}
@Override
public int hashCode() {
return Objects.hash(term, maxEdits);
}
@Override
public String toString() {
return "FuzzyNode{term='" + term + "', maxEdits=" + maxEdits + '}';
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/Node.java | package am.ik.query.ast;
import java.util.List;
import java.util.function.Consumer;
/**
* Base interface for all AST nodes in a query. This is a sealed interface to ensure type
* safety and exhaustive pattern matching.
*
* @author Toshiaki Maki
*/
public sealed interface Node permits RootNode, TokenNode, AndNode, OrNode, NotNode, FieldNode, PhraseNode, WildcardNode,
FuzzyNode, RangeNode {
/**
* Gets the string value representation of this node.
* @return the node value
*/
String value();
/**
* Accepts a visitor for this node.
* @param visitor the visitor to accept
* @param <T> the return type of the visitor
* @return the result of the visitor
*/
<T> T accept(NodeVisitor<T> visitor);
/**
* Walks through this node and all its children.
* @param consumer the consumer to apply to each node
*/
void walk(Consumer<Node> consumer);
/**
* Gets the parent node of this node.
* @return the parent node, or null if this is the root
*/
Node parent();
/**
* Sets the parent node of this node.
* @param parent the parent node
*/
void setParent(Node parent);
/**
* Checks if this is a leaf node (has no children).
* @return true if this is a leaf node
*/
default boolean isLeaf() {
return this instanceof TokenNode || this instanceof FieldNode || this instanceof PhraseNode
|| this instanceof WildcardNode || this instanceof FuzzyNode;
}
/**
* Checks if this is a group node (has children).
* @return true if this is a group node
*/
default boolean isGroup() {
return !isLeaf();
}
/**
* Gets the children of this node.
* @return list of child nodes, or empty list if leaf node
*/
default List<Node> children() {
return List.of();
}
/**
* Gets the depth of this node in the AST.
* @return the depth (0 for root)
*/
default int depth() {
int depth = 0;
Node current = parent();
while (current != null) {
depth++;
current = current.parent();
}
return depth;
}
/**
* Utility method to print a node tree.
* @param node the root node to print
* @deprecated Use Query.prettyPrint() instead
*/
@Deprecated(since = "2.0", forRemoval = true)
static void print(RootNode node) {
print(node, 0);
}
/**
* Utility method to print a node with indentation.
* @param node the node to print
* @param level the indentation level
* @deprecated Use Query.prettyPrint() instead
*/
@Deprecated(since = "2.0", forRemoval = true)
static void print(Node node, int level) {
if (node instanceof TokenNode) {
System.out.println("\t".repeat(level) + node);
}
else if (node instanceof RootNode) {
System.out.println("\t".repeat(level) + node);
List<Node> children = ((RootNode) node).children();
if (!children.isEmpty()) {
children.forEach(c -> print(c, level + 1));
}
}
}
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/NodeVisitor.java | package am.ik.query.ast;
/**
* Visitor interface for traversing query AST nodes. Implements the visitor pattern for
* type-safe node traversal.
*
* @param <T> the return type of visit operations
* @author Toshiaki Maki
*/
public interface NodeVisitor<T> {
/**
* Visits a token node.
* @param node the token node to visit
* @return the result of visiting the node
*/
T visitToken(TokenNode node);
/**
* Visits a root/group node.
* @param node the root node to visit
* @return the result of visiting the node
*/
T visitRoot(RootNode node);
/**
* Visits an AND node.
* @param node the AND node to visit
* @return the result of visiting the node
*/
T visitAnd(AndNode node);
/**
* Visits an OR node.
* @param node the OR node to visit
* @return the result of visiting the node
*/
T visitOr(OrNode node);
/**
* Visits a NOT node.
* @param node the NOT node to visit
* @return the result of visiting the node
*/
T visitNot(NotNode node);
/**
* Visits a field query node.
* @param node the field node to visit
* @return the result of visiting the node
*/
T visitField(FieldNode node);
/**
* Visits a phrase query node.
* @param node the phrase node to visit
* @return the result of visiting the node
*/
T visitPhrase(PhraseNode node);
/**
* Visits a wildcard query node.
* @param node the wildcard node to visit
* @return the result of visiting the node
*/
T visitWildcard(WildcardNode node);
/**
* Visits a fuzzy query node.
* @param node the fuzzy node to visit
* @return the result of visiting the node
*/
T visitFuzzy(FuzzyNode node);
/**
* Visits a range query node.
* @param node the range node to visit
* @return the result of visiting the node
*/
T visitRange(RangeNode node);
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/NotNode.java | package am.ik.query.ast;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a NOT operation node in the query AST. The child must not match for this
* node to match.
*
* @author Toshiaki Maki
*/
public final class NotNode implements Node {
private final Node child;
private Node parent;
public NotNode(Node child) {
this.child = Objects.requireNonNull(child, "child must not be null");
this.child.setParent(this);
}
@Override
public String value() {
return "NOT";
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitNot(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
child.walk(consumer);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public List<Node> children() {
return List.of(child);
}
public Node child() {
return child;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NotNode notNode))
return false;
return Objects.equals(child, notNode.child);
}
@Override
public int hashCode() {
return Objects.hash(child);
}
@Override
public String toString() {
return "NotNode{child=" + child + '}';
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/OrNode.java | package am.ik.query.ast;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents an OR operation node in the query AST. At least one child must match for
* this node to match.
*
* @author Toshiaki Maki
*/
public final class OrNode implements Node {
private final List<Node> children;
private Node parent;
public OrNode(List<Node> children) {
this.children = List.copyOf(Objects.requireNonNull(children, "children must not be null"));
this.children.forEach(child -> child.setParent(this));
}
@Override
public String value() {
return "OR";
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitOr(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
children.forEach(child -> child.walk(consumer));
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public List<Node> children() {
return children;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OrNode orNode))
return false;
return Objects.equals(children, orNode.children);
}
@Override
public int hashCode() {
return Objects.hash(children);
}
@Override
public String toString() {
return "OrNode{children=" + children + '}';
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/PhraseNode.java | package am.ik.query.ast;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a phrase query node in the AST. Phrases are exact matches of multiple terms.
*
* @author Toshiaki Maki
*/
public final class PhraseNode implements Node {
private final String phrase;
private final Token token;
private Node parent;
public PhraseNode(String phrase, Token token) {
this.phrase = Objects.requireNonNull(phrase, "phrase must not be null");
this.token = Objects.requireNonNull(token, "token must not be null");
}
public PhraseNode(String phrase) {
this(phrase, new Token(TokenType.PHRASE, phrase));
}
@Override
public String value() {
return phrase;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitPhrase(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public String phrase() {
return phrase;
}
public Token token() {
return token;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PhraseNode that))
return false;
return Objects.equals(phrase, that.phrase);
}
@Override
public int hashCode() {
return Objects.hash(phrase);
}
@Override
public String toString() {
return "PhraseNode{phrase='" + phrase + "'}";
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/RangeNode.java | package am.ik.query.ast;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a range query node in the AST. Format: [start TO end] or {start TO end}
*
* @author Toshiaki Maki
*/
public final class RangeNode implements Node {
private final String start;
private final String end;
private final boolean includeStart;
private final boolean includeEnd;
private final String field;
private Node parent;
private RangeNode(Builder builder) {
this.start = builder.start;
this.end = builder.end;
this.includeStart = builder.includeStart;
this.includeEnd = builder.includeEnd;
this.field = builder.field;
}
@Override
public String value() {
String startBracket = includeStart ? "[" : "{";
String endBracket = includeEnd ? "]" : "}";
String range = startBracket + start + " TO " + end + endBracket;
return field != null ? field + ":" + range : range;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitRange(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public String start() {
return start;
}
public String end() {
return end;
}
public boolean includeStart() {
return includeStart;
}
public boolean includeEnd() {
return includeEnd;
}
public String field() {
return field;
}
public static Builder builder() {
return new Builder();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof RangeNode rangeNode))
return false;
return includeStart == rangeNode.includeStart && includeEnd == rangeNode.includeEnd
&& Objects.equals(start, rangeNode.start) && Objects.equals(end, rangeNode.end)
&& Objects.equals(field, rangeNode.field);
}
@Override
public int hashCode() {
return Objects.hash(start, end, includeStart, includeEnd, field);
}
@Override
public String toString() {
return "RangeNode{" + "start='" + start + '\'' + ", end='" + end + '\'' + ", includeStart=" + includeStart
+ ", includeEnd=" + includeEnd + ", field='" + field + '\'' + '}';
}
public static class Builder {
private String start;
private String end;
private boolean includeStart = true;
private boolean includeEnd = true;
private String field;
private Builder() {
}
public Builder start(String start) {
this.start = Objects.requireNonNull(start, "start must not be null");
return this;
}
public Builder end(String end) {
this.end = Objects.requireNonNull(end, "end must not be null");
return this;
}
public Builder includeStart(boolean includeStart) {
this.includeStart = includeStart;
return this;
}
public Builder includeEnd(boolean includeEnd) {
this.includeEnd = includeEnd;
return this;
}
public Builder field(String field) {
this.field = field;
return this;
}
public RangeNode build() {
Objects.requireNonNull(start, "start must not be null");
Objects.requireNonNull(end, "end must not be null");
return new RangeNode(this);
}
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/RootNode.java | package am.ik.query.ast;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents the root node of a query AST. Acts as a container for top-level query
* elements.
*
* @author Toshiaki Maki
*/
public final class RootNode implements Node {
private final List<Node> children;
private Node parent;
public RootNode() {
this.children = new ArrayList<>();
}
public RootNode(List<Node> children) {
this.children = new ArrayList<>(Objects.requireNonNull(children, "children must not be null"));
this.children.forEach(child -> child.setParent(this));
}
@Override
public String value() {
return "root";
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitRoot(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
children.forEach(child -> child.walk(consumer));
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public List<Node> children() {
return this.children;
}
public boolean hasChildren() {
return !this.children.isEmpty();
}
public void addChild(Node child) {
Objects.requireNonNull(child, "child must not be null");
this.children.add(child);
child.setParent(this);
}
public void addChildren(List<Node> children) {
Objects.requireNonNull(children, "children must not be null");
children.forEach(this::addChild);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof RootNode rootNode))
return false;
return Objects.equals(children, rootNode.children);
}
@Override
public int hashCode() {
return Objects.hash(children);
}
@Override
public String toString() {
return "RootNode{children=" + children + '}';
}
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/TokenNode.java | package am.ik.query.ast;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a token node in the query AST. This is a leaf node containing a single
* token.
*
* @author Toshiaki Maki
*/
public final class TokenNode implements Node {
private final TokenType type;
private final String value;
private final Token token;
private Node parent;
public TokenNode(TokenType type, String value) {
this.type = Objects.requireNonNull(type, "type must not be null");
this.value = Objects.requireNonNull(value, "value must not be null");
this.token = new Token(type, value);
}
public TokenNode(Token token) {
this.token = Objects.requireNonNull(token, "token must not be null");
this.type = token.type();
this.value = token.value();
}
@Override
public String value() {
return value;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitToken(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public TokenType type() {
return type;
}
public Token token() {
return token;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TokenNode tokenNode))
return false;
return type == tokenNode.type && Objects.equals(value, tokenNode.value);
}
@Override
public int hashCode() {
return Objects.hash(type, value);
}
@Override
public String toString() {
return "TokenNode{type=" + type + ", value='" + value + "'}";
}
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/ast/WildcardNode.java | package am.ik.query.ast;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Represents a wildcard query node in the AST. Supports * (zero or more chars) and ?
* (single char) wildcards.
*
* @author Toshiaki Maki
*/
public final class WildcardNode implements Node {
private final String pattern;
private final Token token;
private Node parent;
public WildcardNode(String pattern, Token token) {
this.pattern = Objects.requireNonNull(pattern, "pattern must not be null");
this.token = Objects.requireNonNull(token, "token must not be null");
}
public WildcardNode(String pattern) {
this(pattern, new Token(TokenType.WILDCARD, pattern));
}
@Override
public String value() {
return pattern;
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return visitor.visitWildcard(this);
}
@Override
public void walk(Consumer<Node> consumer) {
consumer.accept(this);
}
@Override
public Node parent() {
return parent;
}
@Override
public void setParent(Node parent) {
this.parent = parent;
}
public String pattern() {
return pattern;
}
public Token token() {
return token;
}
/**
* Checks if this wildcard pattern contains any wildcard characters.
* @return true if pattern contains * or ?
*/
public boolean hasWildcards() {
return pattern.contains("*") || pattern.contains("?");
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof WildcardNode that))
return false;
return Objects.equals(pattern, that.pattern);
}
@Override
public int hashCode() {
return Objects.hash(pattern);
}
@Override
public String toString() {
return "WildcardNode{pattern='" + pattern + "'}";
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/lexer/LegacyQueryLexer.java | package am.ik.query.lexer;
import java.util.ArrayList;
import java.util.List;
/**
* Legacy lexer for backward compatibility.
*
* @author Toshiaki Maki
* @deprecated Use QueryLexer instead
*/
@Deprecated(since = "0.2.0", forRemoval = true)
public class LegacyQueryLexer {
private final String input;
public LegacyQueryLexer(String input) {
this.input = input;
}
public List<Token> tokenize() {
List<Token> tokens = new ArrayList<>();
if (input == null || input.isEmpty()) {
return tokens;
}
int i = 0;
while (i < input.length()) {
char c = input.charAt(i);
// Skip whitespace
if (Character.isWhitespace(c)) {
i++;
continue;
}
// Handle quotes
if (c == '"') {
i++; // skip opening quote
int start = i;
while (i < input.length() && input.charAt(i) != '"') {
i++;
}
String value = input.substring(start, i);
tokens.add(new Token(TokenType.PHRASE, value));
if (i < input.length()) {
i++; // skip closing quote
}
continue;
}
// Handle parentheses
if (c == '(') {
tokens.add(new Token(TokenType.LPAREN, "("));
i++;
continue;
}
if (c == ')') {
tokens.add(new Token(TokenType.RPAREN, ")"));
i++;
continue;
}
// Handle exclusion
if (c == '-' && i + 1 < input.length() && Character.isLetterOrDigit(input.charAt(i + 1))) {
i++; // skip minus
int start = i;
while (i < input.length() && !Character.isWhitespace(input.charAt(i)) && input.charAt(i) != ')'
&& input.charAt(i) != '"') {
i++;
}
String value = input.substring(start, i);
tokens.add(new Token(TokenType.EXCLUDE, value));
continue;
}
// Handle keywords and operators
int start = i;
while (i < input.length() && !Character.isWhitespace(input.charAt(i)) && input.charAt(i) != '('
&& input.charAt(i) != ')') {
// Check for quoted value after equals
if (input.charAt(i) == '=' && i + 1 < input.length() && input.charAt(i + 1) == '"') {
i++; // include =
i++; // skip opening quote
while (i < input.length() && input.charAt(i) != '"') {
i++;
}
if (i < input.length()) {
i++; // include closing quote
}
break;
}
else if (input.charAt(i) == '"') {
break;
}
i++;
}
String value = input.substring(start, i);
// Check for OR operator
if ("or".equalsIgnoreCase(value) || "OR".equals(value)) {
tokens.add(new Token(TokenType.OR, value));
}
else if ("and".equalsIgnoreCase(value) || "AND".equals(value)) {
tokens.add(new Token(TokenType.AND, value));
}
else if ("not".equalsIgnoreCase(value) || "NOT".equals(value)) {
tokens.add(new Token(TokenType.NOT, value));
}
else {
tokens.add(new Token(TokenType.KEYWORD, value));
}
}
return tokens;
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/lexer/QueryLexer.java | package am.ik.query.lexer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Query lexer with support for advanced query features.
*
* @author Toshiaki Maki
*/
public class QueryLexer {
private static final Set<String> BOOLEAN_OPERATORS = Set.of("AND", "OR", "NOT");
private String input;
private int position;
private int length;
private List<Token> tokens;
public List<Token> tokenize(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
this.input = input;
this.position = 0;
this.length = input.length();
this.tokens = new ArrayList<>();
while (!isAtEnd()) {
scanToken();
}
// Add EOF token
tokens.add(new Token(TokenType.EOF, ""));
return tokens;
}
private void scanToken() {
char c = advance();
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
whitespace();
break;
case '"':
phrase();
break;
case '(':
addToken(TokenType.LPAREN, "(");
break;
case ')':
addToken(TokenType.RPAREN, ")");
break;
case '[':
addToken(TokenType.RANGE_START, "[");
break;
case ']':
addToken(TokenType.RANGE_END, "]");
break;
case '{':
addToken(TokenType.RANGE_START, "{");
break;
case '}':
addToken(TokenType.RANGE_END, "}");
break;
case ':':
addToken(TokenType.COLON, ":");
break;
case '+':
addToken(TokenType.REQUIRED, "+");
break;
case '-':
minus();
break;
case '*':
if (isWordChar(peek())) {
keyword(); // Part of a word
}
else {
addToken(TokenType.WILDCARD, "*");
}
break;
case '?':
if (isWordChar(peek())) {
keyword(); // Part of a word
}
else {
addToken(TokenType.WILDCARD, "?");
}
break;
case '~':
addToken(TokenType.FUZZY, "~");
break;
case '^':
addToken(TokenType.BOOST, "^");
break;
default:
if (isWordStart(c)) {
keyword();
}
else {
// Skip unknown character
}
}
}
private void whitespace() {
int start = position - 1;
while (Character.isWhitespace(peek())) {
advance();
}
addToken(TokenType.WHITESPACE, input.substring(start, position));
}
private void phrase() {
int start = position - 1;
while (peek() != '"' && !isAtEnd()) {
advance();
}
if (isAtEnd()) {
// Unterminated phrase
addToken(TokenType.PHRASE, input.substring(start + 1));
}
else {
// Consume closing "
advance();
addToken(TokenType.PHRASE, input.substring(start + 1, position - 1));
}
}
private void minus() {
// Check if this is an exclusion operator or part of a hyphenated word
if (position > 1 && isWordChar(input.charAt(position - 2)) && isWordChar(peek())) {
// Part of hyphenated word like "e-mail"
keyword();
}
else if (isWordChar(peek())) {
// Exclusion operator followed by a word
int start = position - 1;
while (isWordChar(peek()) || peek() == '*' || peek() == '?') {
advance();
}
String value = input.substring(start + 1, position); // Skip the minus
addToken(TokenType.EXCLUDE, value);
}
else {
// Just a minus sign
addToken(TokenType.EXCLUDE, "-");
}
}
private void keyword() {
int start = position - 1;
// Handle leading minus for exclusion
boolean isExclusion = false;
if (start > 0 && input.charAt(start) == '-'
&& (start == 0 || Character.isWhitespace(input.charAt(start - 1)))) {
isExclusion = true;
start++;
}
// Scan the word, including quoted strings within words
while (isWordChar(peek()) || (peek() == '-' && isWordChar(peekNext())) || peek() == '*' || peek() == '?'
|| peek() == '"') {
if (peek() == '"') {
// Include quoted content as part of the keyword
advance(); // consume opening quote
while (peek() != '"' && !isAtEnd()) {
advance();
}
if (peek() == '"') {
advance(); // consume closing quote
}
}
else {
advance();
}
}
// Check for field:value pattern
if (peek() == ':' && !Character.isWhitespace(peekNext())) {
// This is a field name
String fieldName = input.substring(start, position);
advance(); // consume ':'
addToken(TokenType.KEYWORD, fieldName);
addToken(TokenType.COLON, ":");
return;
}
// Check for fuzzy operator
if (peek() == '~') {
String term = input.substring(start, position);
addToken(TokenType.KEYWORD, term);
return;
}
// Check for quoted value after = (e.g., foo="bar")
if (peek() == '"' && position > start && input.charAt(position - 1) == '=') {
// Include the quoted part as part of the keyword
advance(); // consume opening quote
while (peek() != '"' && !isAtEnd()) {
advance();
}
if (peek() == '"') {
advance(); // consume closing quote
}
}
String value = input.substring(start, position);
// Check for boolean operators
if (BOOLEAN_OPERATORS.contains(value.toUpperCase(java.util.Locale.ROOT))) {
switch (value.toUpperCase(java.util.Locale.ROOT)) {
case "AND":
addToken(TokenType.AND, value);
break;
case "OR":
addToken(TokenType.OR, value);
break;
case "NOT":
addToken(TokenType.NOT, value);
break;
}
}
else if ("TO".equals(value.toUpperCase(java.util.Locale.ROOT))) {
addToken(TokenType.RANGE_TO, value);
}
else if (isExclusion) {
addToken(TokenType.EXCLUDE, value);
}
else if (value.contains("*") || value.contains("?")) {
addToken(TokenType.WILDCARD, value);
}
else {
addToken(TokenType.KEYWORD, value);
}
}
private boolean isWordStart(char c) {
return Character.isLetterOrDigit(c) || c == '_' || c == '-';
}
private boolean isWordChar(char c) {
return Character.isLetterOrDigit(c) || c == '_' || c == '.' || c == '@' || c == '=' || c == '\\';
}
private char advance() {
return input.charAt(position++);
}
private boolean isAtEnd() {
return position >= length;
}
private char peek() {
if (isAtEnd())
return '\0';
return input.charAt(position);
}
private char peekNext() {
if (position + 1 >= length)
return '\0';
return input.charAt(position + 1);
}
private void addToken(TokenType type, String value) {
tokens.add(new Token(type, value));
}
/**
* Creates the default query lexer.
* @return the default lexer
*/
public static QueryLexer defaultLexer() {
return new QueryLexer();
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/lexer/Token.java | package am.ik.query.lexer;
public record Token(TokenType type, String value) {
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/lexer/TokenType.java | package am.ik.query.lexer;
/**
* Enumeration of token types supported by the query parser.
*
* @author Toshiaki Maki
*/
public enum TokenType {
/**
* A quoted phrase like "hello world"
*/
PHRASE,
/**
* An excluded term prefixed with - like -world
*/
EXCLUDE,
/**
* The OR boolean operator
*/
OR,
/**
* The AND boolean operator
*/
AND,
/**
* The NOT boolean operator
*/
NOT,
/**
* A regular keyword
*/
KEYWORD,
/**
* A field:value pair like title:hello
*/
FIELD,
/**
* A wildcard character * or ?
*/
WILDCARD,
/**
* A fuzzy search indicator ~
*/
FUZZY,
/**
* A boost indicator ^
*/
BOOST,
/**
* A range query indicator [ or ]
*/
RANGE_START,
/**
* A range query end indicator [ or ]
*/
RANGE_END,
/**
* The TO keyword in range queries
*/
RANGE_TO,
/**
* Whitespace characters
*/
WHITESPACE,
/**
* Left parenthesis (
*/
LPAREN,
/**
* Right parenthesis )
*/
RPAREN,
/**
* Plus sign for required terms +
*/
REQUIRED,
/**
* Colon separator for field queries :
*/
COLON,
/**
* End of input marker
*/
EOF;
/**
* Checks if this token type represents a boolean operator.
* @return true if this is OR, AND, or NOT
*/
public boolean isBooleanOperator() {
return this == OR || this == AND || this == NOT;
}
/**
* Checks if this token type represents a term modifier.
* @return true if this is EXCLUDE, REQUIRED, WILDCARD, FUZZY, or BOOST
*/
public boolean isModifier() {
return this == EXCLUDE || this == REQUIRED || this == WILDCARD || this == FUZZY || this == BOOST;
}
/**
* Checks if this token type represents actual content.
* @return true if this is KEYWORD, PHRASE, or FIELD
*/
public boolean isContent() {
return this == KEYWORD || this == PHRASE || this == FIELD;
}
/**
* Checks if this token type is structural.
* @return true if this is LPAREN, RPAREN, or WHITESPACE
*/
public boolean isStructural() {
return this == LPAREN || this == RPAREN || this == WHITESPACE || this == COLON || this == EOF;
}
}
|
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/parser/LegacyQueryParser.java | package am.ik.query.parser;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.lexer.Token;
import java.util.List;
/**
* Legacy query parser for backward compatibility.
*/
@Deprecated(since = "0.2.0", forRemoval = true)
class LegacyQueryParser {
private final List<Token> tokens;
private int position;
public LegacyQueryParser(List<Token> tokens) {
this.tokens = tokens;
this.position = 0;
}
public RootNode parse() {
return parseExpression(new RootNode());
}
private RootNode parseExpression(RootNode node) {
while (position < tokens.size()) {
Token token = tokens.get(position);
switch (token.type()) {
case PHRASE:
case EXCLUDE:
case KEYWORD:
case OR:
node.children().add(new TokenNode(token.type(), token.value()));
position++;
break;
case LPAREN:
position++;
node.children().add(parseExpression(new RootNode()));
break;
case RPAREN:
position++;
return node;
case WHITESPACE:
position++;
break;
default:
position++;
break;
}
}
return node;
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/parser/QueryParseException.java | package am.ik.query.parser;
/**
* Exception thrown when a query parsing error occurs.
*
* @author Toshiaki Maki
*/
public class QueryParseException extends RuntimeException {
private final int position;
private final String query;
public QueryParseException(String message, String query, int position) {
super(message);
this.query = query;
this.position = position;
}
public QueryParseException(String message, String query, int position, Throwable cause) {
super(message, cause);
this.query = query;
this.position = position;
}
public QueryParseException(String message) {
this(message, null, -1);
}
public QueryParseException(String message, Throwable cause) {
this(message, null, -1, cause);
}
/**
* Gets the position in the query where the error occurred.
* @return the error position, or -1 if unknown
*/
public int getPosition() {
return position;
}
/**
* Gets the original query that caused the error.
* @return the query string, or null if not available
*/
public String getQuery() {
return query;
}
/**
* Gets a detailed error message with position indicator.
* @return the detailed error message
*/
public String getDetailedMessage() {
if (query == null || position < 0) {
return getMessage();
}
StringBuilder sb = new StringBuilder();
sb.append(getMessage()).append("\n");
sb.append("Query: ").append(query).append("\n");
sb.append(" ");
for (int i = 0; i < position && i < query.length(); i++) {
sb.append(" ");
}
sb.append("^");
return sb.toString();
}
@Override
public String toString() {
return getDetailedMessage();
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/parser/QueryParser.java | package am.ik.query.parser;
import am.ik.query.Query;
import am.ik.query.ast.AndNode;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.NotNode;
import am.ik.query.ast.OrNode;
import am.ik.query.ast.PhraseNode;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.ast.WildcardNode;
import am.ik.query.lexer.LegacyQueryLexer;
import am.ik.query.lexer.QueryLexer;
import am.ik.query.lexer.Token;
import am.ik.query.lexer.TokenType;
import am.ik.query.validation.QueryValidationException;
import am.ik.query.validation.QueryValidator;
import am.ik.query.validation.ValidationResult;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
/**
* Query parser with advanced features and builder pattern.
*
* @author Toshiaki Maki
*/
public final class QueryParser {
private final QueryLexer lexer;
private final ParserOptions options;
private final Map<String, Function<String, Node>> fieldParsers;
private List<Token> tokens;
private int position;
private QueryParser(Builder builder) {
this.lexer = builder.lexer != null ? builder.lexer : QueryLexer.defaultLexer();
this.options = builder.options;
this.fieldParsers = new HashMap<>(builder.fieldParsers);
}
/**
* Parses the given query string into a Query object.
* @param queryString the query string to parse
* @return the parsed Query
* @throws QueryParseException if parsing fails
*/
public Query parse(String queryString) {
if (queryString == null) {
throw new IllegalArgumentException("queryString must not be null");
}
long startTime = System.nanoTime();
Instant parsedAt = Instant.now();
try {
// Tokenize
this.tokens = lexer.tokenize(queryString);
this.position = 0;
// Parse
Node rootNode = parseQuery();
Query query = new Query(queryString, rootNode);
// Validate if enabled
if (options.validateAfterParse()) {
ValidationResult result = QueryValidator.validate(query, options.allowedTokenTypes());
if (!result.isValid() && options.throwOnValidationError()) {
throw new QueryValidationException(result);
}
}
return query;
}
catch (Exception e) {
if (e instanceof QueryParseException || e instanceof QueryValidationException) {
throw e;
}
throw new QueryParseException("Failed to parse query: " + e.getMessage(), queryString, position, e);
}
}
private Node parseQuery() {
List<Node> nodes = new ArrayList<>();
while (!isAtEnd()) {
skipWhitespace();
if (isAtEnd())
break;
Node node = parseOr();
if (node != null) {
nodes.add(node);
}
}
if (nodes.isEmpty()) {
return new RootNode();
}
else if (nodes.size() == 1) {
return nodes.get(0);
}
else {
// Multiple nodes - combine with default operator
if (options.defaultOperator() == BooleanOperator.OR) {
return new OrNode(nodes);
}
else {
return new AndNode(nodes);
}
}
}
private Node parseOr() {
Node left = parseAnd();
// Skip whitespace before checking for OR
skipWhitespace();
// Create OR nodes only for explicit OR tokens
while (match(TokenType.OR)) {
List<Node> nodes = new ArrayList<>();
nodes.add(left);
do {
skipWhitespace();
Node right = parseAnd();
if (right != null) {
nodes.add(right);
}
skipWhitespace(); // Skip whitespace before checking for more ORs
}
while (match(TokenType.OR));
left = new OrNode(nodes);
}
return left;
}
private Node parseAnd() {
Node left = parseNot();
if (left == null)
return null;
// Skip whitespace before checking for OR/AND
skipWhitespace();
// Create AND nodes only for explicit AND tokens
boolean foundAnd = false;
while (match(TokenType.AND)) {
foundAnd = true;
List<Node> nodes = new ArrayList<>();
nodes.add(left);
do {
skipWhitespace();
if (isAtEnd() || check(TokenType.RPAREN))
break;
Node right = parseNot();
if (right != null) {
nodes.add(right);
}
skipWhitespace(); // Skip whitespace before checking for more ANDs
}
while (match(TokenType.AND));
if (nodes.size() > 1) {
left = new AndNode(nodes);
}
}
return left;
}
private Node parseNot() {
if (match(TokenType.NOT)) {
skipWhitespace();
// Recursively parse NOT to handle double negation
Node node = parseNot();
if (node == null) {
throw new QueryParseException("Expected term after NOT operator", tokens.toString(), position);
}
return new NotNode(node);
}
// EXCLUDE tokens are handled in parseTerm
return parseTerm();
}
private Node parseTerm() {
skipWhitespace();
// Handle grouping
if (match(TokenType.LPAREN)) {
Node node = parseOr();
consume(TokenType.RPAREN, "Expected ')' after expression");
return node;
}
// Handle required terms
if (match(TokenType.REQUIRED)) {
return parseTerm(); // Required is handled by validation/execution
}
// Handle field queries
if (check(TokenType.KEYWORD) && checkNext(TokenType.COLON)) {
return parseField();
}
// Handle phrases
if (match(TokenType.PHRASE)) {
String phrase = previous().value();
// Remove quotes if present
if (phrase.startsWith("\"") && phrase.endsWith("\"") && phrase.length() > 1) {
phrase = phrase.substring(1, phrase.length() - 1);
}
return new PhraseNode(phrase, previous());
}
// Handle wildcards
if (match(TokenType.WILDCARD)) {
return new WildcardNode(previous().value(), previous());
}
// Handle EXCLUDE tokens (when lexer creates "-word" as single EXCLUDE token)
if (match(TokenType.EXCLUDE)) {
Token exclude = previous();
return new NotNode(new TokenNode(TokenType.KEYWORD, exclude.value()));
}
// Handle keywords with modifiers
if (match(TokenType.KEYWORD)) {
Token keyword = previous();
String value = keyword.value();
// Check for fuzzy
if (match(TokenType.FUZZY)) {
int maxEdits = 2;
if (check(TokenType.KEYWORD) && peek().value().matches("\\d")) {
maxEdits = Integer.parseInt(advance().value());
}
return new FuzzyNode(value, maxEdits);
}
// Check for wildcard in keyword
if (value.contains("*") || value.contains("?")) {
return new WildcardNode(value, keyword);
}
return new TokenNode(keyword);
}
// Handle range queries
if (match(TokenType.RANGE_START)) {
return parseRange();
}
// Skip unknown tokens
if (!isAtEnd()) {
advance();
}
return null;
}
private Node parseField() {
String field = advance().value();
consume(TokenType.COLON, "Expected ':' after field name");
skipWhitespace();
// Check if field has custom parser
if (fieldParsers.containsKey(field)) {
String value = advance().value();
return fieldParsers.get(field).apply(value);
}
// Parse field value
Node value = parseTerm();
if (value instanceof TokenNode tokenNode) {
return new FieldNode(field, tokenNode.value(), tokenNode.token());
}
else if (value instanceof PhraseNode phraseNode) {
return new FieldNode(field, phraseNode.phrase(), phraseNode.token());
}
throw new QueryParseException("Invalid field value", tokens.toString(), position);
}
private Node parseRange() {
boolean includeStart = previous().value().equals("[");
skipWhitespace();
String start = advance().value();
skipWhitespace();
// Check for TO keyword
if (!check(TokenType.RANGE_TO) && peek().value().equalsIgnoreCase("TO")) {
advance(); // consume TO
}
else {
consume(TokenType.RANGE_TO, "Expected 'TO' in range query");
}
skipWhitespace();
String end = advance().value();
skipWhitespace();
Token endBracket = consume(TokenType.RANGE_END, "Expected ']' or '}' to close range");
boolean includeEnd = endBracket.value().equals("]");
return RangeNode.builder().start(start).end(end).includeStart(includeStart).includeEnd(includeEnd).build();
}
private boolean match(TokenType... types) {
for (TokenType type : types) {
if (check(type)) {
advance();
return true;
}
}
return false;
}
private boolean check(TokenType type) {
if (isAtEnd())
return false;
return peek().type() == type;
}
private boolean check(TokenType... types) {
if (isAtEnd())
return false;
TokenType currentType = peek().type();
for (TokenType type : types) {
if (currentType == type)
return true;
}
return false;
}
private boolean checkNext(TokenType type) {
if (position + 1 >= tokens.size())
return false;
return tokens.get(position + 1).type() == type;
}
private Token advance() {
if (!isAtEnd())
position++;
return previous();
}
private boolean isAtEnd() {
return position >= tokens.size() || peek().type() == TokenType.EOF;
}
private Token peek() {
return tokens.get(position);
}
private Token previous() {
return tokens.get(position - 1);
}
private Token consume(TokenType type, String message) {
if (check(type))
return advance();
throw new QueryParseException(message + " at position " + position, tokens.toString(), position);
}
private void skipWhitespace() {
while (match(TokenType.WHITESPACE)) {
// Skip whitespace
}
}
private int countNodes(Node node) {
final int[] count = { 0 };
node.walk(n -> count[0]++);
return count[0];
}
/**
* Calculates the maximum depth of a query AST.
* @param node the root node
* @return the maximum depth
*/
private static int calculateMaxDepth(Node node) {
if (node.isLeaf()) {
return 1;
}
int maxChildDepth = 0;
for (Node child : node.children()) {
maxChildDepth = Math.max(maxChildDepth, calculateMaxDepth(child));
}
return maxChildDepth + 1;
}
/**
* Creates a new parser builder.
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a new QueryParser with default settings.
* @return a new QueryParser instance
*/
public static QueryParser create() {
return builder().build();
}
/**
* Parses a query using default settings (backward compatibility).
* @param query the query string to parse
* @return the root node of the parsed query
* @deprecated Use Query.parse(query) or QueryParser.builder().build().parse(query)
* instead
*/
@Deprecated(since = "2.0", forRemoval = true)
@SuppressWarnings("removal")
public static RootNode parseQuery(String query) {
List<Token> tokens = legacyTokenize(query);
LegacyQueryParser legacyParser = new LegacyQueryParser(tokens);
return legacyParser.parse();
}
/**
* Legacy tokenization method for backward compatibility.
* @param input the input string
* @return list of tokens
* @deprecated Use QueryLexer.defaultLexer().tokenize() instead
*/
@Deprecated(since = "2.0", forRemoval = true)
@SuppressWarnings("removal")
private static List<Token> legacyTokenize(String input) {
// Simple legacy tokenization for backward compatibility
LegacyQueryLexer lexer = new LegacyQueryLexer(input);
return lexer.tokenize();
}
/**
* Builder for QueryParser.
*/
public static class Builder {
private QueryLexer lexer;
private ParserOptions options = ParserOptions.defaultOptions();
private final Map<String, Function<String, Node>> fieldParsers = new HashMap<>();
private Builder() {
}
/**
* Sets the lexer to use for tokenization.
* @param lexer the lexer to use (default: QueryLexer.defaultLexer())
* @return this builder
*/
public Builder lexer(QueryLexer lexer) {
this.lexer = lexer;
return this;
}
/**
* Sets the parser options.
* @param options the parser options to use
* @return this builder
*/
public Builder options(ParserOptions options) {
this.options = Objects.requireNonNull(options, "options must not be null");
return this;
}
/**
* Sets the default boolean operator used between terms when no explicit operator
* is specified.
* @param operator the default operator to use (default: BooleanOperator.AND)
* @return this builder
*/
public Builder defaultOperator(BooleanOperator operator) {
this.options = options.withDefaultOperator(operator);
return this;
}
/**
* Sets whether to validate the query after parsing.
* @param validate true to enable validation, false to disable (default: false)
* @return this builder
*/
public Builder validateAfterParse(boolean validate) {
this.options = options.withValidateAfterParse(validate);
return this;
}
/**
* Sets whether to throw an exception when validation errors occur. Only applies
* when validateAfterParse is true.
* @param throwOnError true to throw exceptions on validation errors, false to
* allow manual error checking (default: false)
* @return this builder
*/
public Builder throwOnValidationError(boolean throwOnError) {
this.options = options.withThrowOnValidationError(throwOnError);
return this;
}
/**
* Adds a custom field parser for the specified field name.
* @param field the field name to handle with custom parsing
* @param parser the function to parse field values into nodes (default: no custom
* parsers)
* @return this builder
*/
public Builder fieldParser(String field, Function<String, Node> parser) {
Objects.requireNonNull(field, "field must not be null");
Objects.requireNonNull(parser, "parser must not be null");
this.fieldParsers.put(field, parser);
return this;
}
/**
* Adds multiple custom field parsers at once.
* @param parsers a map of field names to their corresponding parsing functions
* (default: no custom parsers)
* @return this builder
*/
public Builder fieldParsers(Map<String, Function<String, Node>> parsers) {
Objects.requireNonNull(parsers, "parsers must not be null");
this.fieldParsers.putAll(parsers);
return this;
}
/**
* Sets the allowed token types for validation. Queries containing other token
* types will fail validation if validateAfterParse is enabled.
* @param types the token types to allow (default: all TokenType values)
* @return this builder
*/
public Builder allowedTokenTypes(TokenType... types) {
this.options = options.withAllowedTokenTypes(Set.of(types));
return this;
}
/**
* Sets the allowed token types for validation. Queries containing other token
* types will fail validation if validateAfterParse is enabled.
* @param types the token types to allow (default: all TokenType values)
* @return this builder
*/
public Builder allowedTokenTypes(Set<TokenType> types) {
this.options = options.withAllowedTokenTypes(types);
return this;
}
/**
* Builds a QueryParser instance with the configured options.
* @return a new QueryParser instance
*/
public QueryParser build() {
return new QueryParser(this);
}
}
/**
* Boolean operators for queries.
*/
public enum BooleanOperator {
AND, OR
}
/**
* Parser options.
*/
public record ParserOptions(BooleanOperator defaultOperator, boolean validateAfterParse,
boolean throwOnValidationError, Set<TokenType> allowedTokenTypes) {
public ParserOptions {
Objects.requireNonNull(defaultOperator, "defaultOperator must not be null");
Objects.requireNonNull(allowedTokenTypes, "allowedTokenTypes must not be null");
allowedTokenTypes = EnumSet.copyOf(allowedTokenTypes);
}
public static ParserOptions defaultOptions() {
return new ParserOptions(BooleanOperator.AND, false, false, EnumSet.allOf(TokenType.class));
}
public ParserOptions withDefaultOperator(BooleanOperator operator) {
return new ParserOptions(operator, validateAfterParse, throwOnValidationError, allowedTokenTypes);
}
public ParserOptions withValidateAfterParse(boolean validate) {
return new ParserOptions(defaultOperator, validate, throwOnValidationError, allowedTokenTypes);
}
public ParserOptions withThrowOnValidationError(boolean throwOnError) {
return new ParserOptions(defaultOperator, validateAfterParse, throwOnError, allowedTokenTypes);
}
public ParserOptions withAllowedTokenTypes(Set<TokenType> types) {
return new ParserOptions(defaultOperator, validateAfterParse, throwOnValidationError, types);
}
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/transform/QueryNormalizer.java | package am.ik.query.transform;
import am.ik.query.ast.AndNode;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.NodeVisitor;
import am.ik.query.ast.NotNode;
import am.ik.query.ast.OrNode;
import am.ik.query.ast.PhraseNode;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.ast.WildcardNode;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* Query normalizer that standardizes queries.
*
* @author Toshiaki Maki
*/
public class QueryNormalizer {
private QueryNormalizer() {
}
/**
* Creates the default query normalizer.
* @return the default normalizer
*/
public static QueryTransformer defaultNormalizer() {
return toLowerCase().andThen(sortTerms()).andThen(normalizeWhitespace());
}
/**
* Converts all terms to lowercase.
* @return the normalizer
*/
public static QueryTransformer toLowerCase() {
return toLowerCase(Locale.ROOT);
}
/**
* Converts all terms to lowercase using the specified locale.
* @param locale the locale to use
* @return the normalizer
*/
public static QueryTransformer toLowerCase(Locale locale) {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return new TokenNode(node.type(), node.value().toLowerCase(locale));
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(children);
}
@Override
public Node visitField(FieldNode node) {
// Keep field name as-is, only lowercase the value
return new FieldNode(node.field(), node.fieldValue().toLowerCase(locale));
}
@Override
public Node visitPhrase(PhraseNode node) {
return new PhraseNode(node.phrase().toLowerCase(locale));
}
@Override
public Node visitWildcard(WildcardNode node) {
return new WildcardNode(node.pattern().toLowerCase(locale));
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return new FuzzyNode(node.term().toLowerCase(locale), node.maxEdits());
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new OrNode(children);
}
@Override
public Node visitRange(RangeNode node) {
return node; // Range values typically shouldn't be lowercased
}
});
}
/**
* Sorts terms within AND/OR groups alphabetically.
* @return the normalizer
*/
public static QueryTransformer sortTerms() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
private final Comparator<Node> nodeComparator = Comparator.comparing(Node::value);
@Override
public Node visitToken(TokenNode node) {
return node;
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.sorted(nodeComparator)
.toList();
return new RootNode(children);
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.sorted(nodeComparator)
.toList();
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.sorted(nodeComparator)
.toList();
return new OrNode(children);
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitField(FieldNode node) {
return node;
}
@Override
public Node visitPhrase(PhraseNode node) {
return node;
}
@Override
public Node visitWildcard(WildcardNode node) {
return node;
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return node;
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
});
}
/**
* Normalizes whitespace in phrases and terms.
* @return the normalizer
*/
public static QueryTransformer normalizeWhitespace() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return new TokenNode(node.type(), normalizeSpace(node.value()));
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(children);
}
@Override
public Node visitPhrase(PhraseNode node) {
return new PhraseNode(normalizeSpace(node.phrase()));
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new OrNode(children);
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitField(FieldNode node) {
return new FieldNode(node.field(), normalizeSpace(node.fieldValue()));
}
@Override
public Node visitWildcard(WildcardNode node) {
return new WildcardNode(normalizeSpace(node.pattern()));
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return new FuzzyNode(normalizeSpace(node.term()), node.maxEdits());
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
private String normalizeSpace(String text) {
return text.trim().replaceAll("\\s+", " ");
}
});
}
/**
* Removes diacritics from terms.
* @return the normalizer
*/
public static QueryTransformer removeDiacritics() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return new TokenNode(node.type(), removeDiacriticsFromString(node.value()));
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(children);
}
@Override
public Node visitPhrase(PhraseNode node) {
return new PhraseNode(removeDiacriticsFromString(node.phrase()));
}
@Override
public Node visitField(FieldNode node) {
return new FieldNode(node.field(), removeDiacriticsFromString(node.fieldValue()));
}
@Override
public Node visitWildcard(WildcardNode node) {
return new WildcardNode(removeDiacriticsFromString(node.pattern()));
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return new FuzzyNode(removeDiacriticsFromString(node.term()), node.maxEdits());
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new OrNode(children);
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
private String removeDiacriticsFromString(String text) {
return java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
});
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/transform/QueryOptimizer.java | package am.ik.query.transform;
import am.ik.query.ast.AndNode;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.NodeVisitor;
import am.ik.query.ast.NotNode;
import am.ik.query.ast.OrNode;
import am.ik.query.ast.PhraseNode;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.ast.WildcardNode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Query optimizer that applies various optimization strategies.
*
* @author Toshiaki Maki
*/
public class QueryOptimizer {
private QueryOptimizer() {
}
/**
* Creates the default query optimizer.
* @return the default optimizer
*/
public static QueryTransformer defaultOptimizer() {
return removeDuplicates().andThen(flattenNestedBooleans())
.andThen(simplifyBooleans())
.andThen(removeEmptyGroups());
}
/**
* Removes duplicate terms from AND/OR groups.
* @return the optimizer
*/
public static QueryTransformer removeDuplicates() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return node;
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(deduplicate(children));
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new AndNode(deduplicate(children));
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new OrNode(deduplicate(children));
}
private List<Node> deduplicate(List<Node> nodes) {
Set<String> seen = new HashSet<>();
List<Node> result = new ArrayList<>();
for (Node node : nodes) {
String key = nodeKey(node);
if (seen.add(key)) {
result.add(node);
}
}
return result;
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitField(FieldNode node) {
return node;
}
@Override
public Node visitPhrase(PhraseNode node) {
return node;
}
@Override
public Node visitWildcard(WildcardNode node) {
return node;
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return node;
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
private String nodeKey(Node node) {
return node.getClass().getSimpleName() + ":" + node.value();
}
});
}
/**
* Flattens nested boolean operations of the same type. For example: AND(a, AND(b, c))
* becomes AND(a, b, c)
* @return the optimizer
*/
public static QueryTransformer flattenNestedBooleans() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return node;
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(children);
}
@Override
public Node visitAnd(AndNode node) {
List<Node> flattened = new ArrayList<>();
for (Node child : node.children()) {
Node processed = child.accept(this);
if (processed instanceof AndNode) {
flattened.addAll(processed.children());
}
else {
flattened.add(processed);
}
}
return new AndNode(flattened);
}
@Override
public Node visitOr(OrNode node) {
List<Node> flattened = new ArrayList<>();
for (Node child : node.children()) {
Node processed = child.accept(this);
if (processed instanceof OrNode) {
flattened.addAll(processed.children());
}
else {
flattened.add(processed);
}
}
return new OrNode(flattened);
}
@Override
public Node visitNot(NotNode node) {
return new NotNode(node.child().accept(this));
}
@Override
public Node visitField(FieldNode node) {
return node;
}
@Override
public Node visitPhrase(PhraseNode node) {
return node;
}
@Override
public Node visitWildcard(WildcardNode node) {
return node;
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return node;
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
});
}
/**
* Simplifies boolean operations. - AND/OR with single child becomes the child -
* NOT(NOT(x)) becomes x
* @return the optimizer
*/
public static QueryTransformer simplifyBooleans() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return node;
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
return new RootNode(children);
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
if (children.size() == 1) {
return children.get(0);
}
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children().stream().map(child -> child.accept(this)).toList();
if (children.size() == 1) {
return children.get(0);
}
return new OrNode(children);
}
@Override
public Node visitNot(NotNode node) {
Node child = node.child().accept(this);
if (child instanceof NotNode) {
// Double negation
return ((NotNode) child).child();
}
return new NotNode(child);
}
@Override
public Node visitField(FieldNode node) {
return node;
}
@Override
public Node visitPhrase(PhraseNode node) {
return node;
}
@Override
public Node visitWildcard(WildcardNode node) {
return node;
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return node;
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
});
}
/**
* Removes empty groups from the query.
* @return the optimizer
*/
public static QueryTransformer removeEmptyGroups() {
return QueryTransformer.fromVisitor(new NodeVisitor<Node>() {
@Override
public Node visitToken(TokenNode node) {
return node;
}
@Override
public Node visitRoot(RootNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.filter(this::isNotEmpty)
.toList();
return new RootNode(children);
}
@Override
public Node visitAnd(AndNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.filter(this::isNotEmpty)
.toList();
if (children.isEmpty()) {
return null;
}
return new AndNode(children);
}
@Override
public Node visitOr(OrNode node) {
List<Node> children = node.children()
.stream()
.map(child -> child.accept(this))
.filter(this::isNotEmpty)
.toList();
if (children.isEmpty()) {
return null;
}
return new OrNode(children);
}
@Override
public Node visitNot(NotNode node) {
Node child = node.child().accept(this);
if (child == null) {
return null;
}
return new NotNode(child);
}
@Override
public Node visitField(FieldNode node) {
return node;
}
@Override
public Node visitPhrase(PhraseNode node) {
return node;
}
@Override
public Node visitWildcard(WildcardNode node) {
return node;
}
@Override
public Node visitFuzzy(FuzzyNode node) {
return node;
}
@Override
public Node visitRange(RangeNode node) {
return node;
}
private boolean isNotEmpty(Node node) {
if (node == null) {
return false;
}
if (node.isLeaf()) {
return true;
}
return !node.children().isEmpty();
}
});
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/transform/QueryTransformer.java | package am.ik.query.transform;
import am.ik.query.Query;
import am.ik.query.ast.Node;
import am.ik.query.ast.NodeVisitor;
import java.util.function.Function;
/**
* Interface for transforming queries. Implementations can modify the query structure.
*
* @author Toshiaki Maki
*/
@FunctionalInterface
public interface QueryTransformer extends Function<Query, Query> {
/**
* Transforms the given query.
* @param query the query to transform
* @return the transformed query
*/
Query transform(Query query);
@Override
default Query apply(Query query) {
return transform(query);
}
/**
* Chains this transformer with another.
* @param after the transformer to apply after this one
* @return a combined transformer
*/
default QueryTransformer andThen(QueryTransformer after) {
return query -> after.transform(this.transform(query));
}
/**
* Creates a transformer from a node visitor.
* @param visitor the visitor that transforms nodes
* @return a query transformer
*/
static QueryTransformer fromVisitor(NodeVisitor<Node> visitor) {
return query -> {
Node transformedRoot = query.rootNode().accept(visitor);
return new Query(query.originalQuery(), transformedRoot);
};
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/util/QueryPrinter.java | package am.ik.query.util;
import am.ik.query.Query;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.TokenNode;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Pretty printer for queries.
*
* @author Toshiaki Maki
*/
public class QueryPrinter {
private QueryPrinter() {
}
/**
* Converts a query to a pretty string.
* @param query the query to convert
* @return the pretty string
*/
public static String toPrettyString(Query query) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println("Query: " + query.originalQuery());
pw.println("AST:");
printNode(query.rootNode(), pw, 0);
return sw.toString();
}
/**
* Converts a node to a pretty string.
* @param node the node to convert
* @return the pretty string
*/
public static String toPrettyString(Node node) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printNode(node, pw, 0);
return sw.toString();
}
private static void printNode(Node node, PrintWriter pw, int level) {
String indent = " ".repeat(level);
String type = node.getClass().getSimpleName();
String value = node.value();
if (node instanceof TokenNode tokenNode) {
pw.println(indent + "└─ " + type + "[" + tokenNode.type() + "]: \"" + value + "\"");
}
else if (node instanceof FieldNode fieldNode) {
pw.println(indent + "└─ " + type + ": " + fieldNode.field() + "=\"" + fieldNode.fieldValue() + "\"");
}
else if (node instanceof FuzzyNode fuzzyNode) {
pw.println(indent + "└─ " + type + ": \"" + fuzzyNode.term() + "\" ~" + fuzzyNode.maxEdits());
}
else if (node instanceof RangeNode rangeNode) {
String field = rangeNode.field() != null ? rangeNode.field() + ":" : "";
String start = rangeNode.includeStart() ? "[" : "{";
String end = rangeNode.includeEnd() ? "]" : "}";
pw.println(
indent + "└─ " + type + ": " + field + start + rangeNode.start() + " TO " + rangeNode.end() + end);
}
else if (node.isGroup()) {
pw.println(indent + "└─ " + type + " (" + node.children().size() + " children)");
for (Node child : node.children()) {
printNode(child, pw, level + 1);
}
}
else {
pw.println(indent + "└─ " + type + ": \"" + value + "\"");
}
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/validation/QueryValidationException.java | package am.ik.query.validation;
import java.util.List;
/**
* Exception thrown when query validation fails.
*
* @author Toshiaki Maki
*/
public class QueryValidationException extends RuntimeException {
private final ValidationResult validationResult;
public QueryValidationException(ValidationResult validationResult) {
super(buildMessage(validationResult));
this.validationResult = validationResult;
}
public QueryValidationException(String message) {
super(message);
this.validationResult = ValidationResult.invalid(List.of(new ValidationError(message)));
}
/**
* Gets the validation result that caused this exception.
* @return the validation result
*/
public ValidationResult getValidationResult() {
return validationResult;
}
/**
* Gets all validation errors.
* @return list of validation errors
*/
public List<ValidationError> getErrors() {
return validationResult.errors();
}
private static String buildMessage(ValidationResult result) {
if (result.isValid()) {
return "Validation passed but exception was thrown";
}
List<ValidationError> errors = result.errors();
if (errors.size() == 1) {
return errors.get(0).message();
}
StringBuilder sb = new StringBuilder("Query validation failed with ").append(errors.size())
.append(" errors:\n");
for (int i = 0; i < errors.size(); i++) {
sb.append(i + 1).append(". ").append(errors.get(i).message()).append("\n");
}
return sb.toString();
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/validation/QueryValidator.java | package am.ik.query.validation;
import am.ik.query.Query;
import am.ik.query.ast.AndNode;
import am.ik.query.ast.FieldNode;
import am.ik.query.ast.FuzzyNode;
import am.ik.query.ast.Node;
import am.ik.query.ast.NodeVisitor;
import am.ik.query.ast.NotNode;
import am.ik.query.ast.OrNode;
import am.ik.query.ast.PhraseNode;
import am.ik.query.ast.RangeNode;
import am.ik.query.ast.RootNode;
import am.ik.query.ast.TokenNode;
import am.ik.query.ast.WildcardNode;
import am.ik.query.lexer.TokenType;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* Validates queries for structural and semantic correctness.
*
* @author Toshiaki Maki
*/
public class QueryValidator {
private QueryValidator() {
}
/**
* Validates a query using default validation rules.
* @param query the query to validate
* @return the validation result
*/
public static ValidationResult validate(Query query) {
return validate(query, EnumSet.allOf(TokenType.class));
}
/**
* Validates a query using specified allowed token types.
* @param query the query to validate
* @param allowedTokenTypes the set of allowed token types
* @return the validation result
*/
public static ValidationResult validate(Query query, Set<TokenType> allowedTokenTypes) {
List<ValidationError> errors = new ArrayList<>();
// Check for empty query
if (query.isEmpty()) {
errors.add(new ValidationError("Query is empty"));
}
// Validate structure
errors.addAll(validateStructure(query.rootNode()));
// Validate semantic rules
errors.addAll(validateSemantics(query.rootNode()));
// Validate token types (both AST nodes and raw tokens)
errors.addAll(validateTokenTypes(query, allowedTokenTypes));
return errors.isEmpty() ? ValidationResult.valid() : ValidationResult.invalid(errors);
}
private static List<ValidationError> validateStructure(Node root) {
List<ValidationError> errors = new ArrayList<>();
StructureValidator validator = new StructureValidator();
root.walk(validator::visit);
errors.addAll(validator.getErrors());
return errors;
}
private static List<ValidationError> validateSemantics(Node root) {
List<ValidationError> errors = new ArrayList<>();
SemanticsValidator validator = new SemanticsValidator();
root.accept(validator);
errors.addAll(validator.getErrors());
return errors;
}
private static List<ValidationError> validateTokenTypes(Node root, Set<TokenType> allowedTokenTypes) {
List<ValidationError> errors = new ArrayList<>();
TokenTypeValidator validator = new TokenTypeValidator(allowedTokenTypes);
root.walk(validator::visit);
errors.addAll(validator.getErrors());
return errors;
}
private static List<ValidationError> validateTokenTypes(Query query, Set<TokenType> allowedTokenTypes) {
List<ValidationError> errors = new ArrayList<>();
// Validate the AST nodes
TokenTypeValidator nodeValidator = new TokenTypeValidator(allowedTokenTypes);
query.rootNode().walk(nodeValidator::visit);
errors.addAll(nodeValidator.getErrors());
// Note: Original token validation was removed along with QueryMetadata
// This functionality could be re-implemented by passing tokens separately if
// needed
return errors;
}
private static class StructureValidator {
private final List<ValidationError> errors = new ArrayList<>();
private final Stack<Node> nodeStack = new Stack<>();
void visit(Node node) {
// Check for empty groups
if (node.isGroup() && node.children().isEmpty()) {
errors.add(new ValidationError("Empty group node: " + node.getClass().getSimpleName()));
}
// Check NOT nodes have exactly one child
if (node instanceof NotNode notNode) {
if (notNode.children().size() != 1) {
errors.add(new ValidationError("NOT node must have exactly one child"));
}
}
// Check for deeply nested structures (max depth 10)
if (node.depth() > 10) {
errors.add(new ValidationError("Query is too deeply nested (max depth: 10)"));
}
// Check for circular references
if (nodeStack.contains(node)) {
errors.add(new ValidationError("Circular reference detected in query structure"));
}
nodeStack.push(node);
node.children().forEach(this::visit);
nodeStack.pop();
}
List<ValidationError> getErrors() {
return errors;
}
}
private static class SemanticsValidator implements NodeVisitor<Void> {
private final List<ValidationError> errors = new ArrayList<>();
@Override
public Void visitToken(TokenNode node) {
// Validate token value is not empty
if (node.value().trim().isEmpty()) {
errors.add(new ValidationError("Empty token value", node.type().name()));
}
return null;
}
@Override
public Void visitRoot(RootNode node) {
node.children().forEach(child -> child.accept(this));
return null;
}
@Override
public Void visitAnd(AndNode node) {
// Check for conflicting terms (term and -term)
checkConflictingTerms(node.children(), "AND");
node.children().forEach(child -> child.accept(this));
return null;
}
@Override
public Void visitOr(OrNode node) {
// OR of all negative terms is likely an error
boolean allNegative = node.children()
.stream()
.allMatch(child -> child instanceof NotNode
|| (child instanceof TokenNode && ((TokenNode) child).type() == TokenType.EXCLUDE));
if (allNegative) {
errors.add(new ValidationError("OR expression contains only negative terms"));
}
node.children().forEach(child -> child.accept(this));
return null;
}
@Override
public Void visitField(FieldNode node) {
// Validate field name
if (node.field().trim().isEmpty()) {
errors.add(new ValidationError("Empty field name"));
}
// Validate field value
if (node.fieldValue().trim().isEmpty()) {
errors.add(new ValidationError("Empty field value for field: " + node.field()));
}
return null;
}
@Override
public Void visitFuzzy(FuzzyNode node) {
// Fuzzy queries should have reasonable length
if (node.term().length() < 3) {
errors.add(new ValidationError(
"Fuzzy term '" + node.term() + "' is too short (minimum 3 characters recommended)"));
}
return null;
}
@Override
public Void visitNot(NotNode node) {
node.child().accept(this);
return null;
}
@Override
public Void visitPhrase(PhraseNode node) {
if (node.phrase().trim().isEmpty()) {
errors.add(new ValidationError("Empty phrase"));
}
return null;
}
@Override
public Void visitWildcard(WildcardNode node) {
if (node.pattern().trim().isEmpty()) {
errors.add(new ValidationError("Empty wildcard pattern"));
}
return null;
}
@Override
public Void visitRange(RangeNode node) {
// Check range values
if (node.start().equals(node.end())) {
errors.add(new ValidationError("Range start and end values are the same: " + node.start()));
}
// Check for wildcard boundaries
if ("*".equals(node.start()) && "*".equals(node.end())) {
errors.add(new ValidationError("Range with both boundaries as wildcards matches everything"));
}
return null;
}
private void checkConflictingTerms(List<Node> nodes, String operator) {
List<String> positiveTerms = new ArrayList<>();
List<String> negativeTerms = new ArrayList<>();
for (Node node : nodes) {
if (node instanceof TokenNode tokenNode) {
if (tokenNode.type() == TokenType.EXCLUDE) {
negativeTerms.add(tokenNode.value());
}
else {
positiveTerms.add(tokenNode.value());
}
}
else if (node instanceof NotNode notNode && notNode.child() instanceof TokenNode tokenNode) {
negativeTerms.add(tokenNode.value());
}
}
// Check for conflicts
for (String neg : negativeTerms) {
if (positiveTerms.contains(neg)) {
errors.add(new ValidationError(
operator + " expression contains conflicting terms: " + neg + " and -" + neg));
}
}
}
List<ValidationError> getErrors() {
return errors;
}
}
private static class TokenTypeValidator {
private final Set<TokenType> allowedTokenTypes;
private final List<ValidationError> errors = new ArrayList<>();
TokenTypeValidator(Set<TokenType> allowedTokenTypes) {
this.allowedTokenTypes = allowedTokenTypes;
}
void visit(Node node) {
if (node instanceof TokenNode tokenNode) {
TokenType type = tokenNode.type();
if (!allowedTokenTypes.contains(type)) {
errors.add(new ValidationError("Token type not allowed: " + type.name()));
}
}
else if (node instanceof FieldNode) {
if (!allowedTokenTypes.contains(TokenType.FIELD)) {
errors.add(new ValidationError("Token type not allowed: FIELD"));
}
}
else if (node instanceof WildcardNode) {
if (!allowedTokenTypes.contains(TokenType.WILDCARD)) {
errors.add(new ValidationError("Token type not allowed: WILDCARD"));
}
}
else if (node instanceof FuzzyNode) {
if (!allowedTokenTypes.contains(TokenType.FUZZY)) {
errors.add(new ValidationError("Token type not allowed: FUZZY"));
}
}
else if (node instanceof RangeNode) {
if (!allowedTokenTypes.contains(TokenType.RANGE_START)
|| !allowedTokenTypes.contains(TokenType.RANGE_END)
|| !allowedTokenTypes.contains(TokenType.RANGE_TO)) {
errors.add(new ValidationError("Token type not allowed: RANGE"));
}
}
}
List<ValidationError> getErrors() {
return errors;
}
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/validation/ValidationError.java | package am.ik.query.validation;
import java.util.Objects;
/**
* Represents a single validation error.
*
* @author Toshiaki Maki
*/
public record ValidationError(String message, String field, Object invalidValue) {
public ValidationError {
Objects.requireNonNull(message, "message must not be null");
}
/**
* Creates a validation error with just a message.
* @param message the error message
*/
public ValidationError(String message) {
this(message, null, null);
}
/**
* Creates a validation error with message and field.
* @param message the error message
* @param field the field that failed validation
*/
public ValidationError(String message, String field) {
this(message, field, null);
}
@Override
public String toString() {
if (field != null) {
return field + ": " + message + (invalidValue != null ? " (was: " + invalidValue + ")" : "");
}
return message;
}
} |
0 | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query | java-sources/am/ik/query/query-parser/0.2.0/am/ik/query/validation/ValidationResult.java | package am.ik.query.validation;
import java.util.List;
import java.util.Objects;
/**
* Result of query validation.
*
* @author Toshiaki Maki
*/
public record ValidationResult(boolean isValid, List<ValidationError> errors) {
public ValidationResult {
Objects.requireNonNull(errors, "errors must not be null");
errors = List.copyOf(errors);
}
/**
* Creates a valid result with no errors.
* @return a valid result
*/
public static ValidationResult valid() {
return new ValidationResult(true, List.of());
}
/**
* Creates an invalid result with the given errors.
* @param errors the validation errors
* @return an invalid result
*/
public static ValidationResult invalid(List<ValidationError> errors) {
if (errors.isEmpty()) {
throw new IllegalArgumentException("Invalid result must have at least one error");
}
return new ValidationResult(false, errors);
}
/**
* Creates an invalid result with a single error.
* @param error the validation error
* @return an invalid result
*/
public static ValidationResult invalid(ValidationError error) {
return invalid(List.of(error));
}
/**
* Creates an invalid result with a single error message.
* @param message the error message
* @return an invalid result
*/
public static ValidationResult invalid(String message) {
return invalid(new ValidationError(message));
}
/**
* Throws QueryValidationException if validation failed.
* @throws QueryValidationException if not valid
*/
public void throwIfInvalid() {
if (!isValid) {
throw new QueryValidationException(this);
}
}
/**
* Combines this result with another result.
* @param other the other result
* @return combined result
*/
public ValidationResult combine(ValidationResult other) {
if (this.isValid && other.isValid) {
return valid();
}
List<ValidationError> combinedErrors = new java.util.ArrayList<>();
combinedErrors.addAll(this.errors);
combinedErrors.addAll(other.errors);
return invalid(combinedErrors);
}
} |
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/Node.java | package am.ik.query;
import java.util.List;
public sealed interface Node permits RootNode, TokenNode {
String value();
static void print(RootNode node) {
print(node, 0);
}
static void print(Node node, int level) {
if (node instanceof TokenNode) {
System.out.println("\t".repeat(level) + node);
}
else if (node instanceof RootNode) {
System.out.println("\t".repeat(level) + node);
List<Node> children = ((RootNode) node).children();
if (!children.isEmpty()) {
children.forEach(c -> print(c, level + 1));
}
}
}
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/QueryLexer.java | package am.ik.query;
import java.util.ArrayList;
import java.util.List;
public class QueryLexer {
public static List<Token> tokenize(String input) {
List<Token> tokens = new ArrayList<>();
int length = input.length();
for (int i = 0; i < length;) {
char current = input.charAt(i);
if (Character.isWhitespace(current)) {
int start = i;
while (i < length && Character.isWhitespace(input.charAt(i))) {
i++;
}
tokens.add(new Token(TokenType.WHITESPACE, input.substring(start, i)));
}
else if (current == '"') {
int start = i++;
while (i < length && input.charAt(i) != '"') {
i++;
}
if (i < length) {
i++; // consume closing "
}
tokens.add(new Token(TokenType.PHRASE, input.substring(start + 1, i - 1)));
}
else if (current == '-') {
int start = i++;
while (i < length && !Character.isWhitespace(input.charAt(i))) {
i++;
}
tokens.add(new Token(TokenType.EXCLUDE, input.substring(start + 1, i)));
}
else if (current == '(') {
tokens.add(new Token(TokenType.LPAREN, String.valueOf(current)));
i++;
}
else if (current == ')') {
tokens.add(new Token(TokenType.RPAREN, String.valueOf(current)));
i++;
}
else {
int start = i;
while (i < length && !Character.isWhitespace(input.charAt(i)) && input.charAt(i) != '"'
&& input.charAt(i) != '-' && input.charAt(i) != '(' && input.charAt(i) != ')') {
i++;
}
String value = input.substring(start, i);
if (value.equalsIgnoreCase("OR")) {
tokens.add(new Token(TokenType.OR, value));
}
else {
tokens.add(new Token(TokenType.KEYWORD, value));
}
}
}
return tokens;
}
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/QueryParser.java | package am.ik.query;
import java.util.List;
public class QueryParser {
private final List<Token> tokens;
private int position;
public QueryParser(List<Token> tokens) {
this.tokens = tokens;
this.position = 0;
}
public RootNode parse() {
return parseExpression(new RootNode());
}
private RootNode parseExpression(RootNode node) {
while (position < tokens.size()) {
Token token = tokens.get(position);
switch (token.type()) {
case PHRASE:
case EXCLUDE:
case KEYWORD:
case OR:
node.children().add(new TokenNode(token.type(), token.value()));
position++;
break;
case LPAREN:
position++;
node.children().add(parseExpression(new RootNode()));
break;
case RPAREN:
position++;
return node;
case WHITESPACE:
position++;
break;
}
}
return node;
}
public static RootNode parseQuery(String query) {
List<Token> tokens = QueryLexer.tokenize(query);
QueryParser queryParser = new QueryParser(tokens);
return queryParser.parse();
}
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/RootNode.java | package am.ik.query;
import java.util.ArrayList;
import java.util.List;
public final class RootNode implements Node {
private final List<Node> children = new ArrayList<>();
@Override
public String value() {
return "root";
}
public List<Node> children() {
return this.children;
}
public boolean hasChildren() {
return !this.children.isEmpty();
}
@Override
public String toString() {
return RootNode.class.getSimpleName();
}
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/Token.java | package am.ik.query;
public record Token(TokenType type, String value) {
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/TokenNode.java | package am.ik.query;
public record TokenNode(TokenType type, String value) implements Node {
}
|
0 | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik | java-sources/am/ik/query/query-queryParser/0.1.0/am/ik/query/TokenType.java | package am.ik.query;
public enum TokenType {
PHRASE, EXCLUDE, OR, KEYWORD, WHITESPACE, LPAREN, // '('
RPAREN // ')'
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/AmzDate.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
class AmzDate {
private static final DateTimeFormatter AMZDATE_FORMATTER = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'");
private final String date;
private final String yymmdd;
public AmzDate(Instant timestamp) {
final OffsetDateTime dateTime = timestamp.atOffset(ZoneOffset.UTC);
this.date = AMZDATE_FORMATTER.format(dateTime);
this.yymmdd = this.date.substring(0, 8);
}
public String date() {
return date;
}
public String yymmdd() {
return yymmdd;
}
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/AmzHttpHeaders.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
public class AmzHttpHeaders {
static final String X_AMZ_CONTENT_SHA256 = "X-Amz-Content-Sha256";
static final String X_AMZ_DATE = "X-Amz-Date";
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/Bucket.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.time.OffsetDateTime;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public record Bucket(@JacksonXmlProperty(localName = "Name") String name,
@JacksonXmlProperty(localName = "CreationDate") OffsetDateTime creationDate) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/Content.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.time.OffsetDateTime;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public record Content(@JacksonXmlProperty(localName = "Key") String key,
@JacksonXmlProperty(localName = "LastModified") OffsetDateTime lastModified,
@JacksonXmlProperty(localName = "ETag") String etag, @JacksonXmlProperty(localName = "Size") long size,
@JacksonXmlProperty(localName = "Owner") Owner owner,
@JacksonXmlProperty(localName = "StorageClass") String storageClass) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/DeleteMarker.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public record DeleteMarker(@JacksonXmlProperty(localName = "Key") String key,
@JacksonXmlProperty(localName = "LastModified") String lastModified,
@JacksonXmlProperty(localName = "ETag") String eTag, @JacksonXmlProperty(localName = "Size") int size,
@JacksonXmlProperty(localName = "Owner") Owner owner,
@JacksonXmlProperty(localName = "StorageClass") String storageClass,
@JacksonXmlProperty(localName = "IsLatest") boolean isLatest,
@JacksonXmlProperty(localName = "VersionId") String versionId) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/ListBucketResult.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "ListBucketResult")
public record ListBucketResult(@JacksonXmlProperty(localName = "Name") String name,
@JacksonXmlProperty(localName = "Prefix") String prefix,
@JacksonXmlProperty(localName = "Marker") String marker, @JacksonXmlProperty(localName = "MaxKeys") int maxKeys,
@JacksonXmlProperty(localName = "IsTruncated") boolean isTruncated, @JacksonXmlProperty(
localName = "Contents") @JacksonXmlElementWrapper(useWrapping = false) List<Content> contents) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/ListBucketsResult.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "ListAllMyBucketsResult")
public record ListBucketsResult(@JacksonXmlProperty(localName = "Owner") Owner owner,
@JacksonXmlProperty(localName = "Buckets") List<Bucket> buckets) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/ListVersionsResult.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "ListVersionsResult")
public final class ListVersionsResult {
private final String name;
private final String prefix;
private final String keyMarker;
private final String nextVersionIdMarker;
private final String versionIdMarker;
private final int maxKeys;
private final boolean isTruncated;
private List<DeleteMarker> deleteMarkers;
private List<Version> versions;
public ListVersionsResult(@JacksonXmlProperty(localName = "Name") String name,
@JacksonXmlProperty(localName = "Prefix") String prefix,
@JacksonXmlProperty(localName = "KeyMarker") String keyMarker,
@JacksonXmlProperty(localName = "NextVersionIdMarker") String nextVersionIdMarker,
@JacksonXmlProperty(localName = "VersionIdMarker") String versionIdMarker,
@JacksonXmlProperty(localName = "MaxKeys") int maxKeys,
@JacksonXmlProperty(localName = "IsTruncated") boolean isTruncated,
@JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(
localName = "DeleteMarker") List<DeleteMarker> deleteMarkers,
@JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(
localName = "Version") List<Version> versions) {
this.name = name;
this.prefix = prefix;
this.keyMarker = keyMarker;
this.nextVersionIdMarker = nextVersionIdMarker;
this.versionIdMarker = versionIdMarker;
this.maxKeys = maxKeys;
this.isTruncated = isTruncated;
this.deleteMarkers = deleteMarkers;
this.versions = versions;
}
public String name() {
return name;
}
public String prefix() {
return prefix;
}
public String keyMarker() {
return keyMarker;
}
public String nextVersionIdMarker() {
return nextVersionIdMarker;
}
public String versionIdMarker() {
return versionIdMarker;
}
public int maxKeys() {
return maxKeys;
}
public boolean isTruncated() {
return isTruncated;
}
public List<DeleteMarker> deleteMarkers() {
return deleteMarkers;
}
public List<Version> versions() {
return versions;
}
public void setVersions(List<Version> versions) {
this.versions = versions;
}
public void setDeleteMarkers(List<DeleteMarker> deleteMarkers) {
this.deleteMarkers = deleteMarkers;
}
} |
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/Owner.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public record Owner(@JacksonXmlProperty(localName = "ID") String id,
@JacksonXmlProperty(localName = "DisplayName") String displayName) {
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/S3Client.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.web.client.RestTemplate;
import static am.ik.s3.S3RequestBuilder.s3Request;
/**
* Consider using {@link S3Request} instead.
*/
@Deprecated(since = "0.2.0", forRemoval = true)
public class S3Client {
private final RestTemplate restTemplate;
private final URI endpoint;
private final String region;
private final String accessKeyId;
private final String secretAccessKey;
public S3Client(RestTemplate restTemplate, URI endpoint, String region, String accessKeyId,
String secretAccessKey) {
this.restTemplate = restTemplate;
this.endpoint = endpoint;
this.region = region;
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
}
public ListBucketsResult listBuckets() {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.GET)
.path(b -> b)
.build()
.toEntityBuilder()
.build();
return this.restTemplate.exchange(request, ListBucketsResult.class).getBody();
}
public ListBucketResult listBucket(String bucket) {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.GET)
.path(b -> b.bucket(bucket))
.build()
.toEntityBuilder()
.build();
return this.restTemplate.exchange(request, ListBucketResult.class).getBody();
}
public void deleteBucket(String bucket) {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.DELETE)
.path(b -> b.bucket(bucket))
.build()
.toEntityBuilder()
.build();
this.restTemplate.exchange(request, String.class);
}
public void putBucket(String bucket) {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.PUT)
.path(b -> b.bucket(bucket))
.build()
.toEntityBuilder()
.build();
this.restTemplate.exchange(request, String.class);
}
public void putObject(String bucket, String key, byte[] content, MediaType mediaType) {
RequestEntity<byte[]> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.PUT)
.path(b -> b.bucket(bucket).key(key))
.content(S3Content.of(content, mediaType))
.build()
.toEntityBuilder()
.body(content);
this.restTemplate.exchange(request, Void.class);
}
public void putObject(String bucket, String key, Resource resource, MediaType mediaType) {
try {
byte[] body = resource.getContentAsByteArray();
RequestEntity<byte[]> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.PUT)
.path(b -> b.bucket(bucket).key(key))
.content(S3Content.of(body, mediaType))
.build()
.toEntityBuilder()
.body(body);
this.restTemplate.exchange(request, Void.class);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public byte[] getObject(String bucket, String key) {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.GET)
.path(b -> b.bucket(bucket).key(key))
.build()
.toEntityBuilder()
.build();
return this.restTemplate.exchange(request, byte[].class).getBody();
}
public void deleteObject(String bucket, String key) {
RequestEntity<Void> request = s3Request().endpoint(this.endpoint)
.region(this.region)
.accessKeyId(this.accessKeyId)
.secretAccessKey(this.secretAccessKey)
.method(HttpMethod.DELETE)
.path(b -> b.bucket(bucket).key(key))
.build()
.toEntityBuilder()
.build();
this.restTemplate.exchange(request, Void.class);
}
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/S3Content.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.nio.charset.StandardCharsets;
import org.springframework.http.MediaType;
public record S3Content(byte[] body, MediaType mediaType) {
public static S3Content of(String body, MediaType mediaType) {
return new S3Content(body.getBytes(StandardCharsets.UTF_8), mediaType);
}
public static S3Content of(byte[] body, MediaType mediaType) {
return new S3Content(body, mediaType);
}
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/S3Path.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.util.Objects;
import org.jilt.Builder;
import org.springframework.web.util.UriComponentsBuilder;
@Builder
public final class S3Path {
private final String bucket;
private final String key;
private final Boolean encodeKey;
public S3Path(String bucket, String key, Boolean encodeKey) {
this.bucket = bucket;
this.key = key;
this.encodeKey = Objects.requireNonNullElse(encodeKey, true);
}
public String toCanonicalUri() {
StringBuilder builder = new StringBuilder();
if (bucket == null || bucket.isEmpty()) {
builder.append("/");
}
else {
if (!bucket.startsWith("/")) {
builder.append("/");
}
builder.append(bucket);
}
if (key != null && !key.isEmpty()) {
if (!key.startsWith("/")) {
builder.append("/");
}
if (encodeKey) {
builder.append(encodeKey(key));
}
else {
builder.append(key);
}
}
return builder.toString();
}
private static String encodeKey(String key) {
String encodedKey = UriComponentsBuilder.fromPath(key).encode().build().getPath();
if (encodedKey == null) {
return null;
}
return encodedKey.replace("!", "%21")
.replace("#", "%23")
.replace("$", "%24")
.replace("&", "%26")
.replace("'", "%27")
.replace("(", "%28")
.replace(")", "%29")
.replace("*", "%2A")
.replace("+", "%2B")
.replace(",", "%2C")
.replace(":", "%3A")
.replace(";", "%3B")
.replace("=", "%3D")
.replace("@", "%40")
.replace("[", "%5B")
.replace("]", "%5D")
.replace("{", "%7B")
.replace("}", "%7D");
}
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/S3Request.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.HexFormat;
import java.util.Objects;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.jilt.Builder;
import org.jilt.BuilderStyle;
import org.jilt.Opt;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.web.util.UriComponentsBuilder;
public final class S3Request {
private final URI endpoint;
private final String region;
private final String accessKeyId;
private final String secretAccessKey;
private final HttpMethod method;
private final String canonicalUri;
private final String canonicalQueryString;
private final S3Content content;
private final Clock clock;
public static final String AWS4_HMAC_SHA256 = "AWS4-HMAC-SHA256";
private static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
private URI uri;
private HttpHeaders httpHeaders;
@Builder(style = BuilderStyle.STAGED)
public S3Request(URI endpoint, String region, String accessKeyId, String secretAccessKey, HttpMethod method,
Function<S3PathBuilder, S3PathBuilder> path, @Opt String canonicalQueryString, @Opt S3Content content,
@Opt Clock clock) {
this.endpoint = endpoint;
this.region = region;
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.method = method;
this.canonicalUri = path == null ? "/" : path.apply(new S3PathBuilder()).build().toCanonicalUri();
this.canonicalQueryString = Objects.requireNonNullElse(canonicalQueryString, "");
this.content = content;
this.clock = Objects.requireNonNullElseGet(clock, Clock::systemUTC);
this.init();
}
private void init() {
AmzDate amzDate = new AmzDate(this.clock.instant());
String contentSha256 = content == null ? UNSIGNED_PAYLOAD : encodeHex(sha256Hash(content.body()));
TreeMap<String, String> headers = new TreeMap<>();
StringBuilder host = new StringBuilder(this.endpoint.getHost());
if (this.endpoint.getPort() != -1) {
host.append(":").append(this.endpoint.getPort());
}
headers.put(HttpHeaders.HOST, host.toString());
headers.put(AmzHttpHeaders.X_AMZ_CONTENT_SHA256, contentSha256);
headers.put(AmzHttpHeaders.X_AMZ_DATE, amzDate.date());
if (content != null && content.body() != null) {
headers.put(HttpHeaders.CONTENT_LENGTH, String.valueOf(content.body().length));
}
if (content != null && content.mediaType() != null) {
headers.put(HttpHeaders.CONTENT_TYPE, content.mediaType().toString());
}
String authorization = this.authorization(headers, contentSha256, amzDate);
this.httpHeaders = new HttpHeaders();
headers.forEach(this.httpHeaders::add);
this.httpHeaders.add(HttpHeaders.AUTHORIZATION, authorization);
this.uri = UriComponentsBuilder.fromUri(this.endpoint)
.path(canonicalUri)
.query(canonicalQueryString)
.build(true)
.toUri();
}
public URI uri() {
return this.uri;
}
public Consumer<HttpHeaders> headers() {
return headers -> headers.addAll(this.httpHeaders);
}
public RequestEntity.BodyBuilder toEntityBuilder() {
return RequestEntity.method(this.method, this.uri).headers(this.httpHeaders);
}
private String authorization(
TreeMap<String, String> headers /* must appear in alphabetical order */, String payloadHash,
AmzDate amzDate) {
// Step 1: Create a canonical request
// https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request
String canonicalHeaders = headers.entrySet()
.stream()
.map(e -> "%s:%s".formatted(e.getKey().toLowerCase(), e.getValue()))
.collect(Collectors.joining("\n")) + "\n";
String signedHeaders = headers.keySet().stream().map(String::toLowerCase).collect(Collectors.joining(";"));
String canonicalRequest = String.join("\n", method.name(), canonicalUri, canonicalQueryString, canonicalHeaders,
signedHeaders, payloadHash);
// Step 2: Create a hash of the canonical request
// https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request-hash
String hashedCanonicalRequest = encodeHex(sha256Hash(canonicalRequest.getBytes(StandardCharsets.UTF_8)));
// Step 3: Create a string to sign
// https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-string-to-sign
String credentialScope = "%s/%s/s3/aws4_request".formatted(amzDate.yymmdd(), this.region);
String stringToSign = String.join("\n", AWS4_HMAC_SHA256, amzDate.date(), credentialScope,
hashedCanonicalRequest);
// Step 4: Calculate the signature
// https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#calculate-signature
String signature = this.sign(stringToSign, amzDate);
// Step 5: Add the signature to the request
// https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#add-signature-to-request
String credential = "%s/%s".formatted(this.accessKeyId, credentialScope);
return "%s Credential=%s,SignedHeaders=%s,Signature=%s".formatted(AWS4_HMAC_SHA256, credential, signedHeaders,
signature);
}
private String sign(String stringToSign, AmzDate amzDate) {
byte[] kSecret = ("AWS4" + this.secretAccessKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSHA256(amzDate.yymmdd(), kSecret);
byte[] kRegion = hmacSHA256(this.region, kDate);
byte[] kService = hmacSHA256("s3", kRegion);
byte[] kSigning = hmacSHA256("aws4_request", kService);
return encodeHex(hmacSHA256(stringToSign, kSigning));
}
private static byte[] sha256Hash(byte[] data) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(data);
}
catch (NoSuchAlgorithmException e) {
// should not happen
throw new IllegalStateException(e);
}
}
private static byte[] hmacSHA256(String data, byte[] key) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
catch (NoSuchAlgorithmException | InvalidKeyException e) {
// should not happen
throw new IllegalStateException(e);
}
}
private static String encodeHex(byte[] data) {
HexFormat hex = HexFormat.of();
StringBuilder sb = new StringBuilder();
for (byte datum : data) {
sb.append(hex.toHexDigits(datum));
}
return sb.toString();
}
@Override
public String toString() {
return "S3Request{" + "endpoint=" + endpoint + ", region='" + region + '\'' + ", accessKeyId='" + accessKeyId
+ '\'' + ", method=" + method + ", canonicalUri='" + canonicalUri + '\'' + ", canonicalQueryString='"
+ canonicalQueryString + '\'' + '}';
}
}
|
0 | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik | java-sources/am/ik/s3/simple-s3-client/0.2.2/am/ik/s3/Version.java | /*
* Copyright (C) 2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed 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 am.ik.s3;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public record Version(@JacksonXmlProperty(localName = "Key") String key,
@JacksonXmlProperty(localName = "LastModified") String lastModified,
@JacksonXmlProperty(localName = "ETag") String eTag, @JacksonXmlProperty(localName = "Size") int size,
@JacksonXmlProperty(localName = "Owner") Owner owner,
@JacksonXmlProperty(localName = "StorageClass") String storageClass,
@JacksonXmlProperty(localName = "IsLatest") boolean isLatest,
@JacksonXmlProperty(localName = "VersionId") String versionId) {
} |
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/CloudKarafkaServiceBrokerApplication.java | package am.ik.servicebroker.cloudkarafka;
import org.apache.catalina.filters.RequestDumperFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
@SpringBootApplication
public class CloudKarafkaServiceBrokerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudKarafkaServiceBrokerApplication.class, args);
}
@Bean
@Profile("default")
RequestDumperFilter requestDumperFilter() {
return new RequestDumperFilter();
}
}
|
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/cloudkarafka/CloudKarafka.java | package am.ik.servicebroker.cloudkarafka.cloudkarafka;
import java.util.Base64;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "cloudkarafka")
@Component
public class CloudKarafka {
private String uri = "https://customer.cloudkarafka.com";
private String apiKey = "";
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String authorization() {
return "Basic "
+ Base64.getEncoder().encodeToString((this.apiKey + ":").getBytes());
}
}
|
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/cloudkarafka/CloudKarafkaClient.java | package am.ik.servicebroker.cloudkarafka.cloudkarafka;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
@Component
public class CloudKarafkaClient {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public CloudKarafkaClient(CloudKarafka cloudKarafka, RestTemplateBuilder builder,
ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.restTemplate = builder.basicAuthorization(cloudKarafka.getApiKey(), "")
.rootUri(cloudKarafka.getUri()).build();
}
public List<CloudKarafkaInstance> listInstances() {
LinkedCaseInsensitiveMap[] instances = this.restTemplate
.getForObject("/api/instances", LinkedCaseInsensitiveMap[].class);
return instances == null ? emptyList()
: Arrays.stream(instances).map(this::caseInsensitiveConvert)
.collect(toList());
}
public CloudKarafkaInstance getInstance(Integer id) {
LinkedCaseInsensitiveMap json = this.restTemplate
.getForObject("/api/instances/{id}", LinkedCaseInsensitiveMap.class, id);
return this.caseInsensitiveConvert(json);
}
public CloudKarafkaInstance createInstance(String name, CloudKarafkaPlan plan,
CloudKarafkaRegion region) {
LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("name", name);
body.add("plan", plan.toString());
body.add("region", region.toString());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
LinkedCaseInsensitiveMap json = this.restTemplate
.exchange("/api/instances", HttpMethod.POST,
new HttpEntity<>(body, headers), LinkedCaseInsensitiveMap.class)
.getBody();
return this.caseInsensitiveConvert(json);
}
public Optional<CloudKarafkaInstance> findByName(String name) {
return this.listInstances().stream() //
.map(i -> this.getInstance(i.getId())) //
.filter(i -> Objects.equals(name, i.getName())) //
.findAny();
}
public void deleteInstance(Integer id) {
this.restTemplate.delete("/api/instances/{id}", id);
}
CloudKarafkaInstance caseInsensitiveConvert(LinkedCaseInsensitiveMap json) {
// Some API return lower snake keys but some API return upper snake keys
CloudKarafkaInstance instance = new CloudKarafkaInstance();
instance.setId((Integer) json.get("id"));
instance.setName((String) json.get("name"));
instance.setPlan(CloudKarafkaPlan.of((String) json.get("plan")));
instance.setRegion(CloudKarafkaRegion.of((String) json.get("region")));
instance.setCa((String) json.get("ca"));
instance.setBrokers((String) json.get("brokers"));
instance.setPassword((String) json.get("password"));
instance.setUsername((String) json.get("username"));
instance.setTopicPrefix((String) json.get("topic_prefix"));
return instance;
}
}
|
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/cloudkarafka/CloudKarafkaInstance.java | package am.ik.servicebroker.cloudkarafka.cloudkarafka;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CloudKarafkaInstance implements Serializable {
private Integer id;
private String name;
private CloudKarafkaPlan plan;
private CloudKarafkaRegion region;
private String ca;
private String brokers;
private String username;
private String password;
private String topicPrefix;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CloudKarafkaPlan getPlan() {
return plan;
}
public void setPlan(CloudKarafkaPlan plan) {
this.plan = plan;
}
public CloudKarafkaRegion getRegion() {
return region;
}
public void setRegion(CloudKarafkaRegion region) {
this.region = region;
}
public String getCa() {
return ca;
}
public void setCa(String ca) {
this.ca = ca;
}
public String getBrokers() {
return brokers;
}
public void setBrokers(String brokers) {
this.brokers = brokers;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTopicPrefix() {
return topicPrefix;
}
public void setTopicPrefix(String topicPrefix) {
this.topicPrefix = topicPrefix;
}
@Override
public String toString() {
return "CloudKarafkaInstance{" + "id=" + id + ", name='" + name + '\'' + ", plan="
+ plan + ", region=" + region + ", ca='" + ca + '\'' + ", brokers='"
+ brokers + '\'' + ", username='" + username + '\'' + ", password='"
+ password + '\'' + ", topicPrefix='" + topicPrefix + '\'' + '}';
}
public Credential credential() {
return new Credential(name, brokers, username, password, topicPrefix, ca);
}
public static class Credential {
private final String name;
private final String brokers;
private final String username;
private final String password;
private final String topicPrefix;
private final String ca;
public Credential(String name, String brokers, String username, String password,
String topicPrefix, String ca) {
this.name = name;
this.brokers = brokers;
this.username = username;
this.password = password;
this.topicPrefix = topicPrefix;
this.ca = ca;
}
public String getName() {
return name;
}
public String getBrokers() {
return brokers;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getTopicPrefix() {
return topicPrefix;
}
public String getCa() {
return ca;
}
}
}
|
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/cloudkarafka/CloudKarafkaPlan.java | package am.ik.servicebroker.cloudkarafka.cloudkarafka;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonCreator;
public enum CloudKarafkaPlan {
DUCKY;
@JsonCreator
public static CloudKarafkaPlan of(String value) {
return Arrays.stream(values()).filter(v -> v.name().equalsIgnoreCase(value))
.findAny().orElse(null);
}
@Override
public String toString() {
return name().toLowerCase();
}
} |
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/cloudkarafka/CloudKarafkaRegion.java | package am.ik.servicebroker.cloudkarafka.cloudkarafka;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonCreator;
public enum CloudKarafkaRegion {
GOOGLE_COMPUTE_ENGINE_US_CENTRAL1("google-compute-engine::us-central1"), //
AMAZON_WEB_SERVICES_US_EAST_1("amazon-web-services::us-east-1"), //
AMAZON_WEB_SERVICES_EU_WEST_1("amazon-web-services::eu-west-1");
private final String value;
CloudKarafkaRegion(String value) {
this.value = value;
}
@JsonCreator
public static CloudKarafkaRegion of(String value) {
return Arrays.stream(values()).filter(v -> v.value.equals(value)).findAny()
.orElse(null);
}
@Override
public String toString() {
return this.value;
}
} |
0 | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka | java-sources/am/ik/servicebroker/cloud-karafka-service-broker/0.1.0/am/ik/servicebroker/cloudkarafka/config/SecurityConfig.java | package am.ik.servicebroker.cloudkarafka.config;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //
.mvcMatchers("/actuator/health").permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN") //
.mvcMatchers("/v2/**").hasRole("ADMIN") //
.and() //
.httpBasic() //
.and() //
.csrf().disable() //
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.