repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/AuthorizationException.java | deepl-java/src/main/java/com/deepl/api/AuthorizationException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when the specified authentication key was invalid. */
public class AuthorizationException extends DeepLException {
public AuthorizationException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/Language.java | deepl-java/src/main/java/com/deepl/api/Language.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import org.jetbrains.annotations.Nullable;
/**
* A language supported by DeepL translation. The {@link Translator} class provides functions to
* retrieve the available source and target languages.
*
* @see Translator#getSourceLanguages()
* @see Translator#getTargetLanguages()
*/
public class Language {
private final String name;
private final String code;
private final @Nullable Boolean supportsFormality;
/**
* Initializes a new Language object.
*
* @param name The name of the language in English.
* @param code The language code.
* @param supportsFormality <code>true</code> for a target language that supports the {@link
* TextTranslationOptions#setFormality} option for translations, <code>false</code> for other
* target languages, or <code>null</code> for source languages.
*/
public Language(String name, String code, @Nullable Boolean supportsFormality) {
this.name = name;
this.code = LanguageCode.standardize(code);
this.supportsFormality = supportsFormality;
}
/** @return The name of the language in English, for example "Italian" or "Romanian". */
public String getName() {
return name;
}
/**
* @return The language code, for example "it", "ro" or "en-US". Language codes follow ISO 639-1
* with an optional regional code from ISO 3166-1.
*/
public String getCode() {
return code;
}
/**
* @return <code>true</code> if this language is a target language that supports the {@link
* TextTranslationOptions#setFormality} option for translations, <code>false</code> if this
* language is a target language that does not support formality, or <code>null</code> if this
* language is a source language.
*/
public @Nullable Boolean getSupportsFormality() {
return supportsFormality;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/GlossaryLanguagePair.java | deepl-java/src/main/java/com/deepl/api/GlossaryLanguagePair.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
/**
* Information about a language pair supported for glossaries.
*
* @see Translator#getGlossaryLanguages()
*/
public class GlossaryLanguagePair {
@SerializedName("source_lang")
private final String sourceLang;
@SerializedName("target_lang")
private final String targetLang;
/**
* Initializes a new GlossaryLanguagePair object.
*
* @param sourceLang Language code of the source terms in the glossary.
* @param targetLang Language code of the target terms in the glossary.
*/
public GlossaryLanguagePair(String sourceLang, String targetLang) {
this.sourceLang = LanguageCode.standardize(sourceLang);
this.targetLang = LanguageCode.standardize(targetLang);
}
/** @return Language code of the source terms in the glossary. */
public String getSourceLanguage() {
return sourceLang;
}
/** @return Language code of the target terms in the glossary. */
public String getTargetLanguage() {
return targetLang;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/IGlossary.java | deepl-java/src/main/java/com/deepl/api/IGlossary.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Interface representing a glossary. */
public interface IGlossary {
/** @return Unique ID assigned to the glossary. */
String getGlossaryId();
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/StyleRuleListResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/StyleRuleListResponse.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.StyleRuleInfo;
import java.util.List;
/**
* Class representing v3 style_rules list response by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class StyleRuleListResponse {
private List<StyleRuleInfo> style_rules;
public List<StyleRuleInfo> getStyleRules() {
return style_rules;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/GlossaryLanguagesResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/GlossaryLanguagesResponse.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.*;
import com.google.gson.annotations.*;
import java.util.List;
/**
* Class representing glossary-languages response from the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class GlossaryLanguagesResponse {
@SerializedName("supported_languages")
private List<GlossaryLanguagePair> supportedLanguages;
public List<GlossaryLanguagePair> getSupportedLanguages() {
return supportedLanguages;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryDictionaryEntriesResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryDictionaryEntriesResponse.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.GlossaryEntries;
import com.deepl.api.MultilingualGlossaryDictionaryEntries;
import com.google.gson.annotations.SerializedName;
/**
* Class representing v3 list-glossaries response by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
public class MultilingualGlossaryDictionaryEntriesResponse {
@SerializedName(value = "source_lang")
private final String sourceLanguageCode;
@SerializedName(value = "target_lang")
private final String targetLanguageCode;
@SerializedName(value = "entries")
private final String entries;
@SerializedName(value = "entries_format")
private final String entriesFormat;
/**
* Initializes a new {@link MultilingualGlossaryDictionaryEntriesResponse} containing information
* about a glossary dictionary.
*
* @param sourceLanguageCode the source language for this dictionary
* @param targetLanguageCode the target language for this dictionary
* @param entries the entries in this dictionary
* @param entriesFormat the format of the entries in this dictionary
*/
public MultilingualGlossaryDictionaryEntriesResponse(
String sourceLanguageCode, String targetLanguageCode, String entries, String entriesFormat) {
this.sourceLanguageCode = sourceLanguageCode;
this.targetLanguageCode = targetLanguageCode;
this.entries = entries;
this.entriesFormat = entriesFormat;
}
public MultilingualGlossaryDictionaryEntries getDictionaryEntries() {
return new MultilingualGlossaryDictionaryEntries(
this.sourceLanguageCode,
this.targetLanguageCode,
new GlossaryEntries(GlossaryEntries.fromTsv(this.entries)));
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/WriteResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/WriteResponse.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.WriteResult;
import java.util.List;
/**
* Class representing text rephrase responses from the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class WriteResponse {
public List<WriteResult> improvements;
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/WriteResultDeserializer.java | deepl-java/src/main/java/com/deepl/api/parsing/WriteResultDeserializer.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.WriteResult;
import com.google.gson.*;
import java.lang.reflect.Type;
/**
* Utility class for deserializing text rephrase results returned by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class WriteResultDeserializer implements JsonDeserializer<WriteResult> {
public WriteResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return new WriteResult(
jsonObject.get("text").getAsString(),
jsonObject.get("detected_source_language").getAsString(),
jsonObject.get("target_language").getAsString());
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/TextResultDeserializer.java | deepl-java/src/main/java/com/deepl/api/parsing/TextResultDeserializer.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.TextResult;
import com.google.gson.*;
import java.lang.reflect.Type;
/**
* Utility class for deserializing text translation results returned by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class TextResultDeserializer implements JsonDeserializer<TextResult> {
public TextResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonElement modelType = jsonObject.get("model_type_used");
return new TextResult(
jsonObject.get("text").getAsString(),
jsonObject.get("detected_source_language").getAsString(),
jsonObject.get("billed_characters").getAsInt(),
modelType != null ? (modelType.getAsString()) : null);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryListResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryListResponse.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.MultilingualGlossaryInfo;
import java.util.List;
/**
* Class representing v3 list-glossaries response by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class MultilingualGlossaryListResponse {
private List<MultilingualGlossaryInfo> glossaries;
public List<MultilingualGlossaryInfo> getGlossaries() {
return glossaries;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/UsageDeserializer.java | deepl-java/src/main/java/com/deepl/api/parsing/UsageDeserializer.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.*;
import com.google.gson.*;
import java.lang.reflect.*;
import org.jetbrains.annotations.*;
/**
* Class representing usage responses from the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class UsageDeserializer implements JsonDeserializer<Usage> {
public Usage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return new Usage(
createDetail(jsonObject, "character_"),
createDetail(jsonObject, "document_"),
createDetail(jsonObject, "team_document_"));
}
public static @Nullable Usage.Detail createDetail(JsonObject jsonObject, String prefix) {
Long count = Parser.getAsLongOrNull(jsonObject, prefix + "count");
Long limit = Parser.getAsLongOrNull(jsonObject, prefix + "limit");
if (count == null || limit == null) return null;
return new Usage.Detail(count, limit);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/GlossaryListResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/GlossaryListResponse.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.*;
import java.util.List;
/**
* Class representing list-glossaries response by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class GlossaryListResponse {
private List<GlossaryInfo> glossaries;
public List<GlossaryInfo> getGlossaries() {
return glossaries;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/TextResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/TextResponse.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.TextResult;
import java.util.List;
/**
* Class representing text translation responses from the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class TextResponse {
public List<TextResult> translations;
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryDictionaryListResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/MultilingualGlossaryDictionaryListResponse.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import java.util.List;
/**
* Class representing v3 list-glossaries response by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
public class MultilingualGlossaryDictionaryListResponse {
private List<MultilingualGlossaryDictionaryEntriesResponse> dictionaries;
public List<MultilingualGlossaryDictionaryEntriesResponse> getDictionaries() {
return dictionaries;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/ErrorResponse.java | deepl-java/src/main/java/com/deepl/api/parsing/ErrorResponse.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import org.jetbrains.annotations.Nullable;
/**
* Class representing error messages returned by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class ErrorResponse {
@Nullable private String message;
@Nullable private String detail;
/** Returns a diagnostic string including the message and detail (if available). */
public String getErrorMessage() {
StringBuilder sb = new StringBuilder();
if (getMessage() != null) sb.append("message: ").append(getMessage());
if (getDetail() != null) {
if (sb.length() != 0) sb.append(", ");
sb.append("detail: ").append(getDetail());
}
return sb.toString();
}
public @Nullable String getMessage() {
return message;
}
public @Nullable String getDetail() {
return detail;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/LanguageDeserializer.java | deepl-java/src/main/java/com/deepl/api/parsing/LanguageDeserializer.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.Language;
import com.google.gson.*;
import java.lang.reflect.Type;
/**
* Utility class for deserializing language codes returned by the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
class LanguageDeserializer implements JsonDeserializer<Language> {
public Language deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
Boolean supportsFormality = Parser.getAsBooleanOrNull(jsonObject, "supports_formality");
return new Language(
jsonObject.get("name").getAsString(),
jsonObject.get("language").getAsString(),
supportsFormality);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/parsing/Parser.java | deepl-java/src/main/java/com/deepl/api/parsing/Parser.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.parsing;
import com.deepl.api.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
import java.lang.reflect.*;
import java.util.*;
import org.jetbrains.annotations.*;
/**
* Parsing functions for responses from the DeepL API.
*
* <p>This class is internal; you should not use this class directly.
*/
public class Parser {
private final Gson gson;
public Parser() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(TextResult.class, new TextResultDeserializer());
gsonBuilder.registerTypeAdapter(WriteResult.class, new WriteResultDeserializer());
gsonBuilder.registerTypeAdapter(Language.class, new LanguageDeserializer());
gsonBuilder.registerTypeAdapter(Usage.class, new UsageDeserializer());
gson = gsonBuilder.create();
}
public List<TextResult> parseTextResult(String json) {
TextResponse result = gson.fromJson(json, TextResponse.class);
return result.translations;
}
public List<WriteResult> parseWriteResult(String json) {
WriteResponse result = gson.fromJson(json, WriteResponse.class);
return result.improvements;
}
public Usage parseUsage(String json) {
return gson.fromJson(json, Usage.class);
}
public List<Language> parseLanguages(String json) {
Type languageListType = new TypeToken<ArrayList<Language>>() {}.getType();
return gson.fromJson(json, languageListType);
}
public List<GlossaryLanguagePair> parseGlossaryLanguageList(String json) {
return gson.fromJson(json, GlossaryLanguagesResponse.class).getSupportedLanguages();
}
public DocumentStatus parseDocumentStatus(String json) {
return gson.fromJson(json, DocumentStatus.class);
}
public DocumentHandle parseDocumentHandle(String json) {
return gson.fromJson(json, DocumentHandle.class);
}
public GlossaryInfo parseGlossaryInfo(String json) {
return gson.fromJson(json, GlossaryInfo.class);
}
public MultilingualGlossaryInfo parseMultilingualGlossaryInfo(String json) {
return gson.fromJson(json, MultilingualGlossaryInfo.class);
}
public MultilingualGlossaryDictionaryListResponse parseMultilingualGlossaryDictionaryListResponse(
String json) {
return gson.fromJson(json, MultilingualGlossaryDictionaryListResponse.class);
}
public List<GlossaryInfo> parseGlossaryInfoList(String json) {
GlossaryListResponse result = gson.fromJson(json, GlossaryListResponse.class);
return result.getGlossaries();
}
public List<MultilingualGlossaryInfo> parseMultilingualGlossaryInfoList(String json) {
MultilingualGlossaryListResponse result =
gson.fromJson(json, MultilingualGlossaryListResponse.class);
return result.getGlossaries();
}
public MultilingualGlossaryDictionaryInfo parseMultilingualGlossaryDictionaryInfo(String json) {
return gson.fromJson(json, MultilingualGlossaryDictionaryInfo.class);
}
public List<StyleRuleInfo> parseStyleRuleInfoList(String json) {
StyleRuleListResponse result = gson.fromJson(json, StyleRuleListResponse.class);
return result.getStyleRules();
}
public String parseErrorMessage(String json) {
ErrorResponse response = gson.fromJson(json, ErrorResponse.class);
if (response != null) {
return response.getErrorMessage();
} else {
return "";
}
}
static @Nullable Integer getAsIntOrNull(JsonObject jsonObject, String parameterName) {
if (!jsonObject.has(parameterName)) return null;
return jsonObject.get(parameterName).getAsInt();
}
static @Nullable Long getAsLongOrNull(JsonObject jsonObject, String parameterName) {
if (!jsonObject.has(parameterName)) return null;
return jsonObject.get(parameterName).getAsLong();
}
static @Nullable String getAsStringOrNull(JsonObject jsonObject, String parameterName) {
if (!jsonObject.has(parameterName)) return null;
return jsonObject.get(parameterName).getAsString();
}
static @Nullable Boolean getAsBooleanOrNull(JsonObject jsonObject, String parameterName) {
if (!jsonObject.has(parameterName)) return null;
return jsonObject.get(parameterName).getAsBoolean();
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/utils/BackoffTimer.java | deepl-java/src/main/java/com/deepl/api/utils/BackoffTimer.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.utils;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ThreadLocalRandom;
public class BackoffTimer {
private int numRetries;
private Duration backoff;
private final Duration minTimeout;
private Instant deadline;
private static final Duration backoffInitial = Duration.ofSeconds(1);
private static final Duration backoffMax = Duration.ofSeconds(120);
private static final float jitter = 0.23F;
private static final float multiplier = 1.6F;
public BackoffTimer(Duration minTimeout) {
numRetries = 0;
backoff = backoffInitial;
this.minTimeout = minTimeout;
deadline = Instant.now().plus(backoff);
}
public Duration getTimeout() {
Duration timeToDeadline = getTimeUntilDeadline();
if (timeToDeadline.compareTo(minTimeout) < 0) return minTimeout;
return timeToDeadline;
}
public long getTimeoutMillis() {
return getTimeout().toMillis();
}
public int getNumRetries() {
return numRetries;
}
public void sleepUntilRetry() throws InterruptedException {
try {
Thread.sleep(getTimeUntilDeadline().toMillis());
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw exception;
}
backoff = Duration.ofNanos((long) (backoff.toNanos() * multiplier));
if (backoff.compareTo(backoffMax) > 0) backoff = backoffMax;
float randomJitter = (ThreadLocalRandom.current().nextFloat() * 2.0F - 1.0F) * jitter + 1.0F;
Duration jitteredBackoff = Duration.ofNanos((long) (backoff.toNanos() * randomJitter));
deadline = Instant.now().plus(jitteredBackoff);
++numRetries;
}
private Duration getTimeUntilDeadline() {
Instant currentTime = Instant.now();
if (currentTime.isAfter(deadline)) return Duration.ZERO;
return Duration.between(currentTime, deadline);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/utils/StreamUtil.java | deepl-java/src/main/java/com/deepl/api/utils/StreamUtil.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.utils;
import java.io.*;
import java.nio.charset.*;
public class StreamUtil {
public static final int DEFAULT_BUFFER_SIZE = 1024;
public static String readStream(InputStream inputStream) throws IOException {
Charset charset = StandardCharsets.UTF_8;
final char[] buffer = new char[DEFAULT_BUFFER_SIZE];
final StringBuilder sb = new StringBuilder();
try (InputStreamReader isr = new InputStreamReader(inputStream, charset);
final Reader in = new BufferedReader(isr)) {
int charsRead;
while ((charsRead = in.read(buffer, 0, DEFAULT_BUFFER_SIZE)) > 0) {
sb.append(buffer, 0, charsRead);
}
}
return sb.toString();
}
/**
* Reads all bytes from input stream and writes the bytes to the given output stream in the order
* that they are read. On return, input stream will be at end of stream. This method does not
* close either stream.
*
* <p>Implementation based on {@link InputStream#transferTo(OutputStream)} added in Java 9.
*
* @param inputStream The input stream, non-null.
* @param outputStream The output stream, non-null.
* @return Number of bytes transferred.
* @throws IOException if an I/O error occurs when reading or writing.
*/
public static long transferTo(InputStream inputStream, OutputStream outputStream)
throws IOException {
long transferred = 0;
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int read;
while ((read = inputStream.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {
outputStream.write(buffer, 0, read);
transferred += read;
}
return transferred;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/utils/NamedStream.java | deepl-java/src/main/java/com/deepl/api/utils/NamedStream.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.utils;
import java.io.*;
public class NamedStream {
private final String fileName;
private final InputStream inputStream;
public NamedStream(String fileName, InputStream inputStream) {
this.fileName = fileName;
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public InputStream getInputStream() {
return inputStream;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/utils/KeyValuePair.java | deepl-java/src/main/java/com/deepl/api/utils/KeyValuePair.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.utils;
import java.util.AbstractMap;
public class KeyValuePair<K, V> extends AbstractMap.SimpleEntry<K, V> {
public KeyValuePair(K key, V value) {
super(key, value);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/http/HttpResponse.java | deepl-java/src/main/java/com/deepl/api/http/HttpResponse.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.http;
public class HttpResponse {
private final int code;
private final String body;
public HttpResponse(int code, String body) {
this.code = code;
this.body = body;
}
public int getCode() {
return code;
}
public String getBody() {
return body;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/http/HttpContent.java | deepl-java/src/main/java/com/deepl/api/http/HttpContent.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.http;
import com.deepl.api.*;
import com.deepl.api.utils.*;
import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
import org.jetbrains.annotations.*;
public class HttpContent {
private static final String LINE_BREAK = "\r\n";
private final String contentType;
private final byte[] content;
private HttpContent(String contentType, byte[] content) {
this.contentType = contentType;
this.content = content;
}
public byte[] getContent() {
return content;
}
public String getContentType() {
return contentType;
}
public static HttpContent buildFormURLEncodedContent(
@Nullable Iterable<KeyValuePair<String, String>> params) throws DeepLException {
StringBuilder sb = new StringBuilder();
if (params != null) {
for (KeyValuePair<String, String> pair : params) {
if (sb.length() != 0) sb.append("&");
sb.append(urlEncode(pair.getKey()));
sb.append("=");
sb.append(urlEncode(pair.getValue()));
}
}
return new HttpContent(
"application/x-www-form-urlencoded", sb.toString().getBytes(StandardCharsets.UTF_8));
}
private static String urlEncode(String value) throws DeepLException {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException exception) {
throw new DeepLException("Error while URL-encoding request", exception);
}
}
public static HttpContent buildMultipartFormDataContent(
Iterable<KeyValuePair<String, Object>> params) throws Exception {
String boundary = UUID.randomUUID().toString();
return buildMultipartFormDataContent(params, boundary);
}
private static HttpContent buildMultipartFormDataContent(
Iterable<KeyValuePair<String, Object>> params, String boundary) throws Exception {
try (ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(osw)) {
if (params != null) {
for (KeyValuePair<String, Object> entry : params) {
String key = entry.getKey();
Object value = entry.getValue();
if (entry.getValue() instanceof NamedStream) {
NamedStream namedStream = (NamedStream) entry.getValue();
String probableContentType =
URLConnection.guessContentTypeFromName(namedStream.getFileName());
writer.append("--").append(boundary).append(LINE_BREAK);
writer
.append("Content-Disposition: form-data; name=\"")
.append(key)
.append("\"; filename=\"")
.append(namedStream.getFileName())
.append("\"")
.append(LINE_BREAK);
writer.append("Content-Type: ").append(probableContentType).append(LINE_BREAK);
writer.append("Content-Transfer-Encoding: binary").append(LINE_BREAK);
writer.append(LINE_BREAK);
writer.flush();
StreamUtil.transferTo(namedStream.getInputStream(), stream);
writer.append(LINE_BREAK);
writer.flush();
} else if (value instanceof String) {
writer.append("--").append(boundary).append(LINE_BREAK);
writer
.append("Content-Disposition: form-data; name=\"")
.append(key)
.append("\"")
.append(LINE_BREAK);
writer.append(LINE_BREAK);
writer.append((String) value).append(LINE_BREAK);
writer.flush();
} else {
throw new Exception("Unknown argument type: " + value.getClass().getName());
}
}
}
writer.append("--").append(boundary).append("--").append(LINE_BREAK);
writer.flush();
writer.close();
return new HttpContent("multipart/form-data; boundary=" + boundary, stream.toByteArray());
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/http/HttpResponseStream.java | deepl-java/src/main/java/com/deepl/api/http/HttpResponseStream.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api.http;
import com.deepl.api.*;
import com.deepl.api.utils.*;
import java.io.*;
import org.jetbrains.annotations.*;
public class HttpResponseStream implements AutoCloseable {
private final int code;
@Nullable private final InputStream body;
public HttpResponseStream(int code, @Nullable InputStream body) {
this.code = code;
this.body = body;
}
public void close() {
try {
if (this.body != null) {
this.body.close();
}
} catch (Exception e) {
// ignore
}
}
public HttpResponse toStringResponse() throws DeepLException {
try {
String content = this.body == null ? "" : StreamUtil.readStream(this.body);
return new HttpResponse(getCode(), content);
} catch (IOException exception) {
throw new DeepLException("Error reading stream", exception);
} finally {
close();
}
}
public int getCode() {
return code;
}
public @Nullable InputStream getBody() {
return body;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/examples/maven/deepl-test-app/src/test/java/com/deepl/deepltestapp/DeepLIntegrationTest.java | examples/maven/deepl-test-app/src/test/java/com/deepl/deepltestapp/DeepLIntegrationTest.java | // Copyright 2023 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.deepltestapp;
import com.deepl.api.*;
import com.deepl.deepltestapp.*;
import com.deepl.deepltestapp.annotation.IntegrationTest;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert.*;
import org.junit.experimental.categories.Category;
/**
* Internal DeepL Integration Test
*/
@Category(IntegrationTest.class)
public class DeepLIntegrationTest extends TestCase {
public DeepLIntegrationTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(DeepLIntegrationTest.class);
}
/**
* Runs the hello world example. Requires a DeepL auth key via the DEEPL_AUTH_KEY
* environment variable.
*/
public void testApp() throws InterruptedException, DeepLException {
String result = App.translateHelloWorld();
String[] wordsToCheck = {"Hello", "World"};
for (String wordToCheck : wordsToCheck) {
assertFalse(String.format("Expected translation to no longer contain the english %s, received %s",
wordToCheck, result), result.contains(wordToCheck)
);
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/examples/maven/deepl-test-app/src/main/java/com/deepl/deepltestapp/App.java | examples/maven/deepl-test-app/src/main/java/com/deepl/deepltestapp/App.java | // Copyright 2023 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.deepltestapp;
import com.deepl.api.*;
import java.lang.System.*;
/**
* Hello world translation example
*
*/
public class App {
/**
* Hello world example - insert your API key to test the library.
*/
public static void main( String[] args ) throws InterruptedException, DeepLException {
String authKey = "f63c02c5-f056-..."; // Replace with your key
Translator translator = new Translator(authKey);
TextResult result =
translator.translateText("Hello, world!", null, "fr");
System.out.println(result.getText()); // "Bonjour, le monde !"
}
/////////////////////////////////////////////////////////////////////////////////////
/// These methods are for a test using DeepLs CI pipeline, ignore.
public static String getEnvironmentVariableValue(String envVar) {
return System.getenv(envVar);
}
public static String getAuthKeyFromEnvironmentVariables() {
return getEnvironmentVariableValue("DEEPL_AUTH_KEY");
}
public static String getServerUrlFromEnvironmentVariables() {
return getEnvironmentVariableValue("DEEPL_SERVER_URL");
}
public static String translateHelloWorld() throws InterruptedException, DeepLException {
Translator translator = new Translator(getAuthKeyFromEnvironmentVariables(),
(new TranslatorOptions()).setServerUrl(getServerUrlFromEnvironmentVariables()));
TextResult result =
translator.translateText("Hello, world!", null, "fr");
String translatedText = result.getText();
return translatedText;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/examples/maven/deepl-test-app/src/main/java/com/deepl/deepltestapp/annotation/IntegrationTest.java | examples/maven/deepl-test-app/src/main/java/com/deepl/deepltestapp/annotation/IntegrationTest.java | // Copyright 2023 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.deepltestapp.annotation;
/**
* Marks tests as Integration tests, used for DeepLs internal CI pipeline.
*/
public interface IntegrationTest {}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/MainActivity2.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/MainActivity2.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.tinbytes.samples.showhidetoolbar.util.CityUtils;
import com.tinbytes.samples.showhidetoolbar.util.HelpUtils;
import com.tinbytes.samples.showhidetoolbar.util.RecyclerViewUtils;
public class MainActivity2 extends AppCompatActivity {
// We need a reference to save/restore its state
private RecyclerViewUtils.ShowHideToolbarOnScrollingListener showHideToolbarListener;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Assign Toolbar to the activity
Toolbar tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
getSupportActionBar().setTitle(R.string.app_name);
// RecyclerView with sample data
RecyclerView rvCities = (RecyclerView) findViewById(R.id.rvCities);
rvCities.setLayoutManager(new LinearLayoutManager(this));
rvCities.setAdapter(new CitiesAdapter(CityUtils.CITIES));
rvCities.addOnScrollListener(showHideToolbarListener = new RecyclerViewUtils.ShowHideToolbarOnScrollingListener(tToolbar));
if (savedInstanceState != null) {
showHideToolbarListener.onRestoreInstanceState((RecyclerViewUtils.ShowHideToolbarOnScrollingListener.State) savedInstanceState
.getParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE,
showHideToolbarListener.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
HelpUtils.showAbout(this);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Cities adapter to hold sample data for our RecyclerView.
*/
static class CitiesAdapter extends RecyclerView.Adapter<CitiesAdapter.ViewHolder> {
private String[] data;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
ViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
}
}
CitiesAdapter(String... data) {
this.data = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.city_item, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tvName.setText(data[position]);
}
@Override
public int getItemCount() {
return data.length;
}
}
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/MainActivity.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/MainActivity.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
import com.tinbytes.samples.showhidetoolbar.util.AndroidUtils;
import com.tinbytes.samples.showhidetoolbar.util.CityUtils;
import com.tinbytes.samples.showhidetoolbar.util.HelpUtils;
public class MainActivity extends AppCompatActivity {
// The elevation of the toolbar when content is scrolled behind
private static final float TOOLBAR_ELEVATION = 14f;
// To save/restore recyclerview state on configuration changes
private static final String STATE_RECYCLER_VIEW = "state-recycler-view";
private static final String STATE_VERTICAL_OFFSET = "state-vertical-offset";
private static final String STATE_SCROLLING_OFFSET = "state-scrolling-direction";
private static final String STATE_TOOLBAR_ELEVATION = "state-toolbar-elevation";
private static final String STATE_TOOLBAR_TRANSLATION_Y = "state-toolbar-translation-y";
// We need a reference to the toolbar for hide/show animation
private Toolbar tToolbar;
// We need a reference to the recyclerview to save/restore its state
private RecyclerView rvCities;
// Keeps track of the overall vertical offset in the list
private int verticalOffset;
// Determines the scroll UP/DOWN offset
private int scrollingOffset;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Assign Toolbar to the activity
tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
getSupportActionBar().setTitle(R.string.app_name);
// RecyclerView with sample data
rvCities = (RecyclerView) findViewById(R.id.rvCities);
rvCities.setLayoutManager(new LinearLayoutManager(this));
rvCities.setAdapter(new CitiesAdapter(CityUtils.CITIES));
if (savedInstanceState != null) {
if (AndroidUtils.isLollipop()) {
tToolbar.setElevation(savedInstanceState.getFloat(STATE_TOOLBAR_ELEVATION));
}
tToolbar.setTranslationY(savedInstanceState.getFloat(STATE_TOOLBAR_TRANSLATION_Y));
verticalOffset = savedInstanceState.getInt(STATE_VERTICAL_OFFSET);
scrollingOffset = savedInstanceState.getInt(STATE_SCROLLING_OFFSET);
rvCities.getLayoutManager().onRestoreInstanceState(savedInstanceState.getParcelable(STATE_RECYCLER_VIEW));
}
// We need to detect scrolling changes in the RecyclerView
rvCities.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (scrollingOffset > 0) {
if (verticalOffset > tToolbar.getHeight()) {
toolbarAnimateHide();
} else {
toolbarAnimateShow(verticalOffset);
}
} else if (scrollingOffset < 0) {
if (tToolbar.getTranslationY() < tToolbar.getHeight() * -0.6 && verticalOffset > tToolbar.getHeight()) {
toolbarAnimateHide();
} else {
toolbarAnimateShow(verticalOffset);
}
}
}
}
@Override
public final void onScrolled(RecyclerView recyclerView, int dx, int dy) {
verticalOffset = rvCities.computeVerticalScrollOffset();
scrollingOffset = dy;
int toolbarYOffset = (int) (dy - tToolbar.getTranslationY());
tToolbar.animate().cancel();
if (scrollingOffset > 0) {
if (toolbarYOffset < tToolbar.getHeight()) {
if (verticalOffset > tToolbar.getHeight()) {
toolbarSetElevation(TOOLBAR_ELEVATION);
}
tToolbar.setTranslationY(-toolbarYOffset);
} else {
toolbarSetElevation(0);
tToolbar.setTranslationY(-tToolbar.getHeight());
}
} else if (scrollingOffset < 0) {
if (toolbarYOffset < 0) {
if (verticalOffset <= 0) {
toolbarSetElevation(0);
}
tToolbar.setTranslationY(0);
} else {
if (verticalOffset > tToolbar.getHeight()) {
toolbarSetElevation(TOOLBAR_ELEVATION);
}
tToolbar.setTranslationY(-toolbarYOffset);
}
}
}
});
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onSaveInstanceState(Bundle outState) {
if (AndroidUtils.isLollipop()) {
outState.putFloat(STATE_TOOLBAR_ELEVATION, tToolbar.getElevation());
}
outState.putFloat(STATE_TOOLBAR_TRANSLATION_Y, tToolbar.getTranslationY());
outState.putInt(STATE_VERTICAL_OFFSET, verticalOffset);
outState.putInt(STATE_SCROLLING_OFFSET, scrollingOffset);
outState.putParcelable(STATE_RECYCLER_VIEW, rvCities.getLayoutManager().onSaveInstanceState());
super.onSaveInstanceState(outState);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void toolbarSetElevation(float elevation) {
// setElevation() only works on Lollipop
if (AndroidUtils.isLollipop()) {
tToolbar.setElevation(elevation);
}
}
private void toolbarAnimateShow(final int verticalOffset) {
tToolbar.animate()
.translationY(0)
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
toolbarSetElevation(verticalOffset == 0 ? 0 : TOOLBAR_ELEVATION);
}
});
}
private void toolbarAnimateHide() {
tToolbar.animate()
.translationY(-tToolbar.getHeight())
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
toolbarSetElevation(0);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
HelpUtils.showAbout(this);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Cities adapter to hold sample data for our RecyclerView.
*/
static class CitiesAdapter extends RecyclerView.Adapter<CitiesAdapter.ViewHolder> {
private String[] data;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
ViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
}
}
CitiesAdapter(String... data) {
this.data = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.city_item, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tvName.setText(data[position]);
}
@Override
public int getItemCount() {
return data.length;
}
}
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/RecyclerViewUtils.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/RecyclerViewUtils.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar.util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.animation.LinearInterpolator;
/**
* Helper class for RecyclerView/Toolbar scroll listener.
*/
public final class RecyclerViewUtils {
/**
* This class simplifies the hide/show Toolbar animation depicted in MainActivity.java.
* Check MainActivity2.java to see how to use it.
*/
public static class ShowHideToolbarOnScrollingListener extends RecyclerView.OnScrollListener {
public static final String SHOW_HIDE_TOOLBAR_LISTENER_STATE = "show-hide-toolbar-listener-state";
// The elevation of the toolbar when content is scrolled behind
private static final float TOOLBAR_ELEVATION = 14f;
private Toolbar toolbar;
private State state;
public ShowHideToolbarOnScrollingListener(Toolbar toolbar) {
this.toolbar = toolbar;
this.state = new State();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void toolbarSetElevation(float elevation) {
if (AndroidUtils.isLollipop()) {
toolbar.setElevation(elevation == 0 ? 0 : TOOLBAR_ELEVATION);
}
}
private void toolbarAnimateShow(final int verticalOffset) {
toolbar.animate()
.translationY(0)
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
toolbarSetElevation(verticalOffset == 0 ? 0 : TOOLBAR_ELEVATION);
}
});
}
private void toolbarAnimateHide() {
toolbar.animate()
.translationY(-toolbar.getHeight())
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
toolbarSetElevation(0);
}
});
}
@Override
public final void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (state.scrollingOffset > 0) {
if (state.verticalOffset > toolbar.getHeight()) {
toolbarAnimateHide();
} else {
toolbarAnimateShow(state.verticalOffset);
}
} else if (state.scrollingOffset < 0) {
if (toolbar.getTranslationY() < toolbar.getHeight() * -0.6 && state.verticalOffset > toolbar.getHeight()) {
toolbarAnimateHide();
} else {
toolbarAnimateShow(state.verticalOffset);
}
}
}
}
@Override
public final void onScrolled(RecyclerView recyclerView, int dx, int dy) {
state.verticalOffset = recyclerView.computeVerticalScrollOffset();
state.scrollingOffset = dy;
int toolbarYOffset = (int) (dy - toolbar.getTranslationY());
toolbar.animate().cancel();
if (state.scrollingOffset > 0) {
if (toolbarYOffset < toolbar.getHeight()) {
if (state.verticalOffset > toolbar.getHeight()) {
toolbarSetElevation(TOOLBAR_ELEVATION);
}
toolbar.setTranslationY(state.translationY = -toolbarYOffset);
} else {
toolbarSetElevation(0);
toolbar.setTranslationY(state.translationY = -toolbar.getHeight());
}
} else if (state.scrollingOffset < 0) {
if (toolbarYOffset < 0) {
if (state.verticalOffset <= 0) {
toolbarSetElevation(0);
}
toolbar.setTranslationY(state.translationY = 0);
} else {
if (state.verticalOffset > toolbar.getHeight()) {
toolbarSetElevation(TOOLBAR_ELEVATION);
}
toolbar.setTranslationY(state.translationY = -toolbarYOffset);
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void onRestoreInstanceState(State state) {
this.state.verticalOffset = state.verticalOffset;
this.state.scrollingOffset = state.scrollingOffset;
if (AndroidUtils.isLollipop()) {
toolbar.setElevation(state.elevation);
toolbar.setTranslationY(state.translationY);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public State onSaveInstanceState() {
state.translationY = toolbar.getTranslationY();
if (AndroidUtils.isLollipop()) {
state.elevation = toolbar.getElevation();
}
return state;
}
/**
* Parcelable RecyclerView/Toolbar state for simpler saving/restoring its current state.
*/
public static final class State implements Parcelable {
public static Creator<State> CREATOR = new Creator<State>() {
public State createFromParcel(Parcel parcel) {
return new State(parcel);
}
public State[] newArray(int size) {
return new State[size];
}
};
// Keeps track of the overall vertical offset in the list
private int verticalOffset;
// Determines the scroll UP/DOWN offset
private int scrollingOffset;
// Toolbar values
private float translationY;
private float elevation;
State() {
}
State(Parcel parcel) {
this.verticalOffset = parcel.readInt();
this.scrollingOffset = parcel.readInt();
this.translationY = parcel.readFloat();
this.elevation = parcel.readFloat();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(verticalOffset);
parcel.writeInt(scrollingOffset);
parcel.writeFloat(translationY);
parcel.writeFloat(elevation);
}
}
}
private RecyclerViewUtils() {
}
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/CityUtils.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/CityUtils.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar.util;
/**
* Helper class to hold a bunch of cities.
*/
public final class CityUtils {
public static final String[] CITIES = {
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
"Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
"Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
"Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
"Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
"Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
"Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
"Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
"Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
"Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
"Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
"Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves",
"Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur",
"Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
"Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin",
"Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
"Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
"Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
"Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)",
"Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta",
"Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat",
"Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano",
"Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain",
"Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou",
"Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar",
"Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno",
"Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack",
"Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
"Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)",
"Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese",
"Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
"Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley",
"Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino",
"Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
"Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby",
"Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin",
"Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
"Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue",
"Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz",
"Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich",
"Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue",
"Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle",
"Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia",
"Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis",
"Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus",
"Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison",
"Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois",
"Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse",
"Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese",
"Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise",
"Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra",
"Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
"Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve",
"Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti",
"Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve",
"Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
"Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg",
"Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
"Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese",
"Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere",
"La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire",
"Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou",
"Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings",
"Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse",
"Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam",
"Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego",
"Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)",
"Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse",
"Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda",
"Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte",
"Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne",
"Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)",
"Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster",
"Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca",
"Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre",
"Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty",
"Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano",
"Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage",
"Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry",
"Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid",
"Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn",
"Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin",
"Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin",
"Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre",
"Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone",
"Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark",
"Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit",
"Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia",
"Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)",
"Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna",
"Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera",
"Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou",
"Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder",
"Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort",
"Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr",
"Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin",
"Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre",
"Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss",
"Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela",
"Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda",
"Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain",
"Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese",
"Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale",
"Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie",
"Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri",
"Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar",
"Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance",
"Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes",
"Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet",
"Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe",
"Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa",
"Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois",
"Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
"Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington",
"Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou",
"Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue",
"Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano"
};
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/HelpUtils.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/HelpUtils.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.tinbytes.samples.showhidetoolbar.R;
/**
* Helper class to show a minimalistic About dialog.
*/
public final class HelpUtils {
private static final String ABOUT_DIALOG_TAG = "about_dialog";
public static void showAbout(Activity activity) {
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(ABOUT_DIALOG_TAG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "about_dialog");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
SpannableStringBuilder aboutBody = new SpannableStringBuilder();
aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.about_dialog, null);
TextView tvAbout = (TextView) v.findViewById(R.id.tvAbout);
tvAbout.setText(aboutBody);
tvAbout.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about)
.setView(v)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
).create();
}
}
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
rylexr/android-show-hide-toolbar | https://github.com/rylexr/android-show-hide-toolbar/blob/5497b9d88846564732db8073c77b8fc676da121e/app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/AndroidUtils.java | app/src/main/java/com/tinbytes/samples/showhidetoolbar/util/AndroidUtils.java | /*
* Copyright 2015, Randy Saborio & Tinbytes, Inc.
*
* 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 com.tinbytes.samples.showhidetoolbar.util;
import android.os.Build;
public final class AndroidUtils {
public static boolean isLollipop() {
return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
}
| java | Apache-2.0 | 5497b9d88846564732db8073c77b8fc676da121e | 2026-01-05T02:40:38.492956Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderTest.java | spigui-v2/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderTest.java | package com.samjakob.spigui.toolbar;
import com.samjakob.spigui.item.ItemBuilder;
import org.bukkit.Material;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
public class SGDefaultToolbarBuilderTest {
SGDefaultToolbarBuilder builder = (SGDefaultToolbarBuilder) SGDefaultToolbarBuilderFactory.get().newToolbarBuilder();
@Test
void testPreviousAndNextButtons() {
final ItemBuilder previousButton = builder.initializePreviousPageButton();
final ItemBuilder nextButton = builder.initializeNextPageButton();
assertEquals(Material.ARROW, previousButton.getType());
assertEquals(Material.ARROW, nextButton.getType());
}
@Test
void testCurrentPageIndicator() {
final ItemBuilder currentPageIndicator = builder.initializeCurrentPageIndicator();
assertEquals(Material.NAME_TAG, currentPageIndicator.getType());
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/test/java/com/samjakob/spigui/item/ModernItemBuilderTest.java | spigui-v2/src/test/java/com/samjakob/spigui/item/ModernItemBuilderTest.java | package com.samjakob.spigui.item;
import org.bukkit.Material;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class ModernItemBuilderTest {
@ParameterizedTest
@ValueSource(strings = {
"WHITE", "ORANGE", "MAGENTA", "LIGHT_BLUE", "YELLOW", "LIME", "PINK", "GRAY", "LIGHT_GRAY", "CYAN", "PURPLE",
"BLUE", "BROWN", "GREEN", "RED", "BLACK",
})
void testGetColor(final String color) {
final var expectedItemColor = ItemColor.valueOf(color);
var builder = ItemBuilder.create(Material.valueOf(String.format("%s_WOOL", color)));
assertEquals(expectedItemColor, builder.getColor());
builder = ItemBuilder.create(Material.valueOf(String.format("%s_BED", color)));
assertEquals(expectedItemColor, builder.getColor());
builder = ItemBuilder.create(Material.valueOf(String.format("%s_SHULKER_BOX", color)));
assertEquals(expectedItemColor, builder.getColor());
}
@ParameterizedTest
@ValueSource(strings = {
"WHITE", "ORANGE", "MAGENTA", "LIGHT_BLUE", "YELLOW", "LIME", "PINK", "GRAY", "LIGHT_GRAY", "CYAN", "PURPLE",
"BLUE", "BROWN", "GREEN", "RED", "BLACK",
})
void testSetColor(final String color) {
// The color that the item is to begin with (WHITE, unless the color we want to change it to is WHITE).
final var initialItemColorName = !"WHITE".equals(color) ? "WHITE" : "ORANGE";
// The color that the item should be changed to.
final var expectedItemColor = ItemColor.valueOf(color);
var builder = ItemBuilder.create(Material.valueOf(String.format("%s_WOOL", initialItemColorName)));
assertNotEquals(expectedItemColor, builder.getColor());
builder.color(expectedItemColor);
assertEquals(expectedItemColor, builder.getColor());
builder = ItemBuilder.create(Material.valueOf(String.format("%s_BED", initialItemColorName)));
assertNotEquals(expectedItemColor, builder.getColor());
builder.color(expectedItemColor);
assertEquals(expectedItemColor, builder.getColor());
builder = ItemBuilder.create(Material.valueOf(String.format("%s_SHULKER_BOX", initialItemColorName)));
assertNotEquals(expectedItemColor, builder.getColor());
builder.color(expectedItemColor);
assertEquals(expectedItemColor, builder.getColor());
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/test/java/com/samjakob/spigui/standalone/SpiGUIInitializeTest.java | spigui-v2/src/test/java/com/samjakob/spigui/standalone/SpiGUIInitializeTest.java | package com.samjakob.spigui.standalone;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.menu.SGMenuListenerBase;
import com.samjakob.spigui.toolbar.SGDefaultToolbarBuilderFactory;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class SpiGUIInitializeTest {
@Mock
private JavaPlugin plugin;
@Mock
private Server server;
@Mock
private PluginManager pluginManager;
@Test
void testFactories() {
assertNotNull(ItemBuilder.create(Material.OAK_PLANKS));
assertNotNull(SGDefaultToolbarBuilderFactory.get().newToolbarBuilder());
}
@Test
void testListener() {
given(plugin.getServer()).willReturn(server);
given(server.getPluginManager()).willReturn(pluginManager);
final var spiGUI = new SpiGUI(plugin);
final ArgumentCaptor<SGMenuListenerBase> listenerCaptor = ArgumentCaptor.captor();
verify(pluginManager).registerEvents(listenerCaptor.capture(), eq(plugin));
assertNotNull(listenerCaptor.getValue());
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/main/java/com/samjakob/spigui/InitializeSpiGUI.java | spigui-v2/src/main/java/com/samjakob/spigui/InitializeSpiGUI.java | package com.samjakob.spigui;
import com.samjakob.spigui.item.ModernItemBuilder;
import com.samjakob.spigui.toolbar.SGDefaultToolbarBuilder;
/** Internal helper class used to automatically initialize factories required for SpiGUI. */
final class InitializeSpiGUI {
static {
ModernItemBuilder.register();
SGDefaultToolbarBuilder.register();
}
/** Private constructor. */
private InitializeSpiGUI() {}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilder.java | spigui-v2/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilder.java | package com.samjakob.spigui.toolbar;
import javax.annotation.Nonnull;
import org.bukkit.Material;
import com.samjakob.spigui.item.ItemBuilder;
public class SGDefaultToolbarBuilder extends SGDefaultToolbarBuilderBase {
/**
* Ensures that the {@link SGDefaultToolbarBuilder} has been registered on the
* {@link SGDefaultToolbarBuilderFactory}.
*/
public static void register() {
if (!SGDefaultToolbarBuilderFactory.get().hasSupplier()) {
SGDefaultToolbarBuilderFactory.get().setSupplier(SGDefaultToolbarBuilder::new);
}
}
@Nonnull
@Override
protected ItemBuilder initializePreviousPageButton() {
return ItemBuilder.create(Material.ARROW);
}
@Nonnull
@Override
protected ItemBuilder initializeCurrentPageIndicator() {
return ItemBuilder.create(Material.NAME_TAG);
}
@Nonnull
@Override
protected ItemBuilder initializeNextPageButton() {
return ItemBuilder.create(Material.ARROW);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/main/java/com/samjakob/spigui/item/ModernItemBuilder.java | spigui-v2/src/main/java/com/samjakob/spigui/item/ModernItemBuilder.java | package com.samjakob.spigui.item;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.SkullMeta;
/**
* A modern (1.13+) Minecraft implementation of the {@link ItemBuilderBase} that uses new fields and APIs to customize
* the item stacks.
*/
@SuppressWarnings({"RedundantSuppression", "deprecation"})
public final class ModernItemBuilder implements ItemBuilderBase {
/** Ensures that the {@link ModernItemBuilder} has been registered on the {@link ItemBuilderFactory}. */
public static void register() {
if (!ItemBuilderFactory.get().hasConstructors()) {
ItemBuilderFactory.get().setConstructors(new ItemBuilderConstructors() {
@Override
public ItemBuilderBase create(@Nonnull Material material) {
return new ModernItemBuilder(material);
}
@Override
public ItemBuilderBase from(@Nonnull ItemStack stack) {
return new ModernItemBuilder(stack);
}
});
}
}
/** The item stack being built. */
private final ItemStack stack;
/**
* Constructor for creating a new ItemBuilder with a new internal stack derived from the given {@link Material}.
*
* @param material to create the new stack for.
* @see ItemBuilderBase#create(Material)
*/
private ModernItemBuilder(@Nonnull Material material) {
validateMaterial(material);
this.stack = new ItemStack(material);
}
/**
* Constructor for creating the ItemBuilder with an initial configuration derived from an {@link ItemStack}.
*
* <p><b>NOTE:</b> contrary to before, this method now clones the {@link ItemStack} to ensure that the reference
* passed in is not unexpectedly mutated.
*
* @param stack to create the {@link ModernItemBuilder} from.
* @see ItemBuilderBase#from(ItemStack)
*/
private ModernItemBuilder(@Nonnull ItemStack stack) {
validateMaterial(stack.getType());
this.stack = stack.clone();
}
/**
* Ensures that the specified {@link Material} is a valid material.
*
* @param material to check.
*/
private void validateMaterial(Material material) {
if (material == Material.AIR) {
throw new IllegalArgumentException(
String.format("Cannot create ItemBuilder for invalid stack type: %s", stack.getType()));
}
}
@Nonnull
@Override
public ItemBuilderBase type(@Nonnull Material material) {
stack.setType(material);
return this;
}
@Nonnull
@Override
public Material getType() {
return stack.getType();
}
@Nonnull
@Override
public ItemBuilderBase name(@Nullable String name) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
meta.setDisplayName(name != null ? ChatColor.RESET + ChatColor.translateAlternateColorCodes('&', name) : null);
stack.setItemMeta(meta);
return this;
}
@Nullable
@Override
public String getName() {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (!meta.hasDisplayName()) return null;
return meta.getDisplayName();
}
@Nonnull
@Override
public ItemBuilderBase amount(int amount) {
stack.setAmount(amount);
return this;
}
@Override
public int getAmount() {
return stack.getAmount();
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable String... lore) {
return lore(lore != null ? Arrays.asList(lore) : null);
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable List<String> lore) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (lore != null) {
meta.setLore(lore.stream()
.map(line -> line != null
// Handle color codes on each line.
? ChatColor.RESET + ChatColor.translateAlternateColorCodes('&', line)
// Replace null with an empty line.
: "")
.collect(Collectors.toList()));
} else {
meta.setLore(null);
}
stack.setItemMeta(meta);
return this;
}
@Nullable
@Override
public List<String> getLore() {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (!meta.hasLore()) return null;
return meta.getLore();
}
@Nonnull
@Override
public ItemBuilderBase data(short data) {
throw new UnsupportedOperationException(
"#data(short) is not implemented for Minecraft 1.13+. If you intended to set the color of a colored block, use #color, for durability use #durability. If there's something you were expecting to use this for that is no longer available, please open a GitHub issue.");
}
@Nullable
@Override
public ItemColor getColor() {
// Find a color where the type starts with COLOR_NAME_ (e.g., WHITE_).
return Arrays.stream(ItemColor.values())
.filter(color -> getType().name().startsWith(color.name().concat("_")))
.findAny()
.orElse(null);
}
@Nonnull
@Override
public ItemBuilderBase color(@Nonnull ItemColor color) {
// If we cannot identify the current type as a colored type, do nothing.
final var currentColor = getColor();
if (currentColor == null) return this;
// Attempt to swap the prefix for the other color.
final var currentColorPrefix = String.format("%s_", currentColor);
final String newTypeName = getType().name().replace(currentColorPrefix, String.format("%s_", color.name()));
// If the swapped prefix is still a valid type, change the type.
// Otherwise, do nothing.
try {
final Material newType = Material.valueOf(newTypeName);
return this.type(newType);
} catch (IllegalArgumentException ignored) {
return this;
}
}
@Nonnull
@Override
public ItemBuilderBase durability(int durability) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof Damageable damageable) {
// If there's a limit, check that we're under it.
if (damageable.hasMaxDamage()) {
final int maxDurability = getMaxDurability();
if (durability > maxDurability) {
throw new IllegalArgumentException(String.format(
"Invalid durability (%d). Exceeds maximum permitted value of (%d)",
durability, maxDurability));
}
}
damageable.setDamage(durability);
}
return this;
}
@Override
public int getDurability() {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof Damageable damageable) {
return (short) damageable.getDamage();
}
return 0;
}
@Nonnull
@Override
public ItemBuilderBase maxDurability(int maxDurability) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof Damageable damageable) {
if (damageable.hasMaxDamage()) {
damageable.setMaxDamage(maxDurability);
}
}
return this;
}
@Override
public int getMaxDurability() {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof Damageable damageable) {
if (damageable.hasMaxDamage()) {
return (short) damageable.getMaxDamage();
}
}
return 0;
}
@Nonnull
@Override
public ItemBuilderBase enchant(@Nonnull Enchantment enchantment, int level) {
stack.addUnsafeEnchantment(enchantment, level);
return this;
}
@Nonnull
@Override
public ItemBuilderBase unenchant(@Nonnull Enchantment enchantment) {
stack.removeEnchantment(enchantment);
return this;
}
@Nonnull
@Override
public ItemBuilderBase flag(@Nonnull ItemFlag... flag) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
meta.addItemFlags(flag);
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase deflag(@Nonnull ItemFlag... flag) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
meta.removeItemFlags(flag);
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable String name) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof SkullMeta skullMeta) {
if (name != null) {
skullMeta.setOwningPlayer(
Objects.requireNonNull(Bukkit.getServer().getPlayerExact(name)));
} else {
skullMeta.setOwningPlayer(null);
}
}
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable UUID uuid) {
final var meta = Objects.requireNonNull(stack.getItemMeta());
if (meta instanceof SkullMeta skullMeta) {
if (uuid != null) {
skullMeta.setOwningPlayer(
Objects.requireNonNull(Bukkit.getServer().getOfflinePlayer(uuid)));
} else {
skullMeta.setOwningPlayer(null);
}
}
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemStack build() {
return stack.clone();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui-v2/src/main/java/com/samjakob/spigui/menu/SGMenuListener.java | spigui-v2/src/main/java/com/samjakob/spigui/menu/SGMenuListener.java | package com.samjakob.spigui.menu;
import javax.annotation.Nonnull;
import com.samjakob.spigui.SpiGUI;
/**
* The listener for SpiGUI inventory events.
*
* @see SGMenuListenerBase
*/
public final class SGMenuListener extends SGMenuListenerBase {
/**
* Initialize an SGBaseMenuListener for the specified {@link SpiGUI} instance.
*
* @param spiGUI that this listener is registered for.
*/
public SGMenuListener(@Nonnull SpiGUI spiGUI) {
super(spiGUI);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderTest.java | spigui/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderTest.java | package com.samjakob.spigui.toolbar;
import com.samjakob.spigui.item.ItemBuilder;
import org.bukkit.Material;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
public class SGDefaultToolbarBuilderTest {
SGDefaultToolbarBuilder builder = (SGDefaultToolbarBuilder) SGDefaultToolbarBuilderFactory.get().newToolbarBuilder();
@Test
void testPreviousAndNextButtons() {
final ItemBuilder previousButton = builder.initializePreviousPageButton();
final ItemBuilder nextButton = builder.initializeNextPageButton();
assertEquals(Material.ARROW, previousButton.getType());
assertEquals(Material.ARROW, nextButton.getType());
}
@Test
void testCurrentPageIndicator() {
final ItemBuilder currentPageIndicator = builder.initializeCurrentPageIndicator();
assertEquals(Material.NAME_TAG, currentPageIndicator.getType());
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/test/java/com/samjakob/spigui/standalone/SpiGUIInitializeTest.java | spigui/src/test/java/com/samjakob/spigui/standalone/SpiGUIInitializeTest.java | package com.samjakob.spigui.standalone;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.menu.SGMenuListenerBase;
import com.samjakob.spigui.toolbar.SGDefaultToolbarBuilderFactory;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class SpiGUIInitializeTest {
@Mock
private JavaPlugin plugin;
@Mock
private Server server;
@Mock
private PluginManager pluginManager;
@Test
void testFactories() {
assertNotNull(ItemBuilder.create(Material.WOOD));
assertNotNull(SGDefaultToolbarBuilderFactory.get().newToolbarBuilder());
}
@Test
void testListener() {
given(plugin.getServer()).willReturn(server);
given(server.getPluginManager()).willReturn(pluginManager);
final SpiGUI spiGUI = new SpiGUI(plugin);
final ArgumentCaptor<SGMenuListenerBase> listenerCaptor = ArgumentCaptor.forClass(SGMenuListenerBase.class);
verify(pluginManager).registerEvents(listenerCaptor.capture(), eq(plugin));
assertNotNull(listenerCaptor.getValue());
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/main/java/com/samjakob/spigui/InitializeSpiGUI.java | spigui/src/main/java/com/samjakob/spigui/InitializeSpiGUI.java | package com.samjakob.spigui;
import com.samjakob.spigui.item.LegacyItemBuilder;
import com.samjakob.spigui.toolbar.SGDefaultToolbarBuilder;
/** Internal helper class used to automatically initialize factories required for SpiGUI. */
final class InitializeSpiGUI {
static {
LegacyItemBuilder.register();
SGDefaultToolbarBuilder.register();
}
/** Private constructor. */
private InitializeSpiGUI() {}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilder.java | spigui/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilder.java | package com.samjakob.spigui.toolbar;
import javax.annotation.Nonnull;
import org.bukkit.Material;
import com.samjakob.spigui.item.ItemBuilder;
public class SGDefaultToolbarBuilder extends SGDefaultToolbarBuilderBase {
/**
* Ensures that the {@link SGDefaultToolbarBuilder} has been registered on the
* {@link SGDefaultToolbarBuilderFactory}.
*/
public static void register() {
if (!SGDefaultToolbarBuilderFactory.get().hasSupplier()) {
SGDefaultToolbarBuilderFactory.get().setSupplier(SGDefaultToolbarBuilder::new);
}
}
@Nonnull
@Override
protected ItemBuilder initializePreviousPageButton() {
return ItemBuilder.create(Material.ARROW);
}
@Nonnull
@Override
protected ItemBuilder initializeCurrentPageIndicator() {
return ItemBuilder.create(Material.NAME_TAG);
}
@Nonnull
@Override
protected ItemBuilder initializeNextPageButton() {
return ItemBuilder.create(Material.ARROW);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/main/java/com/samjakob/spigui/item/LegacyItemBuilder.java | spigui/src/main/java/com/samjakob/spigui/item/LegacyItemBuilder.java | package com.samjakob.spigui.item;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
/**
* A legacy (pre-1.13) Minecraft implementation of the {@link ItemBuilderBase} that uses the old metadata fields (e.g.,
* data/durability/damage values).
*/
@SuppressWarnings({"RedundantSuppression", "deprecation"})
public final class LegacyItemBuilder implements ItemBuilderBase {
/** Ensures that the {@link LegacyItemBuilder} has been registered on the {@link ItemBuilderFactory}. */
public static void register() {
if (!ItemBuilderFactory.get().hasConstructors()) {
ItemBuilderFactory.get().setConstructors(new ItemBuilderConstructors() {
@Override
public ItemBuilderBase create(@Nonnull Material material) {
return new LegacyItemBuilder(material);
}
@Override
public ItemBuilderBase from(@Nonnull ItemStack stack) {
return new LegacyItemBuilder(stack);
}
});
}
}
/** The item stack being built. */
private final ItemStack stack;
/**
* Constructor for creating a new ItemBuilder with a new internal stack derived from the given {@link Material}.
*
* @param material to create the new stack for.
* @see ItemBuilderBase#create(Material)
*/
private LegacyItemBuilder(@Nonnull Material material) {
validateMaterial(material);
this.stack = new ItemStack(material);
}
/**
* Constructor for creating the ItemBuilder with an initial configuration derived from an {@link ItemStack}.
*
* <p><b>NOTE:</b> contrary to before, this method now clones the {@link ItemStack} to ensure that the reference
* passed in is not unexpectedly mutated.
*
* @param stack to create the {@link LegacyItemBuilder} from.
* @see ItemBuilderBase#from(ItemStack)
*/
private LegacyItemBuilder(@Nonnull ItemStack stack) {
validateMaterial(stack.getType());
this.stack = stack.clone();
}
/**
* Ensures that the specified {@link Material} is a valid material.
*
* @param material to check.
*/
private void validateMaterial(Material material) {
if (material == Material.AIR) {
throw new IllegalArgumentException(
String.format("Cannot create ItemBuilder for invalid stack type: %s", stack.getType()));
}
}
@Nonnull
@Override
public LegacyItemBuilder type(@Nonnull Material material) {
stack.setType(material);
return this;
}
@Nonnull
@Override
public Material getType() {
return stack.getType();
}
@Nonnull
@Override
public ItemBuilderBase name(@Nullable String name) {
ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
meta.setDisplayName(name != null ? ChatColor.RESET + ChatColor.translateAlternateColorCodes('&', name) : null);
stack.setItemMeta(meta);
return this;
}
@Nullable
@Override
public String getName() {
final ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
if (!meta.hasDisplayName()) return null;
return meta.getDisplayName();
}
@Nonnull
@Override
public ItemBuilderBase amount(int amount) {
stack.setAmount(amount);
return this;
}
@Override
public int getAmount() {
return stack.getAmount();
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable final String... lore) {
return lore(lore != null ? Arrays.asList(lore) : null);
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable final List<String> lore) {
final ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
if (lore != null) {
meta.setLore(lore.stream()
.map(line -> line != null
// Handle color codes on each line.
? ChatColor.RESET + ChatColor.translateAlternateColorCodes('&', line)
// Replace null with an empty line.
: "")
.collect(Collectors.toList()));
} else {
meta.setLore(null);
}
stack.setItemMeta(meta);
return this;
}
@Nullable
@Override
public List<String> getLore() {
final ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
if (!meta.hasLore()) return null;
return meta.getLore();
}
@Nonnull
@Override
public ItemBuilderBase color(@Nonnull ItemColor color) {
return durability(
LegacyItemDataColor.getByColor(Objects.requireNonNull(color)).getDurability());
}
@Nonnull
@Override
public ItemBuilderBase data(short data) {
return durability(data);
}
@Nonnull
@Override
public ItemBuilderBase durability(int durability) {
final int maxDurability = getMaxDurability();
if (durability > maxDurability) {
throw new IllegalArgumentException(String.format(
"Invalid durability (%d). Exceeds maximum permitted value of (%d)", durability, maxDurability));
}
stack.setDurability((short) durability);
return this;
}
@Override
public int getDurability() {
return stack.getDurability();
}
@Nonnull
@Override
public ItemBuilderBase maxDurability(int maxDurability) {
/* no-op */
return this;
}
@Override
public int getMaxDurability() {
return Short.MAX_VALUE;
}
@Nullable
@Override
public ItemColor getColor() {
return Optional.ofNullable(LegacyItemDataColor.getByDurability(stack.getDurability()))
.map(LegacyItemDataColor::getColor)
.orElse(null);
}
@Nonnull
@Override
public ItemBuilderBase enchant(@Nonnull Enchantment enchantment, int level) {
stack.addUnsafeEnchantment(enchantment, level);
return this;
}
@Nonnull
@Override
public ItemBuilderBase unenchant(@Nonnull Enchantment enchantment) {
stack.removeEnchantment(enchantment);
return this;
}
@Nonnull
@Override
public ItemBuilderBase flag(@Nonnull ItemFlag... flag) {
ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
meta.addItemFlags(flag);
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase deflag(@Nonnull ItemFlag... flag) {
ItemMeta meta = Objects.requireNonNull(stack.getItemMeta());
meta.removeItemFlags(flag);
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable String name) {
ItemMeta itemMeta = Objects.requireNonNull(stack.getItemMeta());
if (!(itemMeta instanceof SkullMeta)) return this;
final SkullMeta meta = (SkullMeta) itemMeta;
stack.setDurability((byte) 3);
meta.setOwner(name);
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable UUID uuid) {
final ItemMeta itemMeta = Objects.requireNonNull(stack.getItemMeta());
if (!(itemMeta instanceof SkullMeta)) return this;
final SkullMeta meta = (SkullMeta) itemMeta;
stack.setDurability((byte) 3);
if (uuid == null) {
meta.setOwner(null);
} else {
meta.setOwner(Objects.requireNonNull(
Bukkit.getServer().getOfflinePlayer(uuid),
String.format("Unrecognized player UUID: %s", uuid))
.getName());
}
stack.setItemMeta(meta);
return this;
}
@Nonnull
@Override
public ItemStack build() {
return stack.clone();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/main/java/com/samjakob/spigui/item/LegacyItemDataColor.java | spigui/src/main/java/com/samjakob/spigui/item/LegacyItemDataColor.java | package com.samjakob.spigui.item;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Items such as glass panes can have variable color. This color is set using durability values which is understandable
* from an efficiency perspective however it is rather unintuitive and the values are not clear or memorable.
*
* <p>This class allows those damage values to be referred to by the name of the color they represent.
*
* <p><b>NOTE:</b> this class is made public for convenience to those using legacy versions of Minecraft (e.g., 1.8).
* <b>However,</b> if you intend to upgrade or support later versions you should <i>avoid</i> using (and certainly avoid
* relying on) this class.
*
* @author SamJakob
* @version 2.0.0
*/
public enum LegacyItemDataColor {
/** Value is 0. Use WHITE_WOOL for 1.13+ */
WHITE(ItemColor.WHITE, (short) 0),
/** Value is 1. Use ORANGE_WOOL for 1.13+ */
ORANGE(ItemColor.ORANGE, (short) 1),
/** Value is 2. Use MAGENTA_WOOL for 1.13+ */
MAGENTA(ItemColor.MAGENTA, (short) 2),
/** Value is 3. Use LIGHT_BLUE_WOOL for 1.13+ */
LIGHT_BLUE(ItemColor.LIGHT_BLUE, (short) 3),
/** Value is 4. Use YELLOW_WOOL for 1.13+ */
YELLOW(ItemColor.YELLOW, (short) 4),
/** Value is 5. Use LIME_WOOL for 1.13+ */
LIME(ItemColor.LIME, (short) 5),
/** Value is 6. Use PINK_WOOL for 1.13+ */
PINK(ItemColor.PINK, (short) 6),
/** Value is 7. Use GRAY_WOOL for 1.13+ */
GRAY(ItemColor.GRAY, (short) 7),
/** Value is 8. Use LIGHT_GRAY_WOOL for 1.13+ */
LIGHT_GRAY(ItemColor.LIGHT_GRAY, (short) 8),
/** Value is 9. Use CYAN_WOOL for 1.13+ */
CYAN(ItemColor.CYAN, (short) 9),
/** Value is 10. Use PURPLE_WOOL for 1.13+ */
PURPLE(ItemColor.PURPLE, (short) 10),
/** Value is 11. Use BLUE_WOOL for 1.13+ */
BLUE(ItemColor.BLUE, (short) 11),
/** Value is 12. Use BROWN_WOOL for 1.13+ */
BROWN(ItemColor.BROWN, (short) 12),
/** Value is 13. Use GREEN_WOOL for 1.13+ */
GREEN(ItemColor.GREEN, (short) 13),
/** Value is 14. Use RED_WOOL for 1.13+ */
RED(ItemColor.RED, (short) 14),
/** Value is 15. Use BLACK_WOOL for 1.13+ */
BLACK(ItemColor.BLACK, (short) 15);
/** The public-facing {@link ItemColor}. */
@Nonnull
private final ItemColor color;
/** The durability value of the color. */
private final short durability;
/**
* Define a {@link LegacyItemDataColor} based on a given short value.
*
* @param color The public-facing {@link ItemColor} API value.
* @param durability The color value (as a durability value). Must be between 0 and 15, per Minecraft's color
* mapping.
*/
LegacyItemDataColor(@Nonnull ItemColor color, short durability) {
this.color = Objects.requireNonNull(color);
this.durability = sanitizeDurability(durability);
}
/**
* Returns the public-facing {@link ItemColor} value.
*
* @return The color value.
*/
@Nonnull
public ItemColor getColor() {
return color;
}
/**
* Returns the durability value that the named color represents.
*
* @return The durability value as a 'short'.
*/
public short getDurability() {
return durability;
}
/**
* Returns a {@link LegacyItemDataColor} as found by its damage value, or null if there isn't one.
*
* @param value The corresponding damage value of the color.
* @return The {@link LegacyItemDataColor} associated with {@code value}, or null if there isn't one.
*/
@Nullable
public static LegacyItemDataColor getByDurability(short value) {
sanitizeDurability(value);
return Arrays.stream(values())
.filter(it -> value == it.durability)
.findAny()
.orElseThrow(() -> new NoSuchElementException(
String.format("No LegacyItemDataColor value found for durability value: %d", value)));
}
/**
* Returns a {@link LegacyItemDataColor} as found by the corresponding public-facing {@link ItemColor}, or null if
* there isn't one.
*
* @param color The corresponding public API value of the color.
* @return The {@link LegacyItemDataColor} associated with {@code color}, or null if there isn't one.
*/
@Nonnull
public static LegacyItemDataColor getByColor(@Nonnull ItemColor color) {
Objects.requireNonNull(color);
return Arrays.stream(values())
.filter(it -> it.color == color)
.findFirst()
.orElseThrow(() -> new NoSuchElementException(
String.format("Missing LegacyItemDataColor for ItemColor(%s)", color.name())));
}
/**
* Ensure that the provided {@code durability} value is one that can be interpreted as a color (i.e., between 0 and
* 15).
*
* @param durability value to check
* @return the same durability value.
* @throws IllegalArgumentException if the durability value is unknown or invalid.
*/
private static short sanitizeDurability(final short durability) {
if (durability > 15 || durability < 0) {
throw new IllegalArgumentException("Durability value must be between 0 and 15 (inclusive).");
}
return durability;
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/spigui/src/main/java/com/samjakob/spigui/menu/SGMenuListener.java | spigui/src/main/java/com/samjakob/spigui/menu/SGMenuListener.java | package com.samjakob.spigui.menu;
import javax.annotation.Nonnull;
import com.samjakob.spigui.SpiGUI;
/**
* The listener for SpiGUI inventory events.
*
* @see SGMenuListenerBase
*/
public final class SGMenuListener extends SGMenuListenerBase {
/**
* Initialize an SGBaseMenuListener for the specified {@link SpiGUI} instance.
*
* @param spiGUI that this listener is registered for.
*/
public SGMenuListener(@Nonnull SpiGUI spiGUI) {
super(spiGUI);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/test/java/com/samjakob/spigui/MockItemBuilder.java | core/src/test/java/com/samjakob/spigui/MockItemBuilder.java | package com.samjakob.spigui;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.item.ItemBuilderBase;
import com.samjakob.spigui.item.ItemColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.mockito.quality.Strictness;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class MockItemBuilder implements ItemBuilderBase {
@Nonnull
private Material material;
private String name;
private int amount;
private List<String> lore;
private ItemColor color;
private int durability;
private int maxDurability;
private final Map<Enchantment, Integer> enchantments = new HashMap<>();
private final Set<ItemFlag> flags = new HashSet<>();
private String skullOwner;
public MockItemBuilder(@Nonnull Material material) {
this.material = material;
this.amount = 1;
}
@Nonnull
@Override
public ItemBuilderBase type(@Nonnull Material material) {
this.material = Objects.requireNonNull(material);
return this;
}
@Nonnull
@Override
public Material getType() {
return material;
}
@Nonnull
@Override
public ItemBuilderBase name(@Nullable String name) {
this.name = name;
return this;
}
@Nullable
@Override
public String getName() {
return name;
}
@Nonnull
@Override
public ItemBuilderBase amount(int amount) {
this.amount = amount;
return this;
}
@Override
public int getAmount() {
return amount;
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable String... lore) {
this.lore = lore != null ? Arrays.asList(lore) : null;
return this;
}
@Nonnull
@Override
public ItemBuilderBase lore(@Nullable List<String> lore) {
this.lore = lore;
return this;
}
@Nullable
@Override
public List<String> getLore() {
return new ArrayList<>(this.lore);
}
@Nonnull
@Override
public ItemBuilderBase color(@Nonnull ItemColor color) {
this.color = color;
return this;
}
@Nullable
@Override
public ItemColor getColor() {
return color;
}
@Nonnull
@Override
public ItemBuilderBase data(short data) {
this.durability = data;
return this;
}
@Nonnull
@Override
public ItemBuilderBase durability(int durability) {
this.durability = durability;
return this;
}
@Override
public int getDurability() {
return durability;
}
@Nonnull
@Override
public ItemBuilderBase maxDurability(int maxDurability) {
this.maxDurability = maxDurability;
return this;
}
@Override
public int getMaxDurability() {
return maxDurability;
}
@Nonnull
@Override
public ItemBuilderBase enchant(@Nonnull Enchantment enchantment, int level) {
enchantments.put(enchantment, level);
return this;
}
@Nonnull
@Override
public ItemBuilderBase unenchant(@Nonnull Enchantment enchantment) {
enchantments.remove(enchantment);
return this;
}
@Nonnull
@Override
public ItemBuilderBase flag(@Nonnull ItemFlag... flag) {
flags.addAll(Arrays.asList(flag));
return this;
}
@Nonnull
@Override
public ItemBuilderBase deflag(@Nonnull ItemFlag... flag) {
Arrays.asList(flag).forEach(flags::remove);
return this;
}
@Nonnull
@Override
@Deprecated
public ItemBuilderBase skullOwner(@Nullable String name) {
this.skullOwner = name;
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable UUID uuid) {
this.skullOwner = String.valueOf(uuid);
return this;
}
/**
* Builds a mock {@link ItemStack} and {@link ItemMeta} (that is returned for {@link ItemStack#getItemMeta()}).
*
* <p>The behavior of the mocks is to simply return whatever was passed in (e.g., setting the item stack amount with
* {@link #amount(int)} will cause the mocked {@link #getAmount()} to return the previously set amount).
*
* <p>As such, some implied behaviors will be unavailable - for instance, the implicit link between {@link Material}
* and {@link #getColor()} in later versions of the game and similarly between {@link #data(short)} and
* {@link #durability(int)} in older versions of the game. This will need to be addressed with additional
* scaffolding in the tests if that behavior is relevant.
*
* <p>Both mocks are configured with {@link Strictness#LENIENT} so that all supported aspects of the item stacks can
* be mocked (naturally, without forcing the consumer to utilize all of the stubs).
*
* @return a mock {@link ItemStack} with mock {@link ItemMeta}.
*/
@Nonnull
@Override
public ItemStack build() {
final ItemStack result = mock(ItemStack.class, withSettings().strictness(Strictness.LENIENT));
when(result.getAmount()).thenReturn(amount);
when(result.getDurability()).thenReturn((short) durability);
when(result.getType()).thenReturn(material);
when(result.getEnchantmentLevel(any(Enchantment.class))).thenAnswer(invocation -> enchantments.getOrDefault(invocation.getArgument(0, Enchantment.class), 0));
when(result.getEnchantments()).thenReturn(enchantments);
final ItemMeta resultMeta = mock(ItemMeta.class, withSettings().strictness(Strictness.LENIENT));
when(resultMeta.getLore()).thenReturn(lore);
when(resultMeta.getDisplayName()).thenReturn(name);
when(resultMeta.getItemFlags()).thenReturn(flags);
when(resultMeta.getEnchantLevel(any(Enchantment.class))).thenAnswer(invocation -> enchantments.getOrDefault(invocation.getArgument(0, Enchantment.class), 0));
when(resultMeta.getEnchants()).thenReturn(enchantments);
when(result.getItemMeta()).thenReturn(resultMeta);
return result;
}
/**
* Wraps the {@link MockItemBuilder} with an {@link ItemBuilder} so it can be used in those APIs.
*
* @return the wrapped {@link MockItemBuilder}.
*/
public ItemBuilder asItemBuilder() {
Constructor<ItemBuilder> constructor;
try {
constructor = ItemBuilder.class.getDeclaredConstructor(ItemBuilderBase.class);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
// Suppress the Java (private variable) access checks.
constructor.setAccessible(true);
try {
// Construct the instance.
return constructor.newInstance(this);
} catch (InvocationTargetException | InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
} finally {
// Re-enable the Java access checks.
constructor.setAccessible(false);
}
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/test/java/com/samjakob/spigui/buttons/SGButtonTest.java | core/src/test/java/com/samjakob/spigui/buttons/SGButtonTest.java | package com.samjakob.spigui.buttons;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SGButtonTest {
final ItemStack dirt = new ItemStack(Material.DIRT);
SGButton button;
@BeforeEach
void setup() {
button = new SGButton(dirt);
}
@Test
void testRequiresIcon() {
//noinspection DataFlowIssue - using null for test.
assertThrowsExactly(NullPointerException.class, () -> new SGButton(null));
}
@Test
void testConstruction() {
assertEquals(dirt, button.getIcon());
assertNull(button.getListener());
}
@Test
void testSetIcon() {
assertEquals(dirt, button.getIcon());
final ItemStack stone = new ItemStack(Material.STONE);
button.setIcon(stone);
assertEquals(stone, button.getIcon());
}
@Test
void testSetListener() {
assertNull(button.getListener());
final SGButtonListener listener = (e) -> {};
button.setListener(listener);
assertEquals(listener, button.getListener());
}
@Test
void testDoesNotAllowAirAsIcon() {
assertThrowsExactly(IllegalArgumentException.class, () -> new SGButton(new ItemStack(Material.AIR)));
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/test/java/com/samjakob/spigui/toolbar/SGToolbarButtonTypeTest.java | core/src/test/java/com/samjakob/spigui/toolbar/SGToolbarButtonTypeTest.java | package com.samjakob.spigui.toolbar;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SGToolbarButtonTypeTest {
@Test
void testGetDefaultForSlot() {
assertEquals(SGToolbarButtonType.PREV_BUTTON, SGToolbarButtonType.getDefaultForSlot(3));
assertEquals(SGToolbarButtonType.CURRENT_BUTTON, SGToolbarButtonType.getDefaultForSlot(4));
assertEquals(SGToolbarButtonType.NEXT_BUTTON, SGToolbarButtonType.getDefaultForSlot(5));
// Invalid values should map to UNASSIGNED.
assertEquals(SGToolbarButtonType.UNASSIGNED, SGToolbarButtonType.getDefaultForSlot(-1));
assertEquals(SGToolbarButtonType.UNASSIGNED, SGToolbarButtonType.getDefaultForSlot(Integer.MAX_VALUE));
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderBaseTest.java | core/src/test/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderBaseTest.java | package com.samjakob.spigui.toolbar;
import com.samjakob.spigui.MockItemBuilder;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.menu.SGMenu;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.Event;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import javax.annotation.Nonnull;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
/**
* These tests check the labelling of buttons.
*
* <p>As such, they are fairly specific tests, so if these labels are changed often, this methodology might need to be
* changed.
*
* <p>This is mostly here as a regression test.
*/
@ExtendWith(MockitoExtension.class)
class SGDefaultToolbarBuilderBaseTest {
private static final int MOCK_CURRENT_PAGE_INDEX = 2;
private static final int MOCK_MAX_PAGE_INDEX = 4;
@Mock
private SGMenu menu;
private final SGDefaultToolbarBuilderBase builder = new SGDefaultToolbarBuilderBase() {
@Nonnull
@Override
protected ItemBuilder initializePreviousPageButton() {
return new MockItemBuilder(Material.ARROW).asItemBuilder();
}
@Nonnull
@Override
protected ItemBuilder initializeCurrentPageIndicator() {
return new MockItemBuilder(Material.NAME_TAG).asItemBuilder();
}
@Nonnull
@Override
protected ItemBuilder initializeNextPageButton() {
return new MockItemBuilder(Material.ARROW).asItemBuilder();
}
};
@BeforeEach
void setup() {
given(menu.getCurrentPage()).willReturn(MOCK_CURRENT_PAGE_INDEX);
}
@Test
void testPreviousPageButtonLabelling() {
assertTrue(builder.getPreviousPageLabelBuilder().buildName(menu).toLowerCase().contains("previous"));
assertTrue(String.join("\n", builder.getPreviousPageDescriptionBuilder().buildLore(menu)).toLowerCase().contains("page 2"));
}
@Test
void testCurrentPageButtonLabelling() {
given(menu.getMaxPageNumber()).willReturn(MOCK_MAX_PAGE_INDEX + 1);
assertTrue(builder.getCurrentPageLabelBuilder().buildName(menu).toLowerCase().contains("page 3 of 5"));
assertTrue(String.join("\n", builder.getCurrentPageDescriptionBuilder().buildLore(menu)).toLowerCase().contains("page 3"));
}
@Test
void testNextPageButtonLabelling() {
assertTrue(builder.getNextPageLabelBuilder().buildName(menu).toLowerCase().contains("next"));
assertTrue(String.join("\n", builder.getNextPageDescriptionBuilder().buildLore(menu)).toLowerCase().contains("page 4"));
}
@Test
void testConstructPreviousPageButton() {
final String expectedPreviousButtonLabel = builder.getPreviousPageLabelBuilder().buildName(menu);
final List<String> expectedPreviousButtonDescription = builder.getPreviousPageDescriptionBuilder().buildLore(menu);
// Build the button and ensure that a valid result has been produced for the "PREV_BUTTON" slot.
final SGButton previousButton = builder.buildToolbarButton(SGToolbarButtonType.PREV_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.PREV_BUTTON, menu);
assertNotNull(previousButton);
assertNotNull(previousButton.getIcon());
assertNotNull(previousButton.getListener());
// Check that the icon has been built correctly.
assertEquals(Material.ARROW, previousButton.getIcon().getType());
assertEquals(expectedPreviousButtonLabel, previousButton.getIcon().getItemMeta().getDisplayName());
assertEquals(expectedPreviousButtonDescription, previousButton.getIcon().getItemMeta().getLore());
}
@Test
void testConstructCurrentPageButton() {
final String expectedCurrentButtonLabel = builder.getCurrentPageLabelBuilder().buildName(menu);
final List<String> expectedCurrentButtonDescription = builder.getCurrentPageDescriptionBuilder().buildLore(menu);
// Build the button and ensure that a valid result has been produced for the "CURRENT_BUTTON" slot.
final SGButton currentButton = builder.buildToolbarButton(SGToolbarButtonType.CURRENT_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.CURRENT_BUTTON, menu);
assertNotNull(currentButton);
assertNotNull(currentButton.getIcon());
assertNotNull(currentButton.getListener());
// Check that the icon has been built correctly.
assertEquals(Material.NAME_TAG, currentButton.getIcon().getType());
assertEquals(expectedCurrentButtonLabel, currentButton.getIcon().getItemMeta().getDisplayName());
assertEquals(expectedCurrentButtonDescription, currentButton.getIcon().getItemMeta().getLore());
}
@Test
void testConstructNextPageButton() {
given(menu.getMaxPageNumber()).willReturn(MOCK_MAX_PAGE_INDEX + 1);
given(menu.getMaxPageIndex()).willCallRealMethod();
final String expectedNextButtonLabel = builder.getNextPageLabelBuilder().buildName(menu);
final List<String> expectedNextButtonDescription = builder.getNextPageDescriptionBuilder().buildLore(menu);
// Build the button and ensure that a valid result has been produced for the "NEXT_BUTTON" slot.
final SGButton nextButton = builder.buildToolbarButton(SGToolbarButtonType.NEXT_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.NEXT_BUTTON, menu);
assertNotNull(nextButton);
assertNotNull(nextButton.getIcon());
assertNotNull(nextButton.getListener());
// Check that the icon has been built correctly.
assertEquals(Material.ARROW, nextButton.getIcon().getType());
assertEquals(expectedNextButtonLabel, nextButton.getIcon().getItemMeta().getDisplayName());
assertEquals(expectedNextButtonDescription, nextButton.getIcon().getItemMeta().getLore());
}
@Test
void testPreviousPageButtonHandler() {
// Construct the button to test with.
final SGButton previousButton = builder.buildToolbarButton(SGToolbarButtonType.PREV_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.PREV_BUTTON, menu);
assertNotNull(previousButton);
assertNotNull(previousButton.getListener());
// Invoke the listener and check that the correct behaviors are observed.
final InventoryClickEvent event = mock(InventoryClickEvent.class);
final HumanEntity viewer = mock(HumanEntity.class);
given(event.getWhoClicked()).willReturn(viewer);
// Click the "previous page" button.
previousButton.getListener().onClick(event);
// We consider verifying that "previousPage" is called to be good enough here - as we assume that the test for
// the menu itself will ensure that invoking previousPage reduces the current page index by one where possible.
verify(menu, times(1)).previousPage(viewer);
verify(event, times(1)).setResult(Event.Result.DENY);
verifyNoMoreInteractions(event);
verifyNoMoreInteractions(menu);
}
@Test
void testCurrentPageIndicatorHandler() {
given(menu.getMaxPageNumber()).willReturn(MOCK_MAX_PAGE_INDEX + 1);
// Construct the button to test with.
final SGButton currentPageIndicator = builder.buildToolbarButton(SGToolbarButtonType.CURRENT_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.CURRENT_BUTTON, menu);
assertNotNull(currentPageIndicator);
assertNotNull(currentPageIndicator.getListener());
// Invoke the listener and check that the correct behaviors are observed.
final InventoryClickEvent event = mock(InventoryClickEvent.class);
final HumanEntity viewer = mock(HumanEntity.class);
// Click the "current page" indicator.
currentPageIndicator.getListener().onClick(event);
verify(event, times(1)).setResult(Event.Result.DENY);
verifyNoMoreInteractions(event);
verifyNoMoreInteractions(menu);
}
@Test
void testNextPageButtonHandler() {
given(menu.getMaxPageNumber()).willReturn(MOCK_MAX_PAGE_INDEX + 1);
given(menu.getMaxPageIndex()).willCallRealMethod();
// Construct the button to test with.
final SGButton nextButton = builder.buildToolbarButton(SGToolbarButtonType.NEXT_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.NEXT_BUTTON, menu);
assertNotNull(nextButton);
assertNotNull(nextButton.getListener());
// Invoke the listener and check that the correct behaviors are observed.
final InventoryClickEvent event = mock(InventoryClickEvent.class);
final HumanEntity viewer = mock(HumanEntity.class);
given(event.getWhoClicked()).willReturn(viewer);
// Click the "next page" button.
nextButton.getListener().onClick(event);
// As with previous page.
verify(menu, times(1)).nextPage(viewer);
verify(event, times(1)).setResult(Event.Result.DENY);
verifyNoMoreInteractions(event);
verifyNoMoreInteractions(menu);
}
@Test
void testUnassigned() {
assertNull(builder.buildToolbarButton(0, MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.UNASSIGNED, menu));
assertNull(builder.buildToolbarButton(9, MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.UNASSIGNED, menu));
// Alternatively, we may wish to throw for completely invalid values.
// It's a consideration, but I haven't seen a reason to do this (yet), so I'll leave it as UNASSIGNED.
assertNull(builder.buildToolbarButton(-1, MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.UNASSIGNED, menu));
}
@Test
void testPageBounds() {
// With the given initial state that all of the tests are performed with, the toolbar should render both
// previous and next buttons (current page is always rendered).
given(menu.getMaxPageNumber()).willReturn(MOCK_MAX_PAGE_INDEX + 1);
given(menu.getMaxPageIndex()).willCallRealMethod();
assertNotNull(builder.buildToolbarButton(SGToolbarButtonType.PREV_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.PREV_BUTTON, menu));
assertNotNull(builder.buildToolbarButton(SGToolbarButtonType.NEXT_BUTTON.requireDefaultSlot(), MOCK_CURRENT_PAGE_INDEX, SGToolbarButtonType.NEXT_BUTTON, menu));
// Now, if we're at the first page (index = 0), only the next button should show.
given(menu.getCurrentPage()).willReturn(0);
assertNull(builder.buildToolbarButton(SGToolbarButtonType.PREV_BUTTON.requireDefaultSlot(), 0, SGToolbarButtonType.PREV_BUTTON, menu));
assertNotNull(builder.buildToolbarButton(SGToolbarButtonType.NEXT_BUTTON.requireDefaultSlot(), 0, SGToolbarButtonType.NEXT_BUTTON, menu));
// Similarly, if we're at the last page (index = MOCK_MAX_PAGE_INDEX), only the previous button should show.
given(menu.getCurrentPage()).willReturn(MOCK_MAX_PAGE_INDEX);
assertNotNull(builder.buildToolbarButton(SGToolbarButtonType.PREV_BUTTON.requireDefaultSlot(), MOCK_MAX_PAGE_INDEX, SGToolbarButtonType.PREV_BUTTON, menu));
assertNull(builder.buildToolbarButton(SGToolbarButtonType.NEXT_BUTTON.requireDefaultSlot(), MOCK_MAX_PAGE_INDEX, SGToolbarButtonType.NEXT_BUTTON, menu));
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/test/java/com/samjakob/spigui/menu/SGOpenMenuTest.java | core/src/test/java/com/samjakob/spigui/menu/SGOpenMenuTest.java | package com.samjakob.spigui.menu;
import org.bukkit.entity.Player;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class SGOpenMenuTest {
@Mock
private SGMenu menu;
@Mock
private Player player;
private SGOpenMenu openMenu;
@BeforeEach
void setup() {
openMenu = new SGOpenMenu(menu, player);
}
@Test
void testRequiresMenuAndPlayer() {
//noinspection DataFlowIssue - using null for test.
assertThrowsExactly(NullPointerException.class, () -> new SGOpenMenu(null, null));
//noinspection DataFlowIssue - using null for test.
assertThrowsExactly(NullPointerException.class, () -> new SGOpenMenu(menu, null));
//noinspection DataFlowIssue - using null for test.
assertThrowsExactly(NullPointerException.class, () -> new SGOpenMenu(null, player));
}
@Test
void testConstruct() {
assertEquals(menu, openMenu.getMenu());
assertEquals(player, openMenu.getPlayer());
}
@Test
void testEquality() {
assertEquals(new SGOpenMenu(menu, player), openMenu);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/package-info.java | core/src/main/java/package-info.java | /**
* A comprehensive GUI API for Spigot with pages support.
*
* <p><a href="https://github.com/SamJakob/SpiGUI">https://github.com/SamJakob/SpiGUI</a>
*
* @since 1.0.0
* @version 1.3.0
*/
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/SpiGUI.java | core/src/main/java/com/samjakob/spigui/SpiGUI.java | package com.samjakob.spigui;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;
import com.samjakob.spigui.menu.SGMenu;
import com.samjakob.spigui.menu.SGMenuListenerBase;
import com.samjakob.spigui.menu.SGOpenMenu;
import com.samjakob.spigui.toolbar.SGDefaultToolbarBuilderFactory;
import com.samjakob.spigui.toolbar.SGToolbarBuilder;
/**
* The core class for the SpiGUI library.
*
* <p>One instance of the SpiGUI class is registered for each plugin using it.
*
* <p>The expected usage of SpiGUI is that you register a SpiGUI instance for your plugin with <code>new SpiGUI(this);
* </code> in your class that extends <code>JavaPlugin</code>. You can then use the instance you've created throughout
* your project to create GUIs that use SpiGUI.
*/
public final class SpiGUI {
/**
* The qualified name of the InitializeSpiGUI class.
*
* <p>This class is included in a {@link SpiGUI} distribution and is initialized once for each "installation" of
* SpiGUI to set up version-specific structures and factories.
*/
private static final String INITIALIZER_CLASS = "com.samjakob.spigui.InitializeSpiGUI";
/**
* The qualified name of the class for the SGMenuListener.
*
* <p>This class is initialized for each instance of {@link SpiGUI}.
*/
private static final String LISTENER_CLASS = "com.samjakob.spigui.menu.SGMenuListener";
static {
ensureFactoriesInitialized();
}
/** The plugin that owns this instance of SpiGUI. */
@Nonnull
private final JavaPlugin plugin;
/**
* Whether to cancel inventory click actions by default.
*
* <p>This is typically set to true so events needn't be manually cancelled every time an item is clicked in the
* inventory as that is the behavior most typically used with an inventory GUI.
*
* <p>With this set to true, you can of course use <code>event.setCancelled(false);</code> (or <code>
* event.setResult(Event.Result.DEFAULT);</code>) in your button listeners to allow the default behavior of the
* inventory to take place.
*/
private boolean blockDefaultInteractions = true;
/**
* Whether automatic pagination should be enabled.
*
* <p>This is set to true by default, and it means if you set an inventory slot greater than the highest slot on the
* inventory, a row will automatically be added containing pagination items that allow a user to scroll between
* different 'pages' to access all the assigned slots in the inventory.
*
* <p>This concept is based on an improved version of the approach taken with my SpigotPaginatedGUI library.
*/
private boolean enableAutomaticPagination = true;
/**
* The defaultToolbarBuilder is the plugin-wide {@link SGToolbarBuilder} called when building pagination buttons for
* inventory GUIs.
*
* <p>This can be overridden per-inventory, as well as per-plugin using the appropriate methods on either the
* inventory class ({@link SGMenu}) or your plugin's instance of {@link SpiGUI}.
*/
private SGToolbarBuilder defaultToolbarBuilder =
SGDefaultToolbarBuilderFactory.get().newToolbarBuilder();
/**
* Creates an instance of the SpiGUI library associated with a given plugin.
*
* <p>This is intended to be stored as a static field in your plugin with a public static getter (or a public static
* field - dealer's choice) and you create inventories through this class by calling {@link #create(String, int)} on
* the static {@link SpiGUI} field.
*
* <h4>Design Notes</h4>
*
* <p>The association with a plugin is an important design decision that was overlooked in this library's
* predecessor, SpigotPaginatedGUI.
*
* <p>This library is not designed to act as a standalone plugin because that is inconvenient for both developers
* and server administrators for such a relatively insignificant task - the library is more just a small convenience
* measure. However, this library still needs to register a listener under a given plugin, which is where the issue
* arises; which plugin should the library use to register events with. Previously, it was whichever plugin made the
* call to <code>PaginatedGUI.prepare</code> first, however this obviously causes problems if that particular plugin
* is unloaded - as any other plugins using the library no longer have the listener that was registered.
*
* <p>This approach was therefore considered a viable compromise - each plugin registers its own listener, however
* the downside of this is that each inventory and the listener must now also be registered with the plugin too.
*
* <p>Thus, the design whereby this class is registered as a static field on a {@link JavaPlugin} instance and
* serves as a proxy for creating ({@link SGMenu}) inventories and an instance of the {@code SGMenuListener}
* registered with that plugin seemed like a good way to try and minimize the inconvenience of the approach.
*
* @param plugin The plugin using SpiGUI.
*/
public SpiGUI(@Nonnull JavaPlugin plugin) {
this.plugin = Objects.requireNonNull(plugin, "SpiGUI needs to be registered under a plugin.");
try {
final Class<? extends SGMenuListenerBase> listenerClass =
Class.forName(LISTENER_CLASS).asSubclass(SGMenuListenerBase.class);
final SGMenuListenerBase listener =
listenerClass.getDeclaredConstructor(SpiGUI.class).newInstance(this);
plugin.getServer().getPluginManager().registerEvents(listener, plugin);
} catch (ClassNotFoundException
| ClassCastException
| NoSuchMethodException
| InvocationTargetException
| InstantiationException
| IllegalAccessException ex) {
throw new RuntimeException(String.format(
"Failed to locate and register a valid %s for this Spigot version (%s).",
LISTENER_CLASS, Bukkit.getVersion()));
}
}
/**
* An alias for {@link #create(String, int, String)} with the tag set to null. Use this method if you don't need the
* tag, or you don't know what it's for.
*
* <p>The rows parameter is used in place of the size parameter of the Bukkit/Spigot inventory API. So, if you
* wanted an inventory of size 27, you would supply 3 as the value of the <code>rows</code> parameter.
*
* <p>The <code>name</code> parameter supports the following 'placeholders':
*
* <ul>
* <li><code>{currentPage}</code>: the current page the inventory is on.
* <li><code>{maxPage}</code>: the final page of the inventory.
* </ul>
*
* @param name The display name of the inventory.
* @param rows The number of rows the inventory should have per page.
* @return The created inventory.
*/
public SGMenu create(String name, int rows) {
return create(name, rows, null);
}
/**
* Creates an inventory with a given name, tag and number of rows. The display name is color code translated.
*
* <p>The <code>name</code> parameter supports the following 'placeholders':
*
* <ul>
* <li><code>{currentPage}</code>: the current page the inventory is on.
* <li><code>{maxPage}</code>: the final page of the inventory.
* </ul>
*
* <p>The rows parameter is used in place of the size parameter of the Bukkit/Spigot inventory API. So, if you
* wanted an inventory of size 27, you would supply 3 as the value of the <code>rows</code> parameter.
*
* <p>The tag is used when getting all open inventories ({@link #findOpenWithTag(String)}) with your chosen tag. An
* example of where this might be useful is with a permission GUI - when the permissions are updated by one user in
* the GUI, it would be desirable to refresh the state of the permissions GUI for all users observing the GUI.
*
* <p>You might give the permissions GUI a tag of 'myPermissionsGUI', then refreshing all the open instances of the
* GUI would be as simple as getting all open inventories with the aforementioned tag using
* {@link #findOpenWithTag(String)} and calling refresh on each GUI in the list.
*
* @param name The display name of the inventory.
* @param rows The number of rows the inventory should have per page.
* @param tag The inventory's tag.
* @return The created inventory.
*/
public SGMenu create(String name, int rows, String tag) {
return new SGMenu(this, name, rows, tag);
}
/**
* Returns the plugin that this instance of SpiGUI was registered with.
*
* @return the plugin for this SpiGUI instance.
*/
@Nonnull
public JavaPlugin getOwner() {
return this.plugin;
}
/**
* Whether default inventory interactions should be cancelled.
*
* @param blockDefaultInteractions Whether default inventory interactions should be cancelled.
* @see SpiGUI#blockDefaultInteractions
*/
public void setBlockDefaultInteractions(boolean blockDefaultInteractions) {
this.blockDefaultInteractions = blockDefaultInteractions;
}
/**
* Returns the value of {@link SpiGUI#blockDefaultInteractions} for this plugin.
*
* @return Whether default inventory interactions should be cancelled.
*/
public boolean areDefaultInteractionsBlocked() {
return blockDefaultInteractions;
}
/**
* Whether automatic pagination should be enabled.
*
* @param enableAutomaticPagination Whether automatic pagination should be enabled.
* @see SpiGUI#enableAutomaticPagination
*/
public void setEnableAutomaticPagination(boolean enableAutomaticPagination) {
this.enableAutomaticPagination = enableAutomaticPagination;
}
/**
* Returns the value of {@link SpiGUI#enableAutomaticPagination} for this plugin.
*
* @return Whether automatic pagination is enabled.
*/
public boolean isAutomaticPaginationEnabled() {
return enableAutomaticPagination;
}
/**
* The default toolbar builder used for GUIs.
*
* @param defaultToolbarBuilder The default toolbar builder used for GUIs.
* @see SpiGUI#defaultToolbarBuilder
*/
public void setDefaultToolbarBuilder(SGToolbarBuilder defaultToolbarBuilder) {
this.defaultToolbarBuilder = defaultToolbarBuilder;
}
/**
* The default toolbar builder used for GUIs.
*
* @return The default toolbar builder used for GUIs.
* @see SpiGUI#defaultToolbarBuilder
*/
public SGToolbarBuilder getDefaultToolbarBuilder() {
return defaultToolbarBuilder;
}
/**
* Finds a list of all open inventories with a given tag along with the player who has that inventory open.
*
* <p>This returns a list of {@link SGOpenMenu} which simply stores the opened inventory along with the player
* viewing the open inventory.
*
* <p>Supplying null as the tag value will get all untagged inventories.
*
* @param tag The tag to search for.
* @return A list of {@link SGOpenMenu} whose inventories have the specified tag.
*/
public List<SGOpenMenu> findOpenWithTag(String tag) {
List<SGOpenMenu> foundInventories = new ArrayList<>();
// Loop through every online player...
for (Player player : plugin.getServer().getOnlinePlayers()) {
// ...if that player has an open inventory with a top inventory...
if (player.getOpenInventory().getTopInventory() != null) {
// ...get that top inventory.
Inventory topInventory = player.getOpenInventory().getTopInventory();
// If the top inventory is an SGMenu,
if (topInventory.getHolder() != null && topInventory.getHolder() instanceof SGMenu) {
// and the SGMenu has the tag matching the one we're checking for,
SGMenu inventory = (SGMenu) topInventory.getHolder();
if (Objects.equals(inventory.getTag(), tag))
// add the SGMenu to our list of found inventories.
foundInventories.add(new SGOpenMenu(inventory, player));
}
}
}
return foundInventories;
}
/**
* Loads the {@code InitializeSpiGUI} class from the version-specific wrapper package that includes the core.
*
* <p>This allows version-specific implementations to be loaded into factories.
*/
public static void ensureFactoriesInitialized() {
try {
// This is sufficient for loading the class and having the static initialization blocks run.
Class.forName(INITIALIZER_CLASS);
} catch (ClassNotFoundException ignored) {
throw new RuntimeException(String.format(
"Failed to locate and register a valid %s for this Spigot version (%s).",
INITIALIZER_CLASS, Bukkit.getVersion()));
}
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/buttons/package-info.java | core/src/main/java/com/samjakob/spigui/buttons/package-info.java | /**
* Clickable elements for SpiGUI menus ({@link com.samjakob.spigui.menu.SGMenu}).
*
* <p>Presently, only a button is implemented: {@link com.samjakob.spigui.buttons.SGButton}.
*
* @since 1.0.0
* @version 1.3.0
*/
package com.samjakob.spigui.buttons;
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/buttons/SGButton.java | core/src/main/java/com/samjakob/spigui/buttons/SGButton.java | package com.samjakob.spigui.buttons;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
* An SGButton represents a clickable item in an SGMenu (GUI). It consists of an icon ({@link ItemStack}) and a listener
* ({@link SGButton}).
*
* <p>When the icon is clicked in the SGMenu, the listener is called, thus allowing for rudimentary menus to be built by
* displaying icons and overriding their behavior.
*
* <p>This somewhat resembles the point-and-click nature of Graphical User Interfaces (GUIs) popularized by Operating
* Systems developed in the late 80s and 90s which is where the name of the concept in Spigot plugins was derived.
*/
public class SGButton {
/** The on-click handler for this button. */
@Nullable
private SGButtonListener listener;
/** The Bukkit {@link ItemStack} that will be used as the button's icon. */
@Nonnull
private ItemStack icon;
/**
* Creates an SGButton with the specified {@link ItemStack} as it's 'icon' in the inventory.
*
* @param icon The desired 'icon' for the SGButton.
*/
public SGButton(@Nonnull ItemStack icon) {
this.icon = validateIcon(icon);
}
/**
* Sets the {@link SGButtonListener} to be called when the button is clicked.
*
* @param listener The listener to be called when the button is clicked.
*/
public void setListener(@Nullable SGButtonListener listener) {
this.listener = listener;
}
/**
* A chainable alias of {@link #setListener(SGButtonListener)}.
*
* @param listener The listener to be called when the button is clicked.
* @return The {@link SGButton} the listener was applied to.
*/
public SGButton withListener(@Nullable SGButtonListener listener) {
this.listener = listener;
return this;
}
/**
* Returns the {@link SGButtonListener} that is to be executed when the button is clicked.
*
* <p>This is typically intended for internal use by the main {@link com.samjakob.spigui.SpiGUI} API.
*
* @return The listener to be called when the button is clicked.
*/
@Nullable
public SGButtonListener getListener() {
return listener;
}
/**
* Returns the {@link ItemStack} that will be used as the SGButton's icon in the SGMenu (GUI).
*
* @return The icon ({@link ItemStack}) that will be used to represent the button.
*/
@Nonnull
public ItemStack getIcon() {
return icon;
}
/**
* Changes the SGButton's icon.
*
* @param icon The icon ({@link ItemStack}) that will be used to represent the button.
*/
public void setIcon(@Nonnull ItemStack icon) {
this.icon = validateIcon(icon);
}
/**
* Ensure that the {@link ItemStack} will be a suitable icon.
*
* @param icon to check.
* @return the icon, if it is suitable.
* @throws IllegalArgumentException if the icon is not suitable.
* @throws NullPointerException if the icon is null.
*/
@Nonnull
private ItemStack validateIcon(@Nonnull ItemStack icon) {
if (icon.getType() == Material.AIR) {
throw new IllegalArgumentException("Cannot use AIR as icon.");
}
return Objects.requireNonNull(icon, "Don't use a null icon - remove the button instead.");
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/buttons/SGButtonListener.java | core/src/main/java/com/samjakob/spigui/buttons/SGButtonListener.java | package com.samjakob.spigui.buttons;
import javax.annotation.Nonnull;
import org.bukkit.event.inventory.InventoryClickEvent;
/** Holds the event handler for an SGButton. */
public interface SGButtonListener {
/**
* The event handler that should be executed when an SGButton is clicked. Implement this with a lambda when you
* create an SGButton.
*
* @param event The Bukkit/Spigot API {@link InventoryClickEvent}.
*/
void onClick(@Nonnull InventoryClickEvent event);
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/toolbar/SGToolbarBuilder.java | core/src/main/java/com/samjakob/spigui/toolbar/SGToolbarBuilder.java | package com.samjakob.spigui.toolbar;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.menu.SGMenu;
/**
* An interface for a toolbar button builder.
*
* <p>The toolbar button builder is responsible for rendering the toolbar buttons for an {@link SGMenu}. This can be
* customized to render different pagination items, etc., for a GUI.
*/
public interface SGToolbarBuilder {
/**
* Specifies the toolbar button builder for an {@link SGMenu}. This can be customized to render different toolbar
* buttons for a GUI.
*
* <p>This method is called once per toolbar slot every time a page is rendered. To leave a slot empty, return null.
*
* @param slot The slot being rendered.
* @param page The current page of the inventory being rendered.
* @param defaultType The default button type of the current slot.
* @param menu The inventory the toolbar is being rendered in.
* @return The button to be rendered for that slot, or null if no button should be rendered.
*/
@Nullable
SGButton buildToolbarButton(int slot, int page, @Nonnull SGToolbarButtonType defaultType, @Nonnull SGMenu menu);
/** Builds a flat (name) string for the given menu. */
@FunctionalInterface
interface NameBuilder {
/**
* Builder for the name of a toolbar item.
*
* @param menu that the item is being built for.
* @return the toolbar item name, specified to the menu and its state.
*/
@Nonnull
String buildName(SGMenu menu);
}
/** Builds a string list (lore) for the given menu. */
@FunctionalInterface
interface LoreBuilder {
/**
* Builder for the lore of a toolbar item.
*
* @param menu that the item is being built for.
* @return the toolbar item lore (description), specified to the menu and its state.
*/
@Nonnull
List<String> buildLore(SGMenu menu);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/toolbar/package-info.java | core/src/main/java/com/samjakob/spigui/toolbar/package-info.java | /**
* The Toolbar API.
*
* <p>Used to override the pagination buttons, or to add fixed toolbar items.
*
* <p>This contains the {@link com.samjakob.spigui.toolbar.SGToolbarBuilder} interface, responsible for delegating the
* building of each toolbar button.
*
* <p>For usage, see:
*
* <ul>
* <li>{@link com.samjakob.spigui.menu.SGMenu#setToolbarBuilder(com.samjakob.spigui.toolbar.SGToolbarBuilder)}
* <li>{@link com.samjakob.spigui.SpiGUI#setDefaultToolbarBuilder(com.samjakob.spigui.toolbar.SGToolbarBuilder)}
* </ul>
*/
package com.samjakob.spigui.toolbar;
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderFactory.java | core/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderFactory.java | package com.samjakob.spigui.toolbar;
import java.util.Objects;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.samjakob.spigui.SpiGUI;
public final class SGDefaultToolbarBuilderFactory {
static {
// See ItemBuilderFactory.
FACTORY = new SGDefaultToolbarBuilderFactory();
SpiGUI.ensureFactoriesInitialized();
}
/** The static singleton {@link SGDefaultToolbarBuilderFactory} instance. */
@Nonnull
private static final SGDefaultToolbarBuilderFactory FACTORY;
@Nullable
private Supplier<SGToolbarBuilder> supplier;
/** Internal default constructor for the {@link SGDefaultToolbarBuilderFactory}. */
private SGDefaultToolbarBuilderFactory() {}
/**
* Get the globally registered instance of the {@link SGDefaultToolbarBuilderFactory}.
*
* @return the {@link SGDefaultToolbarBuilderFactory}.
*/
public static SGDefaultToolbarBuilderFactory get() {
return Objects.requireNonNull(FACTORY);
}
/**
* Checks whether the supplier has been registered elsewhere with {@link #setSupplier(Supplier)}.
*
* @return true if the supplier has already been registered (implying new ones will be ignored).
*/
public boolean hasSupplier() {
return this.supplier != null;
}
/**
* Set the supplier for the {@link SGDefaultToolbarBuilderFactory}.
*
* @param supplier to use when creating an {@link SGToolbarBuilder}.
*/
public void setSupplier(@Nonnull Supplier<SGToolbarBuilder> supplier) {
if (hasSupplier()) {
return;
}
this.supplier = Objects.requireNonNull(supplier);
}
/**
* Instantiate a new {@link SGToolbarBuilder} using the supplier passed to {@link #setSupplier(Supplier)}.
*
* @return supplier to use for creating {@link SGToolbarBuilder}s.
*/
@Nonnull
public SGToolbarBuilder newToolbarBuilder() {
final Supplier<SGToolbarBuilder> supplier = Objects.requireNonNull(
this.supplier, "The SGDefaultToolbarBuilderFactory has not been configured with #setSupplier yet.");
return Objects.requireNonNull(
supplier.get(),
"The supplier returned a null SGToolbarBuilder which is not permitted. This means whatever has called #setSupplier first has provided an invalid supplier.");
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderBase.java | core/src/main/java/com/samjakob/spigui/toolbar/SGDefaultToolbarBuilderBase.java | package com.samjakob.spigui.toolbar;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.bukkit.event.Event;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.menu.SGMenu;
/**
* The default base implementation of {@link SGToolbarBuilder}.
*
* <p>This class is the base of the class used by SpiGUI as a default implementation. You can build your own custom
* toolbar by implementing {@link SGToolbarBuilder} and passing your custom implementation to
* {@link SpiGUI#setDefaultToolbarBuilder(SGToolbarBuilder)} (or to use it for a specific menu, pass it to
* {@link SGMenu#setToolbarBuilder(SGToolbarBuilder)}).
*/
@Immutable
public abstract class SGDefaultToolbarBuilderBase implements SGToolbarBuilder {
/** A label equivalent to "<- Previous Page". */
private final NameBuilder previousPageLabelBuilder;
/** An additional description displayed under {@code previousPage}. */
private final LoreBuilder previousPageDescriptionBuilder;
/** A label equivalent to "Page X of Y" */
private final NameBuilder currentPageLabelBuilder;
/** An additional description displayed under {@code currentPage}. */
private final LoreBuilder currentPageDescriptionBuilder;
/** A label equivalent to "Next Page ->". */
private final NameBuilder nextPageLabelBuilder;
/** An additional description displayed under {@code nextPage}. */
private final LoreBuilder nextPageDescriptionBuilder;
/**
* Construct the base default implementation of {@link SGToolbarBuilder}.
*
* @param previousPageLabelBuilder A label equivalent to "<- Previous Page".
* @param previousPageDescriptionBuilder An additional description displayed under {@code previousPage}.
* @param currentPageLabelBuilder A label equivalent to "Page X of Y"
* @param currentPageDescriptionBuilder An additional description displayed under {@code currentPage}.
* @param nextPageLabelBuilder A label equivalent to "Next Page ->".
* @param nextPageDescriptionBuilder An additional description displayed under {@code nextPage}.
*/
public SGDefaultToolbarBuilderBase(
final NameBuilder previousPageLabelBuilder,
final LoreBuilder previousPageDescriptionBuilder,
final NameBuilder currentPageLabelBuilder,
final LoreBuilder currentPageDescriptionBuilder,
final NameBuilder nextPageLabelBuilder,
final LoreBuilder nextPageDescriptionBuilder) {
this.previousPageLabelBuilder = previousPageLabelBuilder;
this.previousPageDescriptionBuilder = previousPageDescriptionBuilder;
this.currentPageLabelBuilder = currentPageLabelBuilder;
this.currentPageDescriptionBuilder = currentPageDescriptionBuilder;
this.nextPageLabelBuilder = nextPageLabelBuilder;
this.nextPageDescriptionBuilder = nextPageDescriptionBuilder;
}
/** Construct the base default implementation of {@link SGToolbarBuilder} with default options. */
public SGDefaultToolbarBuilderBase() {
this(
// Previous
menu -> "&a&l← Previous Page",
menu -> Arrays.asList("&aClick to move back to", "&apage " + menu.getCurrentPage() + "."),
// Current
menu -> String.format("&7&lPage %d of %d", menu.getCurrentPage() + 1, menu.getMaxPageNumber()),
menu -> Arrays.asList("&7You are currently viewing", "&7page " + (menu.getCurrentPage() + 1) + "."),
// Next
menu -> "&a&lNext Page →",
menu -> Arrays.asList("&aClick to move forward to", "&apage " + (menu.getCurrentPage() + 2) + "."));
}
/**
* A label equivalent to "<- Previous Page".
*
* @return A builder for a label equivalent to "<- Previous Page".
*/
public NameBuilder getPreviousPageLabelBuilder() {
return this.previousPageLabelBuilder;
}
/**
* An additional description displayed under {@code previousPage}.
*
* @return A builder for an additional description displayed under {@code previousPage}.
*/
public LoreBuilder getPreviousPageDescriptionBuilder() {
return this.previousPageDescriptionBuilder;
}
/**
* A label equivalent to "Page X of Y"
*
* @return A builder for a label equivalent to "Page X of Y"
*/
public NameBuilder getCurrentPageLabelBuilder() {
return this.currentPageLabelBuilder;
}
/**
* An additional description displayed under {@code currentPage}.
*
* @return A builder for an additional description displayed under {@code currentPage}.
*/
public LoreBuilder getCurrentPageDescriptionBuilder() {
return this.currentPageDescriptionBuilder;
}
/**
* A label equivalent to "Next Page ->".
*
* @return A builder for a label equivalent to "Next Page ->".
*/
public NameBuilder getNextPageLabelBuilder() {
return this.nextPageLabelBuilder;
}
/**
* An additional description displayed under {@code nextPage}.
*
* @return A builder for an additional description displayed under {@code nextPage}.
*/
public LoreBuilder getNextPageDescriptionBuilder() {
return this.nextPageDescriptionBuilder;
}
@Nullable
@Override
public SGButton buildToolbarButton(
int slot, int page, @Nonnull SGToolbarButtonType defaultType, @Nonnull SGMenu menu) {
if (page != menu.getCurrentPage()) {
throw new IllegalStateException(
"Toolbar fragment page number is not consistent with menu page. (This may be caused by an unexpected concurrent modification - please open an issue on GitHub).");
}
switch (defaultType) {
case PREV_BUTTON:
if (menu.getCurrentPage() > 0)
return new SGButton(Objects.requireNonNull(initializePreviousPageButton())
.name(Objects.requireNonNull(this.previousPageLabelBuilder.buildName(menu)))
.lore(Objects.requireNonNull(this.previousPageDescriptionBuilder.buildLore(menu)))
.build())
.withListener(event -> {
event.setResult(Event.Result.DENY);
menu.previousPage(event.getWhoClicked());
});
else return null;
case CURRENT_BUTTON:
return new SGButton(Objects.requireNonNull(initializeCurrentPageIndicator())
.name(Objects.requireNonNull(this.currentPageLabelBuilder.buildName(menu)))
.lore(Objects.requireNonNull(this.currentPageDescriptionBuilder.buildLore(menu)))
.build())
.withListener(event -> event.setResult(Event.Result.DENY));
case NEXT_BUTTON:
if (menu.getCurrentPage() < menu.getMaxPageIndex())
return new SGButton(Objects.requireNonNull(initializeNextPageButton())
.name(Objects.requireNonNull(this.nextPageLabelBuilder.buildName(menu)))
.lore(Objects.requireNonNull(this.nextPageDescriptionBuilder.buildLore(menu)))
.build())
.withListener(event -> {
event.setResult(Event.Result.DENY);
menu.nextPage(event.getWhoClicked());
});
else return null;
case UNASSIGNED:
default:
return null;
}
}
/**
* Build the initial previous page button.
*
* <p>The primary purpose of this method is to initialize an ItemBuilder with an icon. This allows version-specific
* materials and {@link ItemBuilder} implementation to be used.
*
* <p>The item will then be further customized with name, listener, etc., and subsequently built within the
* {@link SGDefaultToolbarBuilderBase}.
*
* @return the previous page button.
*/
@Nonnull
protected abstract ItemBuilder initializePreviousPageButton();
/**
* Build the initial current page button.
*
* <p>The primary purpose of this method is to initialize an ItemBuilder with an icon. This allows version-specific
* materials and {@link ItemBuilder} implementation to be used.
*
* <p>The item will then be further customized with name, listener, etc., and subsequently built within the
* {@link SGDefaultToolbarBuilderBase}.
*
* @return the current page button.
*/
@Nonnull
protected abstract ItemBuilder initializeCurrentPageIndicator();
/**
* Build the initial next page button.
*
* <p>The primary purpose of this method is to initialize an ItemBuilder with an icon. This allows version-specific
* materials and {@link ItemBuilder} implementation to be used.
*
* <p>The item will then be further customized with name, listener, etc., and subsequently built within the
* {@link SGDefaultToolbarBuilderBase}.
*
* @return the next page button.
*/
@Nonnull
protected abstract ItemBuilder initializeNextPageButton();
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/toolbar/SGToolbarButtonType.java | core/src/main/java/com/samjakob/spigui/toolbar/SGToolbarButtonType.java | package com.samjakob.spigui.toolbar;
import java.util.*;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Represents pre-defined types for toolbar buttons. These can be used to easily re-define the buttons used in a
* toolbar, without creating an entirely custom toolbar implementation.
*/
public enum SGToolbarButtonType {
/** The "previous page" pagination button. */
PREV_BUTTON(3),
/** The "current page" indicator button (doesn't necessarily have an action associated). */
CURRENT_BUTTON(4),
/** The "next page" pagination button. */
NEXT_BUTTON(5),
/** No pre-defined action or button. */
UNASSIGNED(null);
/** The default slot for the button, or null. */
@Nullable
private final Integer defaultSlot;
/**
* A pre-defined toolbar type mapping. These can be used to easily re-define the buttons used in a toolbar, without
* creating an entirely custom toolbar implementation.
*
* @param defaultSlot to position the button with the specified type in (or null).
*/
SGToolbarButtonType(@Nullable Integer defaultSlot) {
this.defaultSlot = defaultSlot;
}
/**
* Returns the default slot mapping for the given toolbar button type.
*
* @return the default slot for the toolbar button type.
*/
@Nullable
public Integer getDefaultSlot() {
return defaultSlot;
}
/**
* Convenience method that unboxes {@link #getDefaultSlot()} after null-checking it. Use this method when you can
* guarantee that the type should have an assigned slot (i.e., that it will never be {@link #UNASSIGNED}).
*
* <p>If in doubt, use {@link #getDefaultSlot()} and handle the case where it is null.
*
* @return the default slot.
* @throws NullPointerException if the button type does not have a default slot assigned (i.e.,
* {@link #UNASSIGNED}).
*/
public int requireDefaultSlot() {
return Objects.requireNonNull(
defaultSlot, "#requireDefaultSlot called but the button did not have a default slot.");
}
/**
* Returns the default button type for a slot, given the mapping between a given toolbar slot number (from 0 to 8),
* and {@link SGToolbarButtonType}.
*
* <p>This intended for use in setting (or falling back to) defaults for toolbar buttons, or for minor tweaks to
* existing buttons in a toolbar, as opposed to entirely new custom toolbars.
*
* @param slot to get the default button type mapping for.
* @return The default button type mapping for the specified slot. Alternatively,
* {@link SGToolbarButtonType#UNASSIGNED} if there isn't one.
*/
@Nonnull
public static SGToolbarButtonType getDefaultForSlot(int slot) {
return Arrays.stream(values())
.filter(type -> type.defaultSlot != null)
.filter(type -> type.defaultSlot == slot)
.findFirst()
.orElse(SGToolbarButtonType.UNASSIGNED);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/ItemBuilderFactory.java | core/src/main/java/com/samjakob/spigui/item/ItemBuilderFactory.java | package com.samjakob.spigui.item;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.samjakob.spigui.SpiGUI;
/**
* A factory for {@link ItemBuilderBase}.
*
* <p>This factory is used to auto-register {@link ItemBuilderConstructors} for a compatible {@link ItemBuilderBase}
* depending on which server API version SpiGUI is targeting.
*/
public final class ItemBuilderFactory implements ItemBuilderConstructors {
static {
// Initialize the ItemBuilderFactory before we call ensureFactoriesInitialized.
// This is the entry point for the ItemBuilder, so there's a chance this will be invoked before the factory
// would have been initialized with the static initializer (causing a chicken-and-egg situation). This
// circumvents that by explicitly ensuring the factory is registered first.
FACTORY = new ItemBuilderFactory();
SpiGUI.ensureFactoriesInitialized();
}
/** The static singleton {@link ItemBuilderFactory} instance. */
@Nonnull
private static final ItemBuilderFactory FACTORY;
/** The constructors to use to make {@link ItemBuilderBase}s. */
@Nullable
private ItemBuilderConstructors constructors;
/** Internal default constructor for the {@link ItemBuilderFactory}. */
private ItemBuilderFactory() {}
/**
* Get the globally registered instance of the {@link ItemBuilderFactory}.
*
* @return the {@link ItemBuilderFactory}.
*/
@Nonnull
public static ItemBuilderFactory get() {
return Objects.requireNonNull(FACTORY);
}
/**
* Checks whether the constructors have already been registered elsewhere with
* {@link #setConstructors(ItemBuilderConstructors)}.
*
* @return true if constructors have already been registered (implying new ones will be ignored).
*/
public boolean hasConstructors() {
return this.constructors != null;
}
/**
* Set the constructors for the {@link ItemBuilderFactory}.
*
* <p>This can be used to dynamically set the {@link ItemBuilderBase} implementation at runtime depending on (e.g.,
* API versions).
*
* @param constructors to use when creating an {@link ItemBuilderBase}.
*/
public void setConstructors(@Nonnull ItemBuilderConstructors constructors) {
// Do nothing if the constructors have already been done.
if (hasConstructors()) {
return;
}
this.constructors = Objects.requireNonNull(constructors);
}
/**
* Get the constructors for the {@link ItemBuilderFactory}.
*
* @return constructors to use when creating an {@link ItemBuilderBase}.
*/
@Nonnull
private ItemBuilderConstructors getConstructors() {
return Objects.requireNonNull(
this.constructors, "The ItemBuilderFactory has not been configured with #setConstructors yet.");
}
@Override
public ItemBuilderBase create(@Nonnull Material material) {
return getConstructors().create(material);
}
@Override
public ItemBuilderBase from(@Nonnull ItemStack stack) {
return getConstructors().from(stack);
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/package-info.java | core/src/main/java/com/samjakob/spigui/item/package-info.java | /**
* The {@link com.samjakob.spigui.item.ItemBuilder} API (and friends).
*
* <p>This holds the ItemBuilder API class and other classes (or enums) used to implement it.
*/
package com.samjakob.spigui.item;
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/ItemBuilder.java | core/src/main/java/com/samjakob/spigui/item/ItemBuilder.java | package com.samjakob.spigui.item;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
/**
* A helper for creating and modifying {@link ItemStack}s.
*
* <p>In future, this class will be removed and replaced with {@link ItemBuilderBase}. Presently, this class exists for
* backwards-compatibility, so that previous consumers of the {@link ItemBuilder} API (who would have initialized an
* ItemBuilder with a constructor) can have a phased move to using the static factory methods instead.
*
* <p>This class provides a convenient chainable ('builder pattern') API for manipulating the metadata of an
* {@link ItemStack}, replacing several calls into a clean one-liner in many cases.
*
* <p><b>Note:</b> as a convention (to make debugging and identifying potential issues simpler) all methods on this
* interface shall throw a {@link NullPointerException} if the item meta is null. This would only happen if Bukkit's API
* failed to produce an {@link ItemMeta} object for an item type - which shouldn't ever happen.
*
* <pre>{@code
* final var sponge = ItemBuilder.create(Material.SPONGE).name("&cAlmighty sponge").amount(21).build();
* }</pre>
*
* @author SamJakob
* @version 3.0.0
* @see ItemBuilderBase
* @see ItemStack
*/
public final class ItemBuilder implements ItemBuilderBase {
/** The underlying {@link ItemBuilderBase} that this wrapper will delegate to. */
private final ItemBuilderBase builder;
/**
* Create an {@link ItemBuilder} (wrapper for {@link ItemBuilderBase}).
*
* @param builder (underlying {@link ItemBuilderBase}) to wrap.
*/
private ItemBuilder(ItemBuilderBase builder) {
this.builder = builder;
}
/**
* Create a new {@link ItemBuilder} for the given {@link Material} type.
*
* <p>This method is deprecated and will be replaced with {@link ItemBuilder#create(Material)}. The ultimate goal is
* to replace the {@link ItemBuilder} class with the {@link ItemBuilderBase} interface.
*
* @throws IllegalArgumentException if the material is a non-item type.
* @param material type of stack to create a builder for.
* @deprecated use {@link ItemBuilder#create(Material)} as this method is to be replaced with static factory method
* - see above.
*/
@Deprecated()
public ItemBuilder(@Nonnull Material material) {
this.builder = ItemBuilderBase.create(material);
}
/**
* Create a new {@link ItemBuilder} for the given {@link Material} type.
*
* @throws IllegalArgumentException if the material is a non-item type.
* @param material type of stack to create a builder for.
* @return the constructed {@link ItemBuilder}.
*/
@Nonnull
public static ItemBuilder create(@Nonnull Material material) {
return new ItemBuilder(ItemBuilderBase.create(material));
}
/**
* Create a new {@link ItemBuilder} that uses the provided {@link ItemStack} and associated metadata as the initial
* configuration.
*
* <p>This method is deprecated and will be replaced with {@link ItemBuilder#from(ItemStack)}. The ultimate goal is
* to replace the {@link ItemBuilder} class with the {@link ItemBuilderBase} interface.
*
* @throws IllegalArgumentException if the item stack's type (material) is a non-item type.
* @param stack to derive the builder options from.
* @deprecated use {@link ItemBuilder#from(ItemStack)} as this method is to be replaced with static factory method -
* see above.
*/
@Deprecated()
public ItemBuilder(@Nonnull ItemStack stack) {
this.builder = ItemBuilderBase.from(stack);
}
/**
* Create a new {@link ItemBuilder} that uses the provided {@link ItemStack} and associated metadata as the initial
* configuration.
*
* @throws IllegalArgumentException if the item stack's type (material) is a non-item type.
* @param stack to derive the builder options from.
* @return the constructed {@link ItemBuilder}.
*/
@Nonnull
public static ItemBuilder from(@Nonnull ItemStack stack) {
return new ItemBuilder(ItemBuilderBase.from(stack));
}
@Nonnull
@Override
public ItemBuilder type(@Nonnull Material material) {
builder.type(material);
return this;
}
@Nonnull
@Override
public Material getType() {
return builder.getType();
}
@Nonnull
@Override
public ItemBuilder name(@Nullable String name) {
builder.name(name);
return this;
}
@Nullable
@Override
public String getName() {
return builder.getName();
}
@Nonnull
@Override
public ItemBuilder amount(int amount) {
builder.amount(amount);
return this;
}
@Override
public int getAmount() {
return builder.getAmount();
}
@Nonnull
@Override
public ItemBuilder lore(@Nullable String... lore) {
builder.lore(lore);
return this;
}
@Nonnull
@Override
public ItemBuilder lore(@Nullable List<String> lore) {
builder.lore(lore);
return this;
}
@Nullable
@Override
public List<String> getLore() {
return builder.getLore();
}
@Nonnull
@Override
public ItemBuilder color(@Nonnull ItemColor color) {
builder.color(color);
return this;
}
@Nullable
@Override
public ItemColor getColor() {
return builder.getColor();
}
@Nonnull
@Override
public ItemBuilder data(short data) {
builder.data(data);
return this;
}
@Nonnull
@Override
public ItemBuilder durability(int durability) {
builder.durability(durability);
return this;
}
@Override
public int getDurability() {
return builder.getDurability();
}
@Nonnull
@Override
public ItemBuilderBase maxDurability(int maxDurability) {
builder.maxDurability(maxDurability);
return this;
}
@Override
public int getMaxDurability() {
return builder.getMaxDurability();
}
@Nonnull
@Override
public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) {
builder.enchant(enchantment, level);
return this;
}
@Nonnull
@Override
public ItemBuilder unenchant(@Nonnull Enchantment enchantment) {
builder.unenchant(enchantment);
return this;
}
@Nonnull
@Override
public ItemBuilder flag(@Nonnull ItemFlag... flag) {
builder.flag(flag);
return this;
}
@Nonnull
@Override
public ItemBuilder deflag(@Nonnull ItemFlag... flag) {
builder.deflag(flag);
return this;
}
@Nonnull
@Override
@Deprecated
public ItemBuilderBase skullOwner(@Nullable String name) {
builder.skullOwner(name);
return this;
}
@Nonnull
@Override
public ItemBuilderBase skullOwner(@Nullable UUID uuid) {
builder.skullOwner(uuid);
return this;
}
@Nonnull
@Override
public ItemStack build() {
return builder.build();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/ItemBuilderBase.java | core/src/main/java/com/samjakob/spigui/item/ItemBuilderBase.java | package com.samjakob.spigui.item;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
/**
* A helper for creating and modifying {@link ItemStack}s.
*
* <p><b>NOTE:</b> in future, this class will be renamed to ItemBuilder (see {@link ItemBuilder}). For now, you should
* continue to use {@link ItemBuilder} as it is intended to be a seamless replacement.
*
* <p>This class provides a convenient chainable ('builder pattern') API for manipulating the metadata of an
* {@link ItemStack}, replacing several calls into a clean one-liner in many cases.
*
* <p><b>Note:</b> as a convention (to make debugging and identifying potential issues simpler) all methods on this
* interface shall throw a {@link NullPointerException} if the item meta is null. This would only happen if Bukkit's API
* failed to produce an {@link ItemMeta} object for an item type - which shouldn't ever happen.
*
* <pre>{@code
* final var sponge = ItemBuilder.create(Material.SPONGE).name("&cAlmighty sponge").amount(21).build();
* }</pre>
*
* @author SamJakob
* @version 3.0.0
* @see ItemStack
*/
@SuppressWarnings("UnusedReturnValue")
public interface ItemBuilderBase {
/**
* Create a new {@link ItemBuilderBase} for the given {@link Material} type.
*
* @throws IllegalArgumentException if the material is a non-item type.
* @param material type of stack to create a builder for.
* @return the constructed {@link ItemBuilderBase}.
*/
@Nonnull
static ItemBuilderBase create(@Nonnull Material material) {
return ItemBuilderFactory.get().create(material);
}
/**
* Create a new {@link ItemBuilderBase} that uses the provided {@link ItemStack} and associated metadata as the
* initial configuration.
*
* @throws IllegalArgumentException if the item stack's type (material) is a non-item type.
* @param stack to derive the builder options from.
* @return the constructed {@link ItemBuilderBase}.
*/
@Nonnull
static ItemBuilderBase from(@Nonnull ItemStack stack) {
return ItemBuilderFactory.get().from(stack);
}
/**
* Sets the type ({@link Material}) of the ItemStack.
*
* @param material The {@link Material} of the stack.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase type(@Nonnull Material material);
/**
* Returns the type ({@link Material}) of the ItemStack.
*
* @return The {@link Material} of the stack.
*/
@Nonnull
Material getType();
/**
* Sets the display name of the item.
*
* <p>Color codes using the ampersand ({@code &}) are translated, if you want to avoid this, you should wrap your
* name argument with a {@link ChatColor#stripColor(String)} call.
*
* @param name The desired display name of the item stack.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase name(@Nullable String name);
/**
* Returns either the display name of the item, if it exists, or null if it doesn't.
*
* <p>You should note that this method fetches the name directly from the stack's {@link ItemMeta}, so you should
* take extra care when comparing names with color codes - particularly if you used the {@link #name(String)} method
* as they will be in their translated sectional symbol (§) form, rather than their 'coded' form ({@code &}).
*
* <p>For example, if you used {@link #name(String)} to set the name to '&cMy Item', the output of this method
* would be '§cMy Item'
*
* @return The item's display name as returned from its {@link ItemMeta}.
*/
@Nullable
String getName();
/**
* Sets the amount of items in the {@link ItemStack}.
*
* @param amount The new amount.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase amount(int amount);
/**
* Returns the amount of items in the {@link ItemStack}.
*
* @return The amount of items in the stack.
*/
int getAmount();
/**
* Sets the lore of the item. This method is a var-args alias for the {@link #lore(List)} method.
*
* @param lore The desired lore of the item, with each line as a separate string.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase lore(@Nullable String... lore);
/**
* Sets the lore of the item. As with {@link #name(String)}, color codes will be replaced. Each string represents a
* line of the lore.
*
* <p>Lines will not be automatically wrapped or truncated, so it is recommended you take some consideration into
* how the item will be rendered with the lore.
*
* @param lore The desired lore of the item, with each line as a separate string.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase lore(@Nullable List<String> lore);
/**
* Gets the lore of the item as a list of strings. Each string represents a line of the item's lore in-game.
*
* <p>As with {@link #name(String)}, it should be noted that color-coded lore lines will be returned with the colors
* codes already translated.
*
* @return The lore of the item.
*/
@Nullable
List<String> getLore();
/**
* Set the color of items (where those items can have a color applied to them).
*
* <p>The behavior of this method is undefined when an item does not have color values associated with it.
*
* @param color The desired color of the item.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase color(@Nonnull ItemColor color);
/**
* Returns the color of the item.
*
* <p>The behavior of this method is undefined when an item does not have color values associated with it and may be
* inconsistent across versions of the game.
*
* @return The {@link ItemColor} of the item (where the item has a color associated).
*/
@Nullable
ItemColor getColor();
/**
* Set the data value of the item.
*
* <p>The behavior of this method is undefined when an item does not have a data value associated with it.
*
* <p>In newer versions of the game (Minecraft 1.13+), this method throws {@link UnsupportedOperationException} to
* encourage use of a different method (or to open a GitHub issue if functionality has been missed).
*
* @param data data value for the item.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase data(short data);
/**
* Sets the durability of the item.
*
* <p>The behavior of this method is undefined when an item does not have a data value associated with it.
*
* @param durability The desired durability of the item.
* @return The updated {@link ItemBuilderBase} object.
*/
@Nonnull
ItemBuilderBase durability(int durability);
/**
* Returns the durability or data value of the item.
*
* @return The durability of the item.
*/
int getDurability();
/**
* Sets the maximum possible durability of the item.
*
* <p>Does nothing if the maximum durability cannot be set on the item.
*
* @param maxDurability The desired maximum durability for the item.
* @return The updated {@link ItemBuilderBase} object.
*/
@Nonnull
ItemBuilderBase maxDurability(int maxDurability);
/**
* Returns the maximum possible durability value of the item.
*
* <p>Returns zero if the item does not have a max damage value.
*
* @return The maximum durability of the item.
*/
int getMaxDurability();
/**
* Adds the specified enchantment to the stack.
*
* <p>This method uses {@link ItemStack#addUnsafeEnchantment(Enchantment, int)} rather than
* {@link ItemStack#addEnchantment(Enchantment, int)} to avoid the associated checks of whether level is within the
* range for the enchantment.
*
* @param enchantment The enchantment to apply to the item.
* @param level The level of the enchantment to apply to the item.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase enchant(@Nonnull Enchantment enchantment, int level);
/**
* Removes the specified enchantment from the stack.
*
* @param enchantment The enchantment to remove from the item.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase unenchant(@Nonnull Enchantment enchantment);
/**
* Accepts a variable number of {@link ItemFlag}s to apply to the stack.
*
* @param flag A variable-length argument containing the flags to be applied.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase flag(@Nonnull ItemFlag... flag);
/**
* Accepts a variable number of {@link ItemFlag}s to remove from the stack.
*
* @param flag A variable-length argument containing the flags to be removed.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase deflag(@Nonnull ItemFlag... flag);
/**
* If the item has {@link SkullMeta} (i.e. if the item is a skull), this can be used to set the skull's owner (i.e.
* the player the skull represents.)
*
* <p>In older versions of the game, this also sets the skull's data value to 3 for 'player head', as setting the
* skull's owner doesn't make much sense for the mob skulls. (This is irrelevant in later versions as the skull
* owner can only be set on a PLAYER_HEAD item anyway).
*
* @param name The name of the player the skull item should resemble.
* @return The {@link ItemBuilderBase} instance.
* @deprecated use {@link #skullOwner(UUID)} instead.
*/
@Nonnull
@Deprecated
ItemBuilderBase skullOwner(@Nullable String name);
/**
* If the item has {@link SkullMeta} (i.e. if the item is a skull), this can be used to set the skull's owner (i.e.
* the player the skull represents.)
*
* <p>In older versions of the game, this also sets the skull's data value to 3 for 'player head', as setting the
* skull's owner doesn't make much sense for the mob skulls. (This is irrelevant in later versions as the skull
* owner can only be set on a PLAYER_HEAD item anyway).
*
* @param uuid The UUID of the player the skull item should resemble.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
ItemBuilderBase skullOwner(@Nullable UUID uuid);
/**
* This is used to, inline, perform an operation if a given condition is true.
*
* <p>This can be useful when applying stream operations to {@link ItemBuilderBase}s.
*
* <p>The {@link ItemBuilderBase} instance is supplied to both the predicate (condition) and result function.
*
* <p>For example:
*
* <pre>{@code
* // Renames the ItemStack, if and only if, the stack's type is Acacia Doors.
* ifThen(stack -> stack.getType() == Material.ACACIA_DOOR, stack -> stack.name("&aMagic Door"));
* }</pre>
*
* @param ifTrue The condition upon which, <code>then</code> should be performed.
* @param then The action to perform if the predicate, <code>ifTrue</code>, is true.
* @return The {@link ItemBuilderBase} instance.
*/
@Nonnull
default ItemBuilderBase ifThen(Predicate<ItemBuilderBase> ifTrue, Consumer<ItemBuilderBase> then) {
if (ifTrue.test(this)) then.accept(this);
return this;
}
/**
* Returns the {@link ItemStack} that has been configured on the {@link ItemBuilderBase}.
*
* @return The manipulated ItemStack.
*/
@Nonnull
ItemStack build();
/**
* An alias for {@link #build()}.
*
* @return the built item stack.
* @see #build()
*/
@Nonnull
default ItemStack get() {
return build();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/ItemBuilderConstructors.java | core/src/main/java/com/samjakob/spigui/item/ItemBuilderConstructors.java | package com.samjakob.spigui.item;
import javax.annotation.Nonnull;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
* Constructors that can be used by the {@link ItemBuilderFactory}.
*
* <p>These can be registered dynamically on the factory depending on which {@link ItemBuilderBase} implementation is
* compatible.
*/
public interface ItemBuilderConstructors {
/**
* Create a new {@link ItemBuilderBase} for the given {@link Material} type.
*
* @throws IllegalArgumentException if the material is a non-item type.
* @param material type of stack to create a builder for.
* @return the constructed {@link ItemBuilderBase}.
*/
ItemBuilderBase create(@Nonnull Material material);
/**
* Create a new {@link ItemBuilderBase} that uses the provided {@link ItemStack} and associated metadata as the
* initial configuration.
*
* @throws IllegalArgumentException if the item stack's type (material) is a non-item type.
* @param stack to derive the builder options from.
* @return the constructed {@link ItemBuilderBase}.
*/
ItemBuilderBase from(@Nonnull ItemStack stack);
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/item/ItemColor.java | core/src/main/java/com/samjakob/spigui/item/ItemColor.java | package com.samjakob.spigui.item;
/**
* Items such as glass panes can have variable color. Historically, Minecraft (and the Bukkit/Spigot APIs) represented
* these colors with data/durability values.
*
* <p>This was unclear when working with the items so SpiGUI's (and its predecessor's) item API has always had a tool to
* manage and manipulate those colors in an identifiable way.
*
* <p>This version of the item color tool is designed to have an API that will allow identifying color types across
* different game and API versions.
*
* @author SamJakob
* @version 3.0.0
*/
public enum ItemColor {
/** <img height="64" width="64" src="colors/white_wool.png" alt="White wool"> */
WHITE,
/** <img height="64" width="64" src="colors/orange_wool.png" alt="Orange wool"> */
ORANGE,
/** <img height="64" width="64" src="colors/magenta_wool.png" alt="Magenta wool"> */
MAGENTA,
/** <img height="64" width="64" src="colors/light_blue_wool.png" alt="Light blue wool"> */
LIGHT_BLUE,
/** <img height="64" width="64" src="colors/yellow_wool.png" alt="Yellow wool"> */
YELLOW,
/** <img height="64" width="64" src="colors/lime_wool.png" alt="Lime wool"> */
LIME,
/** <img height="64" width="64" src="colors/pink_wool.png" alt="Pink wool"> */
PINK,
/** <img height="64" width="64" src="colors/gray_wool.png" alt="Gray wool"> */
GRAY,
/** <img height="64" width="64" src="colors/light_gray_wool.png" alt="Light gray wool"> */
LIGHT_GRAY,
/** <img height="64" width="64" src="colors/cyan_wool.png" alt="Cyan wool"> */
CYAN,
/** <img height="64" width="64" src="colors/purple_wool.png" alt="Purple wool"> */
PURPLE,
/** <img height="64" width="64" src="colors/blue_wool.png" alt="Blue wool"> */
BLUE,
/** <img height="64" width="64" src="colors/brown_wool.png" alt="Brown wool"> */
BROWN,
/** <img height="64" width="64" src="colors/green_wool.png" alt="Green wool"> */
GREEN,
/** <img height="64" width="64" src="colors/red_wool.png" alt="Red wool"> */
RED,
/** <img height="64" width="64" src="colors/black_wool.png" alt="Black wool"> */
BLACK
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/menu/package-info.java | core/src/main/java/com/samjakob/spigui/menu/package-info.java | /**
* Menu definitions, including the listener (which handles user events).
*
* @see com.samjakob.spigui.menu.SGMenu
*/
package com.samjakob.spigui.menu;
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/menu/SGOpenMenu.java | core/src/main/java/com/samjakob/spigui/menu/SGOpenMenu.java | package com.samjakob.spigui.menu;
import java.util.Objects;
import java.util.StringJoiner;
import javax.annotation.Nonnull;
import org.bukkit.entity.Player;
/** Used to refer to a player's "viewing session" of a given menu. */
public class SGOpenMenu {
/** The {@link SGMenu} that is currently open. */
private final SGMenu menu;
/** The player viewing the menu. */
private final Player player;
/**
* Pairs an {@link SGMenu} instance with a player viewing that menu.
*
* @param menu The {@link SGMenu} that is open.
* @param player The player viewing the menu.
*/
public SGOpenMenu(@Nonnull SGMenu menu, @Nonnull Player player) {
this.menu = Objects.requireNonNull(menu);
this.player = Objects.requireNonNull(player);
}
/**
* Get the open {@link SGMenu} instance.
*
* @return The menu that is open.
*/
@Nonnull
public SGMenu getMenu() {
return this.menu;
}
/**
* Get the player viewing the {@link SGMenu}.
*
* @return The player viewing the menu.
*/
@Nonnull
public Player getPlayer() {
return this.player;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof SGOpenMenu)) return false;
SGOpenMenu that = (SGOpenMenu) o;
return Objects.equals(menu, that.menu) && Objects.equals(getPlayer(), that.getPlayer());
}
@Override
public int hashCode() {
return Objects.hash(menu, getPlayer());
}
@Override
public String toString() {
return new StringJoiner(", ", SGOpenMenu.class.getSimpleName() + "[", "]")
.add("menu=" + menu)
.add(String.format("player=%s (%s)", player.getUniqueId().toString(), player.getDisplayName()))
.toString();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/menu/SGMenuListenerBase.java | core/src/main/java/com/samjakob/spigui/menu/SGMenuListenerBase.java | package com.samjakob.spigui.menu;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.java.JavaPlugin;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.buttons.SGButtonListener;
import com.samjakob.spigui.toolbar.SGToolbarBuilder;
import com.samjakob.spigui.toolbar.SGToolbarButtonType;
/**
* The {@link SGMenuListenerBase} provides reusable core logic for version-specific SpiGUI inventory listeners.
*
* <p>You must register this class as an event listener in your plugin's {@code onEnable} method by initializing SpiGUI
* there (which will register a listener automatically).
*/
public abstract class SGMenuListenerBase implements Listener {
/** The SpiGUI instance that this listener is operating for. */
protected final SpiGUI spiGUI;
/**
* Initialize an SGBaseMenuListener for the specified {@link SpiGUI} instance.
*
* @param spiGUI that this listener is registered for.
*/
public SGMenuListenerBase(@Nonnull SpiGUI spiGUI) {
this.spiGUI = spiGUI;
}
/**
* Returns true if the specified inventory exists and is an SGMenu, as that implies the inventory event should be
* handled by this {@link SGMenuListenerBase} class.
*
* <p>Alternatively, if the inventory is null, or the inventory is not associated with the {@link SGMenu} class
* (i.e., <code>inventory.getHolder</code> is null), this returns false signalling that the event should not be
* processed.
*
* @param inventory to check.
* @return True if inventory event should be handled by {@link SGMenuListenerBase}, false if not.
*/
protected boolean isSGMenu(@Nullable Inventory inventory) {
return inventory != null && inventory.getHolder() != null && inventory.getHolder() instanceof SGMenu;
}
/**
* In addition to the tests done by {@link #isSGMenu(Inventory)}, this method checks whether the instance of
* {@link SpiGUI} that this listener is listening on behalf of, holds a different plugin to the plugin that the
* inventory is for.
*
* <p>If the {@code inventory} is not an {@link SGMenu}, or it is held by a different plugin, the event should be
* ignored by this listener instance.
*
* @param inventory to check.
* @return False if the inventory event is for this plugin, true if not.
*/
protected boolean shouldIgnoreGUI(@Nullable Inventory inventory) {
return !isSGMenu(inventory)
|| !Objects.equals(
((SGMenu) Objects.requireNonNull(inventory).getHolder()).getOwner(), spiGUI.getOwner());
}
/**
* Handles the main click event for an {@link SGMenu}.
*
* <p>This is a protected method, intended to be delegated to by subclasses of this class and {@link Listener}, so
* as to re-use common logic across versions whilst providing an avenue for version-specific overrides.
*
* <p>The respective inventory is first checked to ensure that it is a SpiGUI {@link SGMenu} and, if it is, whether
* a pagination button was clicked, finally (if not a pagination button) the event is delegated to the inventory the
* click occurred in.
*
* @param event to handle.
* @see SpiGUI#SpiGUI(JavaPlugin)
*/
protected void handleClick(@Nonnull InventoryClickEvent event) {
// Check if the inventory click event is one we should even care about (i.e., that the inventory is actually a
// SpiGUI owned by the current plugin). Then, get the SGMenu instance that backs the inventory.
final Inventory inventory = event.getClickedInventory();
if (shouldIgnoreGUI(inventory)) return;
SGMenu menu = (SGMenu) inventory.getHolder();
// Snapshot information like the page as soon as possible to ensure it is correct by the time the event is
// handled.
final int page = menu.getCurrentPage();
final int pageSize = menu.getPageSize();
// If the action is explicitly blocked, deny the event.
if (menu.getBlockedMenuActions().stream().anyMatch(action -> action == event.getAction())) {
event.setResult(Event.Result.DENY);
return;
}
// If the click type is not permitted, instantly deny the event and
// do nothing else.
if (menu.getPermittedMenuClickTypes().stream().noneMatch(type -> type == event.getClick())) {
event.setResult(Event.Result.DENY);
return;
}
// If, by default, interactions should be blocked, do that now.
final boolean blockByDefault = menu.areDefaultInteractionsBlocked() || spiGUI.areDefaultInteractionsBlocked();
if (blockByDefault) event.setResult(Event.Result.DENY);
// Set up an SGButtonListener Consumer that can be used to invoke a listener where we want to.
final Consumer<SGButtonListener> invokeListener = listener -> listener.onClick(event);
// Handle pagination actions if the slot is on the pagination row.
if (event.getSlot() > pageSize) {
// Deny by default in the toolbar row.
event.setResult(Event.Result.DENY);
// Compute the toolbar offset (i.e., first icon in the toolbar row is 0).
final int offset = event.getSlot() - pageSize;
final SGToolbarBuilder paginationBuilder =
Optional.ofNullable(menu.getToolbarBuilder()).orElse(spiGUI.getDefaultToolbarBuilder());
// Build the button by deferring to the builder logic in the plugin.
final SGToolbarButtonType paginationButtonType = SGToolbarButtonType.getDefaultForSlot(offset);
final SGButton paginationButton =
paginationBuilder.buildToolbarButton(offset, menu.getCurrentPage(), paginationButtonType, menu);
// Attempt to invoke the listener for the button (if it exists), then exit early.
Optional.ofNullable(paginationButton).map(SGButton::getListener).ifPresent(invokeListener);
return;
}
// If the slot is 'stickied', get the button from the first page.
if (menu.isStickiedSlot(event.getSlot())) {
final SGButton button = menu.getButton(0, event.getSlot());
Optional.ofNullable(button).map(SGButton::getListener).ifPresent(invokeListener);
}
// Finally, handle the button normally.
Optional.ofNullable(menu.getButton(page, event.getSlot()))
.map(SGButton::getListener)
.ifPresent(invokeListener);
}
/**
* Blocks events that occur in adjacent inventories to an SGMenu when those events would affect the SGMenu. (For
* example, double-clicking on an item in the player's inventory that is the same as an item in the SGMenu).
*
* @param event to handle.
* @see SpiGUI#SpiGUI(JavaPlugin)
*/
protected void handleAdjacentClick(@Nonnull InventoryClickEvent event) {
// If the clicked inventory is not adjacent to a SpiGUI menu, ignore the click event.
if (shouldIgnoreGUI(event.getView().getTopInventory())) return;
// If the clicked inventory is the SpiGUI menu (the top inventory),
// ignore the click event (it will be handled by handleClick).
if (event.getClickedInventory() == event.getView().getTopInventory()) return;
// Otherwise, the clicked menu was the bottom inventory. Block the action in it if it is one of the actions
// blocked by the top (SGMenu).
final SGMenu menu = (SGMenu) event.getView().getTopInventory().getHolder();
if (menu != null && menu.getBlockedMenuActions().stream().anyMatch(action -> action == event.getAction())) {
event.setResult(Event.Result.DENY);
}
}
/**
* Blocks drag events in an {@link SGMenu} and between an {@link SGMenu} and an adjacent inventory.
*
* @param event to handle.
* @see SpiGUI#SpiGUI(JavaPlugin)
*/
protected void handleDrag(@Nonnull InventoryDragEvent event) {
if (shouldIgnoreGUI(event.getInventory())) return;
final SGMenu menu = (SGMenu) event.getInventory().getHolder();
// Cancel the drag event if any of the affected slots are in the
// SpiGUI menu (the top inventory).
if (slotsIncludeTopInventory(event.getView(), event.getRawSlots())) {
event.setResult(Event.Result.DENY);
}
}
/**
* Overrides the close event for an SGMenu, ensuring the {@link SGMenu#getOnClose()} handler is invoked when the
* inventory is closed.
*
* @param event to handle.
* @see SpiGUI#SpiGUI(JavaPlugin)
*/
protected void handleClose(@Nonnull InventoryCloseEvent event) {
if (shouldIgnoreGUI(event.getInventory())) return;
final SGMenu menu = (SGMenu) event.getInventory().getHolder();
// Invoke the inventory's onClose if there is one.
Optional.ofNullable(menu.getOnClose()).ifPresent(onClose -> onClose.accept(event));
}
/**
* Handles the main click event for an {@link SGMenu}.
*
* @param event to handle.
* @see #handleClick(InventoryClickEvent)
*/
@EventHandler
public void onInventoryClick(@Nonnull InventoryClickEvent event) {
this.handleClick(event);
}
/**
* Blocks events that occur in adjacent inventories to an SGMenu when those events would affect the SGMenu. (For
* example, double-clicking on an item in the player's inventory that is the same as an item in the SGMenu).
*
* <p>It is recommended that the event listener that invokes this method be defined with
* {@link org.bukkit.event.EventPriority#LOWEST}, meaning that the event handler will be invoked first (allowing
* subsequent event handlers to override it).
*
* @param event to handle.
* @see #handleAdjacentClick(InventoryClickEvent)
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onAdjacentInventoryClick(@Nonnull InventoryClickEvent event) {
this.handleAdjacentClick(event);
}
/**
* Blocks drag events in an {@link SGMenu} and between an {@link SGMenu} and an adjacent inventory.
*
* <p>It is recommended that the event listener that invokes this method be defined with
* {@link org.bukkit.event.EventPriority#LOWEST}, meaning that the event handler will be invoked first (allowing
* subsequent event handlers to override it).
*
* @param event to handle.
* @see #handleDrag(InventoryDragEvent)
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryDrag(@Nonnull InventoryDragEvent event) {
this.handleDrag(event);
}
/**
* Overrides the close event for an SGMenu, ensuring the {@link SGMenu#getOnClose()} handler is invoked when the
* inventory is closed.
*
* @param event to handle.
* @see #handleClose(InventoryCloseEvent)
*/
@EventHandler
public void onInventoryClose(@Nonnull InventoryCloseEvent event) {
this.handleClose(event);
}
/**
* Checks whether the specified set of slots includes any slots in the top inventory of the specified
* {@link InventoryView}.
*
* @param view The relevant {@link InventoryView}.
* @param slots The set of slots to check.
* @return True if the set of slots includes any slots in the top inventory, otherwise false.
*/
private boolean slotsIncludeTopInventory(@Nonnull InventoryView view, @Nonnull Set<Integer> slots) {
return slots.stream().anyMatch(slot -> {
// If the slot is bigger than the SpiGUI menu's page size,
// it's a pagination button, so we'll ignore it.
if (slot >= view.getTopInventory().getSize()) return false;
// Otherwise, we'll check if the slot's converted value matches
// its raw value. If it matches, it means the slot is in the
// SpiGUI menu, so we'll return true.
return slot == view.convertSlot(slot);
});
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/core/src/main/java/com/samjakob/spigui/menu/SGMenu.java | core/src/main/java/com/samjakob/spigui/menu/SGMenu.java | package com.samjakob.spigui.menu;
import java.util.*;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.java.JavaPlugin;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.toolbar.SGToolbarBuilder;
import com.samjakob.spigui.toolbar.SGToolbarButtonType;
/**
* SGMenu is used to implement the library's GUIs.
*
* <p>This is a Minecraft 'inventory' that contains items which can have programmable actions performed when they are
* clicked. Additionally, it automatically adds 'pagination' items if the menu overflows.
*
* <p>You do not instantiate this class when you need it - as you would have done with the older version of the library
* - rather you make a call to {@link SpiGUI#create(String, int)} or {@link SpiGUI#create(String, int, String)} from
* your plugin's {@link SpiGUI} instance.
*
* <p>This creates an inventory that is already associated with your plugin. The reason for this is explained in the
* {@link SpiGUI#SpiGUI(JavaPlugin)} class constructor implementation notes.
*/
public class SGMenu implements InventoryHolder {
/** The SpiGUI instance that created this inventory. */
@Nonnull
private final SpiGUI spiGUI;
// Inventory creation parameters
/** The title of the inventory. */
private String name;
/** A tag that may be used to identify the type of inventory. */
private String tag;
/** The number of rows to display per page. */
private int rowsPerPage;
// Items and slots.
/** The map of items in the inventory. */
private final Map<Integer, SGButton> items;
/** The set of sticky slots (that should remain when the page is changed). */
private final HashSet<Integer> stickiedSlots;
/** The toolbar builder used to render this GUI's toolbar. */
private SGToolbarBuilder toolbarBuilder;
/**
* Whether the pagination functionality should be enabled. (True adds pagination buttons when they're needed, false
* does not).
*/
private boolean enableAutomaticPagination;
// Current state
/** The currently selected page of the inventory. */
private int currentPage;
// Interaction management
/**
* Whether the "default" behaviors and interactions should be permitted or blocked. (True prevents default behaviors
* such as moving items in the inventory, false allows them).
*/
private boolean blockDefaultInteractions;
/**
* Any actions in this list will be blocked immediately without further processing if they occur in a SpiGUI menu.
*/
private HashSet<InventoryAction> blockedMenuActions = new HashSet<>(Arrays.asList(DEFAULT_BLOCKED_MENU_ACTIONS));
/** Any actions in this list will be blocked if they occur in the adjacent inventory to an SGMenu. */
private HashSet<InventoryAction> blockedAdjacentActions =
new HashSet<>(Arrays.asList(DEFAULT_BLOCKED_ADJACENT_ACTIONS));
/**
* Any click types not in this array will be immediately prevented in this menu without further processing (i.e.,
* the button's listener will not be called).
*/
private HashSet<ClickType> permittedMenuClickTypes;
// Event handlers
/** The action to be performed on close. */
private Consumer<InventoryCloseEvent> onClose;
/** The action to be performed on page change. */
private Consumer<SGMenu> onPageChange;
// -- DEFAULT PERMITTED / BLOCKED ACTIONS -- //
/** The default set of actions that are permitted if they occur in an SGMenu. */
private static final ClickType[] DEFAULT_PERMITTED_MENU_CLICK_TYPES =
new ClickType[] {ClickType.LEFT, ClickType.RIGHT};
/** The default set of actions that are blocked if they occur in an SGMenu. */
private static final InventoryAction[] DEFAULT_BLOCKED_MENU_ACTIONS =
new InventoryAction[] {InventoryAction.MOVE_TO_OTHER_INVENTORY, InventoryAction.COLLECT_TO_CURSOR};
/** The default set of actions that are blocked if they occur in the adjacent inventory to an SGMenu. */
private static final InventoryAction[] DEFAULT_BLOCKED_ADJACENT_ACTIONS =
new InventoryAction[] {InventoryAction.MOVE_TO_OTHER_INVENTORY, InventoryAction.COLLECT_TO_CURSOR};
/**
* <b>For internal use only</b>: you should probably use {@link SpiGUI#create(String, int)} or
* {@link SpiGUI#create(String, int, String)}!
*
* <p>Used by the library internally to construct an SGMenu. This method is not considered part of the stable public
* API - if you use it you should be prepared to make changes to it when you update your SpiGUI version.
*
* <p>The name parameter is color code translated.
*
* @param spiGUI The SpiGUI instance associated with this menu.
* @param name The name of the menu.
* @param rowsPerPage The number of rows per page in the menu.
* @param tag The tag associated with this menu.
* @param clickTypes The set of permitted click types.
*/
public SGMenu(@Nonnull SpiGUI spiGUI, String name, int rowsPerPage, String tag, @Nullable ClickType... clickTypes) {
this.spiGUI = Objects.requireNonNull(spiGUI);
this.name = ChatColor.translateAlternateColorCodes('&', name);
this.rowsPerPage = rowsPerPage;
this.tag = tag;
this.items = new HashMap<>();
this.stickiedSlots = new HashSet<>();
this.currentPage = 0;
this.permittedMenuClickTypes = clickTypes != null && clickTypes.length > 0
? new HashSet<>(Arrays.asList(clickTypes))
: new HashSet<>(Arrays.asList(DEFAULT_PERMITTED_MENU_CLICK_TYPES));
}
// -- INVENTORY SETTINGS -- //
/**
* This is a per-inventory version of {@link SpiGUI#setBlockDefaultInteractions(boolean)}.
*
* @see SpiGUI#setBlockDefaultInteractions(boolean)
* @param blockDefaultInteractions Whether the default behavior of click events should be cancelled.
*/
public void setBlockDefaultInteractions(boolean blockDefaultInteractions) {
this.blockDefaultInteractions = blockDefaultInteractions;
}
/**
* This is a per-inventory version of {@link SpiGUI#areDefaultInteractionsBlocked()}.
*
* @see SpiGUI#areDefaultInteractionsBlocked()
* @return Whether the default behavior of click events should be cancelled.
*/
public boolean areDefaultInteractionsBlocked() {
return blockDefaultInteractions;
}
/**
* This is a per-inventory version of {@link SpiGUI#setEnableAutomaticPagination(boolean)}. If this value is set, it
* overrides the per-plugin option set in {@link SpiGUI}.
*
* @see SpiGUI#setEnableAutomaticPagination(boolean)
* @param enableAutomaticPagination Whether pagination buttons should be automatically added.
*/
public void setAutomaticPaginationEnabled(boolean enableAutomaticPagination) {
this.enableAutomaticPagination = enableAutomaticPagination;
}
/**
* This is a per-inventory version of {@link SpiGUI#isAutomaticPaginationEnabled()}.
*
* @see SpiGUI#isAutomaticPaginationEnabled()
* @return Whether pagination buttons should be automatically added.
*/
public Boolean isAutomaticPaginationEnabled() {
return enableAutomaticPagination;
}
/**
* This is a per-inventory version of ({@link SpiGUI#setDefaultToolbarBuilder(SGToolbarBuilder)}).
*
* @see SpiGUI#setDefaultToolbarBuilder(SGToolbarBuilder)
* @param toolbarBuilder The default toolbar builder used for GUIs.
*/
public void setToolbarBuilder(SGToolbarBuilder toolbarBuilder) {
this.toolbarBuilder = toolbarBuilder;
}
/**
* This is a per-inventory version of ({@link SpiGUI#getDefaultToolbarBuilder()}).
*
* @see SpiGUI#getDefaultToolbarBuilder()
* @return The default toolbar builder used for GUIs.
*/
public SGToolbarBuilder getToolbarBuilder() {
return this.toolbarBuilder;
}
// -- INVENTORY OWNER -- //
/**
* Returns the plugin that the inventory is associated with. As this field is final, this would be the plugin that
* created the inventory.
*
* @return The plugin the inventory is associated with.
*/
@Nonnull
public JavaPlugin getOwner() {
return spiGUI.getOwner();
}
// -- INVENTORY SIZE -- //
/**
* Returns the number of rows (of 9 columns) per page of the inventory. If you want the total number of slots on a
* page, you should use {@link #getPageSize()} instead.
*
* @return The number of rows per page.
*/
public int getRowsPerPage() {
return rowsPerPage;
}
/**
* Returns the number of slots per page of the inventory. This would be associated with the Bukkit/Spigot APIs
* inventory 'size' parameter.
*
* <p>So for example if {@link #getRowsPerPage()} was 3, this would be 27, as Minecraft Chest inventories have rows
* of 9 columns.
*
* @return The number of inventory slots per page.
*/
public int getPageSize() {
return rowsPerPage * 9;
}
/**
* Sets the number of rows per page of the inventory.
*
* <p>There is no way to set the number of slots per page directly, so if you need to do that, you'll need to divide
* the number of slots by 9 and supply the result to this parameter to achieve that.
*
* @param rowsPerPage The number of rows per page.
*/
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
// -- INVENTORY TAG -- //
/**
* This returns the GUI's tag.
*
* <p>The tag is used when getting all open inventories ({@link SpiGUI#findOpenWithTag(String)}) with your chosen
* tag. An example of where this might be useful is with a permission GUI - when the permissions are updated by one
* user in the GUI, it would be desirable to refresh the state of the permissions GUI for all users observing the
* GUI.
*
* @return The GUI's tag.
*/
public String getTag() {
return tag;
}
/**
* This sets the GUI's tag.
*
* @see #getTag()
* @see SpiGUI#findOpenWithTag(String)
* @param tag The GUI's tag.
*/
public void setTag(String tag) {
this.tag = tag;
}
// -- INVENTORY NAME -- //
/**
* This sets the inventory's display name.
*
* <p>The name parameter is color code translated before the value is set. If you want to avoid this behavior, you
* should use {@link #setRawName(String)} which sets the inventory's name directly.
*
* @param name The display name to set. (and to be color code translated)
*/
public void setName(String name) {
this.name = ChatColor.translateAlternateColorCodes('&', name);
}
/**
* This sets the inventory's display name <b>without</b> first translating color codes.
*
* @param name The display name to set.
*/
public void setRawName(String name) {
this.name = name;
}
/**
* This returns the inventory's display name.
*
* <p>Note that if you used {@link #setName(String)}, this will have been color code translated already.
*
* @return The inventory's display name.
*/
public String getName() {
return name;
}
// -- BUTTONS -- //
/**
* Adds the provided {@link SGButton}.
*
* @param button The button to add.
*/
public void addButton(SGButton button) {
// If slot 0 is empty, but it's the 'highest filled slot', then set slot 0 to contain button.
// (This is an edge case for when the whole inventory is empty).
if (getHighestFilledSlot() == 0 && getButton(0) == null) {
setButton(0, button);
return;
}
// Otherwise, add one to the highest filled slot, then use that slot for the new button.
setButton(getHighestFilledSlot() + 1, button);
}
/**
* Adds the specified {@link SGButton}s consecutively.
*
* @param buttons The buttons to add.
*/
public void addButtons(SGButton... buttons) {
for (SGButton button : buttons) addButton(button);
}
/**
* Adds the provided {@link SGButton} at the position denoted by the supplied slot parameter.
*
* <p>If you specify a value larger than the value of the first page, pagination will be automatically applied when
* the inventory is rendered. An alternative to this is to use {@link #setButton(int, int, SGButton)}.
*
* @see #setButton(int, int, SGButton)
* @param slot The desired location of the button.
* @param button The button to add.
*/
public void setButton(int slot, SGButton button) {
items.put(slot, button);
}
/**
* Adds the provided {@link SGButton} at the position denoted by the supplied slot parameter <i>on the page denoted
* by the supplied page parameter</i>.
*
* <p>This is an alias for {@link #setButton(int, SGButton)}, however one where the slot value is mapped to the
* specified page. So if page is 2 (the third page) and the inventory row count was 3 (so a size of 27), a supplied
* slot value of 3 would actually map to a slot value of (2 * 27) + 3 = 54. The mathematical formula for this is
* <code>(page * pageSize) + slot</code>.
*
* <p>If the slot value is out of the bounds of the specified page, this function will do nothing.
*
* @see #setButton(int, SGButton)
* @param page The page to which the button should be added.
* @param slot The position on that page the button should be added at.
* @param button The button to add.
*/
public void setButton(int page, int slot, SGButton button) {
if (slot < 0 || slot > getPageSize()) return;
setButton((page * getPageSize()) + slot, button);
}
/**
* Removes a button from the specified slot.
*
* @param slot The slot containing the button you wish to remove.
*/
public void removeButton(int slot) {
items.remove(slot);
}
/**
* An alias for {@link #removeButton(int)} to remove a button from the specified slot on the specified page.
*
* <p>If the slot value is out of the bounds of the specified page, this function will do nothing.
*
* @param page The page containing the button you wish to remove.
* @param slot The slot, of that page, containing the button you wish to remove.
*/
public void removeButton(int page, int slot) {
if (slot < 0 || slot > getPageSize()) return;
removeButton((page * getPageSize()) + slot);
}
/**
* Returns the {@link SGButton} in the specified slot.
*
* <p>If you attempt to get a slot less than 0 or greater than the slot containing the button at the greatest slot
* value, this will return null.
*
* @param slot The slot containing the button you wish to get.
* @return The {@link SGButton} that was in that slot or null if the slot was invalid or if there was no button that
* slot.
*/
public SGButton getButton(int slot) {
if (slot < 0 || slot > getHighestFilledSlot()) return null;
return items.get(slot);
}
/**
* This is an alias for {@link #getButton(int)} that allows you to get a button contained by a slot on a given page.
*
* @param page The page containing the button.
* @param slot The slot, on that page, containing the button.
* @return The {@link SGButton} that was in that slot or null if the slot was invalid or if there was no button that
* slot.
*/
public SGButton getButton(int page, int slot) {
if (slot < 0 || slot > getPageSize()) return null;
return getButton((page * getPageSize()) + slot);
}
// -- PAGINATION -- //
/**
* Returns the current page of the inventory. This is the page that will be displayed when the inventory is opened
* and displayed to a player (i.e. rendered).
*
* <p>The value returned by {@code getCurrentPage} and accepted by {@link #setCurrentPage(int)} is zero-indexed -
* that is, the first page is 0. The analogue for getting the maximum page is {@link #getMaxPageIndex()} (rather
* than {@link #getMaxPage()} which is now deprecated).
*
* <p>Unfortunately, the historic behavior for {@link #getMaxPage()} is confusingly that it would be one-indexed not
* zero-indexed - hence the deprecation (for clarity) - and it is anticipated that simply changing the behavior of
* that method would be subtle yet disastrous.
*
* @return The current page of the inventory.
* @see #getMaxPageIndex()
*/
public int getCurrentPage() {
return currentPage;
}
/**
* Sets the page of the inventory that will be displayed when the inventory is opened and displayed to a player
* (i.e. rendered).
*
* @param page The new current page of the inventory.
*/
public void setCurrentPage(int page) {
this.currentPage = page;
if (this.onPageChange != null) this.onPageChange.accept(this);
}
/**
* Gets the page number of the final page of the GUI.
*
* <p>This method is now an alias for {@link #getMaxPageNumber()}.
*
* @return The highest page number that can be viewed.
* @deprecated this method is ambiguous with regard to indexing (confusingly, this method is the one-indexed value
* for the maximum page whilst {@link #getCurrentPage()} is the zero-indexed value) - use
* {@link #getMaxPageIndex()} or {@link #getMaxPageNumber()} (the latter has the same behavior) instead to
* receive the expected value.
*/
@Deprecated
public int getMaxPage() {
return getMaxPageNumber();
}
/**
* Get the maximum page index that can be displayed (starting at 0).
*
* <p>For example, an empty inventory would have a maximum page index of 0 and a maximum page number of 1.
*
* @return the maximum page index.
* @see #getMaxPageNumber()
*/
public int getMaxPageIndex() {
return getMaxPageNumber() - 1;
}
/**
* Get the maximum page (natural) number that can be displayed (starting at 1).
*
* @return the maximum page number.
* @see #getMaxPageIndex()
*/
public int getMaxPageNumber() {
return (int) Math.ceil(((double) getHighestFilledSlot() + 1) / ((double) getPageSize()));
}
/**
* Returns the slot number of the highest filled slot. This is mainly used to calculate the number of pages there
* needs to be to display the GUI's contents in the rendered inventory.
*
* @return The highest filled slot's number.
*/
public int getHighestFilledSlot() {
int slot = 0;
for (int nextSlot : items.keySet()) {
if (items.get(nextSlot) != null && nextSlot > slot) slot = nextSlot;
}
return slot;
}
/**
* Increments the current page. This will automatically refresh the inventory by calling
* {@link #refreshInventory(HumanEntity)} if the page was changed.
*
* @param viewer The {@link HumanEntity} viewing the inventory.
* @return Whether the page could be changed (false means the max page is currently open).
*/
public boolean nextPage(HumanEntity viewer) {
if (currentPage < getMaxPageIndex()) {
currentPage++;
refreshInventory(viewer);
if (this.onPageChange != null) this.onPageChange.accept(this);
return true;
} else {
return false;
}
}
/**
* Decrements the current page. This will automatically refresh the inventory by calling
* {@link #refreshInventory(HumanEntity)} if the page was changed.
*
* @param viewer The {@link HumanEntity} viewing the inventory.
* @return Whether the page could be changed (false means the first page is currently open).
*/
public boolean previousPage(HumanEntity viewer) {
if (currentPage > 0) {
currentPage--;
refreshInventory(viewer);
if (this.onPageChange != null) this.onPageChange.accept(this);
return true;
} else {
return false;
}
}
// -- STICKY SLOTS -- //
/**
* Marks a slot as 'sticky', so that when the page is changed, the slot will always display the value on the first
* page.
*
* <p>This is useful for implementing things like 'toolbars', where you have a set of common items on every page.
*
* <p>If the slot is out of the bounds of the first page (i.e. less than 0 or greater than {@link #getPageSize()} -
* 1) this method will do nothing.
*
* @param slot The slot to mark as 'sticky'.
*/
public void stickSlot(int slot) {
if (slot < 0 || slot >= getPageSize()) return;
this.stickiedSlots.add(slot);
}
/**
* Un-marks a slot as sticky - thereby meaning that slot will display whatever its value on the current page is.
*
* @see #stickSlot(int)
* @param slot The slot to un-mark as 'sticky'.
*/
public void unstickSlot(int slot) {
this.stickiedSlots.remove(slot);
}
/**
* This clears all the 'stuck' slots - essentially un-marking all stuck slots.
*
* @see #stickSlot(int)
*/
public void clearStickiedSlots() {
this.stickiedSlots.clear();
}
/**
* This checks whether a given slot is sticky. If the slot is out of bounds of the first page (as defined by the
* same parameters as {@link #stickSlot(int)}), this will return false.
*
* @see #stickSlot(int)
* @param slot The slot to check.
* @return True if the slot is sticky, false if it isn't or the slot was out of bounds.
*/
public boolean isStickiedSlot(int slot) {
if (slot < 0 || slot >= getPageSize()) return false;
return this.stickiedSlots.contains(slot);
}
/**
* This clears all slots in the inventory, except those which have been marked as 'sticky'.
*
* @see #stickSlot(int)
*/
public void clearAllButStickiedSlots() {
this.currentPage = 0;
items.entrySet().removeIf(item -> !isStickiedSlot(item.getKey()));
}
// -- EVENTS -- //
/**
* The action to be performed on close.
*
* @return The action to be performed on close.
* @see #setOnClose(Consumer)
*/
public Consumer<InventoryCloseEvent> getOnClose() {
return this.onClose;
}
/**
* Used to set an action to be performed on inventory close without registering an
* {@link org.bukkit.event.inventory.InventoryCloseEvent} specifically for this inventory.
*
* @param onClose The action to be performed on close.
*/
public void setOnClose(Consumer<InventoryCloseEvent> onClose) {
this.onClose = onClose;
}
/**
* The action to be performed on page change.
*
* @return The action to be performed on page change.
* @see #setOnPageChange(Consumer)
*/
public Consumer<SGMenu> getOnPageChange() {
return this.onPageChange;
}
/**
* Used to set an action to be performed on inventory page change.
*
* @param onPageChange The action to be performed on page change.
*/
public void setOnPageChange(Consumer<SGMenu> onPageChange) {
this.onPageChange = onPageChange;
}
/**
* Returns the permitted menu click types.
*
* @return A hashSet of permitted menu click types
*/
public HashSet<ClickType> getPermittedMenuClickTypes() {
return this.permittedMenuClickTypes;
}
/**
* Returns an array of blocked menu actions for the current Inventory.
*
* @return A hashSet of blocked menu actions
*/
public HashSet<InventoryAction> getBlockedMenuActions() {
return this.blockedMenuActions;
}
/**
* Returns the blocked adjacent actions for this object.
*
* @return A hashSet of InventoryAction objects representing the blocked adjacent actions.
*/
public HashSet<InventoryAction> getBlockedAdjacentActions() {
return this.blockedAdjacentActions;
}
/**
* Sets the permitted menu click types.
*
* @param clickTypes One or more click types you want to allow for this menu.
*/
public void setPermittedMenuClickTypes(ClickType... clickTypes) {
this.permittedMenuClickTypes = new HashSet<>(Arrays.asList(clickTypes));
}
/**
* Sets the blocked menu actions for the inventory.
*
* @param actions the menu actions to be blocked
*/
public void setBlockedMenuActions(InventoryAction... actions) {
this.blockedMenuActions = new HashSet<>(Arrays.asList(actions));
}
/**
* Sets the blocked adjacent actions for this object.
*
* @param actions The actions to be blocked.
*/
public void setBlockedAdjacentActions(InventoryAction... actions) {
this.blockedAdjacentActions = new HashSet<>(Arrays.asList(actions));
}
/**
* Adds a permitted click type to the menu.
*
* @param clickType the click type to be added
*/
public void addPermittedClickType(ClickType clickType) {
this.permittedMenuClickTypes.add(clickType);
}
/**
* Adds the given InventoryAction to the list of blocked menu actions. Blocked menu actions are actions that are not
* allowed to be performed on the inventory menu.
*
* @param action The InventoryAction to be added to the blocked menu actions list.
*/
public void addBlockedMenuAction(InventoryAction action) {
this.blockedMenuActions.add(action);
}
/**
* Adds a blocked adjacent action to the list of blocked adjacent actions.
*
* @param action The inventory action to be added as blocked adjacent action.
*/
public void addBlockedAdjacentAction(InventoryAction action) {
this.getBlockedAdjacentActions().add(action);
}
/**
* Removes a permitted click type from the list of permitted menu click types.
*
* @param clickType the click type to be removed
*/
public void removePermittedClickType(ClickType clickType) {
this.permittedMenuClickTypes.remove(clickType);
}
/**
* Removes the specified InventoryAction from the list of blocked menu actions.
*
* @param action the InventoryAction to be removed
*/
public void removeBlockedMenuAction(InventoryAction action) {
this.blockedMenuActions.remove(action);
}
/**
* Removes the given action from the list of blocked adjacent actions.
*
* @param action The action to be removed
*/
public void removeBlockedAdjacentAction(InventoryAction action) {
this.getBlockedAdjacentActions().remove(action);
}
// -- INVENTORY API -- //
/**
* Refresh an inventory that is currently open for a given viewer.
*
* <p>This method checks if the specified viewer is looking at an {@link SGMenu} and, if they are, it refreshes the
* inventory for them.
*
* @param viewer The viewer of the open inventory.
*/
public void refreshInventory(HumanEntity viewer) {
// If the open inventory isn't an SGMenu - or if it isn't this inventory, do nothing.
if (!(viewer.getOpenInventory().getTopInventory().getHolder() instanceof SGMenu)
|| viewer.getOpenInventory().getTopInventory().getHolder() != this) return;
// If the new size is different, we'll need to open a new inventory.
if (viewer.getOpenInventory().getTopInventory().getSize() != getPageSize() + (getMaxPageNumber() > 0 ? 9 : 0)) {
viewer.openInventory(getInventory());
return;
}
// If the name has changed, we'll need to open a new inventory.
String newName = name.replace("{currentPage}", String.valueOf(currentPage + 1))
.replace("{maxPage}", String.valueOf(getMaxPageNumber()));
if (!viewer.getOpenInventory().getTitle().equals(newName)) {
viewer.openInventory(getInventory());
return;
}
// Otherwise, we can refresh the contents without re-opening the inventory.
viewer.getOpenInventory().getTopInventory().setContents(getInventory().getContents());
}
/**
* Returns the Bukkit/Spigot {@link Inventory} that represents the GUI. This is shown to a player using
* {@link HumanEntity#openInventory(Inventory)}.
*
* @return The created inventory used to display the GUI.
*/
@Override
public Inventory getInventory() {
boolean isAutomaticPaginationEnabled = spiGUI.isAutomaticPaginationEnabled();
if (isAutomaticPaginationEnabled() != null) {
isAutomaticPaginationEnabled = isAutomaticPaginationEnabled();
}
boolean needsPagination = getMaxPageNumber() > 0 && isAutomaticPaginationEnabled;
Inventory inventory = Bukkit.createInventory(
this,
((needsPagination)
// Pagination enabled: add the bottom toolbar row.
? getPageSize() + 9
// Pagination not required or disabled.
: getPageSize()),
name.replace("{currentPage}", String.valueOf(currentPage + 1))
.replace("{maxPage}", String.valueOf(getMaxPageNumber())));
// Add the main inventory items.
for (int key = currentPage * getPageSize(); key < (currentPage + 1) * getPageSize(); key++) {
// If we've already reached the maximum assigned slot, stop assigning
// slots.
if (key > getHighestFilledSlot()) break;
if (items.containsKey(key)) {
inventory.setItem(
key - (currentPage * getPageSize()), items.get(key).getIcon());
}
}
// Update the stickied slots.
for (int stickiedSlot : stickiedSlots) {
inventory.setItem(stickiedSlot, items.get(stickiedSlot).getIcon());
}
// Render the pagination items.
if (needsPagination) {
SGToolbarBuilder toolbarButtonBuilder = spiGUI.getDefaultToolbarBuilder();
if (getToolbarBuilder() != null) {
toolbarButtonBuilder = getToolbarBuilder();
}
int pageSize = getPageSize();
for (int i = pageSize; i < pageSize + 9; i++) {
int offset = i - pageSize;
SGButton paginationButton = toolbarButtonBuilder.buildToolbarButton(
offset, getCurrentPage(), SGToolbarButtonType.getDefaultForSlot(offset), this);
inventory.setItem(i, paginationButton != null ? paginationButton.getIcon() : null);
}
}
return inventory;
}
@Override
public String toString() {
return new StringJoiner(", ", SGMenu.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("tag='" + tag + "'")
.add("rowsPerPage=" + rowsPerPage)
.add("currentPage=" + currentPage)
.toString();
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
SamJakob/SpiGUI | https://github.com/SamJakob/SpiGUI/blob/9244f5c484bc09a5eb01a084aecf83899959eccf/demo/src/main/java/com/samjakob/spiguitest/SpiGUITest.java | demo/src/main/java/com/samjakob/spiguitest/SpiGUITest.java | package com.samjakob.spiguitest;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;
import javax.annotation.Nonnull;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import com.samjakob.spigui.SpiGUI;
import com.samjakob.spigui.buttons.SGButton;
import com.samjakob.spigui.item.ItemBuilder;
import com.samjakob.spigui.menu.SGMenu;
/**
* SpiGUITest
*
* <p>Simple test plugin to showcase some of the functionality of SpiGUI.
*
* @author SamJakob
* @version 2.0.0
*/
@SuppressWarnings("deprecation")
public class SpiGUITest extends JavaPlugin {
/*
Please feel free to use code from here. Though, do note that it is a very rough proof of concept intended to
showcase and test some of the functionality of SpiGUI.
*/
/** The SpiGUI instance for the {@link SpiGUITest} plugin. */
private static SpiGUI spiGUI;
// Start: variables for demonstration purposes.
/** Fake "gem" count per-player. */
private final Map<Player, Integer> gems = new HashMap<>();
// End: variables for demonstration purposes.
/** Default constructor. */
public SpiGUITest() {}
@Override
public void onEnable() {
spiGUI = new SpiGUI(this);
}
@Override
public boolean onCommand(
@Nonnull final CommandSender sender,
final Command command,
@Nonnull final String label,
@Nonnull final String[] args) {
if (command.getLabel().equalsIgnoreCase("spigui")) {
if (!(sender instanceof Player player)) {
sender.sendMessage("[SpiGUI] [ERROR] You must be a player to run this command.");
return true;
}
// START DEFAULT INVENTORY
// This is a menu intended to showcase general functionality.
if (args.length == 0) {
// Open a test SpiGUI menu.
SGMenu myAwesomeMenu = SpiGUITest.getSpiGUI().create("&c&lSpiGUI &c(Page {currentPage}/{maxPage})", 3);
myAwesomeMenu.setToolbarBuilder((slot, page, defaultType, menu) -> {
if (slot == 8) {
return new SGButton(ItemBuilder.create(Material.EMERALD)
.name(String.format("&a&l%d gems", gems.getOrDefault(player, 5)))
.lore(
"&aUse gems to buy cosmetics",
"&aand other items in the store!",
"",
"&7&o(Click to add more)")
.build())
.withListener((event) -> {
gems.put(player, gems.getOrDefault(player, 5) + 5);
player.sendMessage(ChatColor.translateAlternateColorCodes(
'&', "&a&l&oSUCCESS! &aYou have been given &25 &agems!"));
menu.refreshInventory(event.getWhoClicked());
});
}
// Fallback to rendering the default button for a slot.
return spiGUI.getDefaultToolbarBuilder().buildToolbarButton(slot, page, defaultType, menu);
// Or, alternatively, to render a button when NEITHER a custom per-inventory button OR a fallback
// button has been defined:
// (Comment above line and uncomment below to enable this)
/*
// Ensure fallbackButton is not null before rendering. If it is, render an alternative button
// instead.
SGButton fallbackButton = spiGUI.getDefaultToolbarBuilder().buildToolbarButton(slot, page, defaultType, menu);
if (fallbackButton != null) return fallbackButton;
return new SGButton(new ItemBuilder(Material.BARRIER).name(" ").build());
// You could check if defaultType is UNASSIGNED, however this won't deal with the cases when the
// previous or next button is not shown (there will be an empty space).
*/
});
myAwesomeMenu.setButton(
0,
10,
new SGButton(ItemBuilder.create(Material.LEGACY_SKULL_ITEM)
.skullOwner(player.getName())
.name("&e&l" + player.getDisplayName())
.lore(
"&eGame Mode: &6" + player.getGameMode(),
"&eLocation: &6"
+ String.format(
"%.0f, %.0f, %.0f",
player.getLocation().getX(),
player.getLocation().getY(),
player.getLocation().getZ()),
"&eExperience: &6" + player.getTotalExperience())
.build()));
myAwesomeMenu.setButton(
1,
0,
new SGButton(ItemBuilder.create(Material.GOLD_ORE)
.name("&6Get rich quick!")
.build())
.withListener(event -> {
Inventory playerInventory =
event.getWhoClicked().getInventory();
IntStream.range(0, 9)
.forEach(hotBarSlot -> playerInventory.setItem(
hotBarSlot,
ItemBuilder.create(
event.getCurrentItem()
.getType()
== Material.GOLD_ORE
? Material.GOLD_BLOCK
: event.getCurrentItem()
.getType())
.amount(64)
.build()));
event.getWhoClicked()
.sendMessage(ChatColor.translateAlternateColorCodes(
'&',
event.getCurrentItem().getType() == Material.GOLD_ORE
? "&e&lYou are now rich!"
: "&7&lYou are now poor."));
Material newMaterial =
event.getCurrentItem().getType() == Material.GOLD_ORE
? Material.DIRT
: Material.GOLD_ORE;
myAwesomeMenu
.getButton(1, 0)
.setIcon(ItemBuilder.create(newMaterial)
.name(
newMaterial == Material.GOLD_ORE
? "&6Get rich quick!"
: "&7Get poor quick!")
.amount(1)
.build());
myAwesomeMenu.refreshInventory(event.getWhoClicked());
((Player) event.getWhoClicked()).updateInventory();
}));
AtomicReference<BukkitTask> borderRunnable = new AtomicReference<>();
myAwesomeMenu.setOnPageChange(inventory -> {
if (inventory.getCurrentPage() != 0) {
if (borderRunnable.get() != null) borderRunnable.get().cancel();
} else
borderRunnable.set(
inventory.getCurrentPage() != 0
? null
: new BukkitRunnable() {
private final int[] TILES_TO_UPDATE = {
// @spotless:off
0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26
// @spotless:on
};
private short currentColor = 1;
@Override
public void run() {
IntStream.range(0, TILES_TO_UPDATE.length)
.map(i -> TILES_TO_UPDATE.length - i + -1)
.forEach(index -> myAwesomeMenu.setButton(
TILES_TO_UPDATE[index], nextColorButton()));
currentColor++;
if (currentColor >= 15) currentColor = 0;
myAwesomeMenu.refreshInventory(player);
}
private SGButton nextColorButton() {
return new SGButton(ItemBuilder.create(
Material.LEGACY_STAINED_GLASS_PANE)
.name("&" + Integer.toHexString(currentColor) + "&lSpiGUI!!!")
.data(currentColor)
.build());
}
}.runTaskTimer(this, 0L, 20L));
});
myAwesomeMenu.setOnClose(inventory -> {
if (borderRunnable.get() != null) borderRunnable.get().cancel();
});
myAwesomeMenu.getOnPageChange().accept(myAwesomeMenu);
player.openInventory(myAwesomeMenu.getInventory());
return true;
}
// END DEFAULT INVENTORY
// The following are additional menus intended to test specific functionality:
switch (args[0]) {
case "inventorySizeTest": {
int size;
if (args.length == 1) {
player.sendMessage(ChatColor.translateAlternateColorCodes(
'&', "&c&l&oERROR &cYou must specify an item count as an integer."));
return true;
}
try {
size = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
player.sendMessage(ChatColor.translateAlternateColorCodes(
'&', "&c&l&oERROR &cThe item count must be a valid integer."));
return true;
}
// Create a menu with one row, so that pagination values are easy to calculate (each page is a
// multiple of 9, then the remainder can just be added to ensure the number of items match up).
SGMenu inventorySizeTest = SpiGUITest.getSpiGUI().create("Test Menu", 1);
IntStream.range(0, size)
.forEach(i -> inventorySizeTest.addButton(new SGButton(ItemBuilder.create(Material.GOLD_ORE)
.name(String.format("&6Item %d", i + 1))
.build())));
player.openInventory(inventorySizeTest.getInventory());
return true;
}
case "refreshTest": {
SGMenu refreshTestMenu = SpiGUITest.getSpiGUI().create("&bMatches", 1);
// Generate 3 to 8 random matches.
List<Match> matches = IntStream.range(
0, ThreadLocalRandom.current().nextInt(5) + 3)
.mapToObj((i) -> Match.generateFakeMatch(true))
.toList();
for (int i = 0; i < matches.size(); i++) {
Match match = matches.get(i);
refreshTestMenu.setButton(
i,
new SGButton(ItemBuilder.from(match.getKit().icon())
.name(match.getKit().name())
.lore(
String.format(
"&a%s &evs. &a%s",
match.getPlayerNames()[0], match.getPlayerNames()[1]),
String.format("&fTime: &b%s", match.getTime()),
"",
String.format(
"&fKit: &b%s",
match.getKit().name()),
String.format(
"&fArena: &b%s &7(%s)",
match.getArena(),
match.getKit().name()))
.build()));
}
// Start a refresh task for the menu.
AtomicReference<BukkitTask> refreshMatchesTask = new AtomicReference<>(
new BukkitRunnable() {
@Override
public void run() {
for (int i = 0; i < matches.size(); i++) {
Match match = matches.get(i);
refreshTestMenu.setButton(
i,
new SGButton(ItemBuilder.from(
match.getKit().icon())
.flag(ItemFlag.HIDE_ATTRIBUTES)
.flag(ItemFlag.HIDE_DESTROYS)
.flag(ItemFlag.HIDE_PLACED_ON)
.flag(ItemFlag.HIDE_ADDITIONAL_TOOLTIP)
.name(match.getKit().name())
.lore(
String.format(
"&a%s &evs. &a%s",
match.getPlayerNames()[0],
match.getPlayerNames()[1]),
String.format("&fTime: &b%s", match.getTime()),
"",
String.format(
"&fKit: &b%s",
match.getKit()
.name()),
String.format(
"&fArena: &b%s &7(%s)",
match.getArena(),
match.getKit()
.name()))
.build()));
}
refreshTestMenu.refreshInventory(player);
}
}.runTaskTimer(this, 0L, 20L));
// Cancel the refresh task when the inventory is closed.
refreshTestMenu.setOnClose(menu -> {
if (refreshMatchesTask.get() != null)
refreshMatchesTask.get().cancel();
});
player.openInventory(refreshTestMenu.getInventory());
return true;
}
}
player.sendMessage("Unrecognized command.");
}
return false;
}
/**
* Get the {@link SpiGUI} instance for {@link SpiGUITest}.
*
* @return the {@link SpiGUI} instance to be used by the plugin to show GUIs.
*/
public static SpiGUI getSpiGUI() {
return spiGUI;
}
// The following is mock classes/data for the above test GUIs.
/**
* Mock player kit.
*
* @param name of the kit.
* @param icon to display for the kit.
*/
private record Kit(String name, ItemStack icon) {}
/** Mock match. */
private static class Match {
/** Tracks the state of a {@link Match}. */
private enum MatchState {
/** Waiting to start. */
WAITING,
/** Currently ongoing. */
ONGOING,
/** Ended. */
ENDED
}
// Begin mock data.
/** Fake player names to show. */
private static final String[] fakePlayerNames = {
"MoreHaro",
"Pixelle",
"SpyPlenty",
"Winlink",
"Herobrine",
"Notch",
"Dinnerbone",
"CinnamonTown",
"TreeMushrooms"
};
/** Fake kits to show. */
private static final Kit[] fakeKits = {
new Kit(
"Classic Battle",
ItemBuilder.create(Material.STONE_SWORD)
.name("&7Classic Battle")
.build()),
new Kit(
"OP Battle",
ItemBuilder.create(Material.DIAMOND_SWORD)
.name("&bOP Battle")
.build()),
new Kit(
"Classic UHC",
ItemBuilder.create(Material.GOLDEN_APPLE)
.name("&eClassic UHC")
.build()),
new Kit(
"OP UHC",
ItemBuilder.create(Material.GOLDEN_APPLE)
.data((short) 1)
.name("&6OP UHC")
.build()),
};
/** Fake arena names to show. */
private static final String[] fakeArenas = {"King's Road", "Ilios", "Fort Starr", "The Hopper"};
/**
* Generates a Match with fake data for display purposes.
*
* @return the generated fake match.
*/
public static Match generateFakeMatch() {
return generateFakeMatch(false);
}
/**
* Generate a fake match with a fake start time if {@code alreadyStarted} is true.
*
* @param alreadyStarted indicates that a fake start time should be generated.
* @return the generated fake match.
*/
public static Match generateFakeMatch(boolean alreadyStarted) {
// Ensure unique values are generated for player1 and player2.
int player1 = ThreadLocalRandom.current().nextInt(fakePlayerNames.length);
int player2;
do {
player2 = ThreadLocalRandom.current().nextInt(fakePlayerNames.length);
} while (player2 == player1);
Match fakeMatch = new Match(
new String[] {fakePlayerNames[player1], fakePlayerNames[player2]},
fakeKits[ThreadLocalRandom.current().nextInt(fakeKits.length)],
fakeArenas[ThreadLocalRandom.current().nextInt(fakeArenas.length)]);
if (alreadyStarted) {
// If alreadyStarted specified to true, then generate a match with current time minus up to 5 minutes.
fakeMatch.matchStartTime =
System.currentTimeMillis() - ThreadLocalRandom.current().nextLong(5 * 60000);
}
return fakeMatch;
}
// End mock data.
/** List of players in match. Two players implies a duel. */
private final String[] playerNames;
/**
* Get the list of player names for each player involved in the match.
*
* @return the array of names for players in the match.
*/
public String[] getPlayerNames() {
return playerNames;
}
/** Match start time in UNIX milliseconds. */
private Long matchStartTime;
/** Match end time in UNIX milliseconds. */
private Long matchEndTime;
/** Name of the kit used for the duel. */
private final Kit kit;
/**
* The kit information that is given to players in the match.
*
* @return the kit for the match.
*/
public Kit getKit() {
return kit;
}
/** Name of the arena used for the duel. */
private final String arena;
/**
* The arena for the match.
*
* @return the name of the arena.
*/
public String getArena() {
return arena;
}
/**
* Get the duration of the match.
*
* @return status text or a live time to display for the match's status.
*/
public String getTime() {
switch (getState()) {
case WAITING:
return "Waiting...";
case ONGOING:
case ENDED: {
long duration = (matchEndTime != null ? matchEndTime : System.currentTimeMillis()) - matchStartTime;
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(minutes);
return String.format("%02d:%02d", minutes, seconds);
}
}
return "ERROR";
}
/**
* Construct a match with given values.
*
* @param playerNames involved in the match.
* @param kit given to each player in the match.
* @param arena that the match will take place in.
*/
public Match(String[] playerNames, Kit kit, String arena) {
this.playerNames = playerNames;
this.kit = kit;
this.arena = arena;
}
/** Start the match (record the start time). */
public void start() {
if (this.matchStartTime != null) throw new IllegalStateException("Match already started!");
this.matchStartTime = System.currentTimeMillis();
}
/** Stop the match (record the end time). */
public void stop() {
if (this.matchEndTime != null) throw new IllegalStateException("Match already finished!");
this.matchEndTime = System.currentTimeMillis();
}
/**
* Get the status of the match.
*
* @return the {@link MatchState} for the match.
*/
public MatchState getState() {
if (this.matchStartTime == null) return MatchState.WAITING;
else if (this.matchEndTime == null) return MatchState.ONGOING;
return MatchState.ENDED;
}
}
}
| java | MIT | 9244f5c484bc09a5eb01a084aecf83899959eccf | 2026-01-05T02:40:39.874653Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/BFTNode.java | src/bft/BFTNode.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft;
import bft.util.BFTCommon;
import bft.util.MSPManager;
import bft.util.BlockCutter;
import bft.util.ECDSAKeyLoader;
import bftsmart.reconfiguration.util.TOMConfiguration;
import bftsmart.tom.MessageContext;
import bftsmart.tom.ServiceReplica;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.server.defaultservices.DefaultRecoverable;
import bftsmart.tom.server.defaultservices.DefaultReplier;
import com.google.protobuf.ByteString;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.common.Configtx;
import org.hyperledger.fabric.protos.msp.Identities;
import org.hyperledger.fabric.protos.orderer.Configuration;
import org.hyperledger.fabric.sdk.helper.Config;
/**
*
* @author joao
*/
public class BFTNode extends DefaultRecoverable {
private static String configDir;
private final int id;
private final CryptoPrimitives crypto;
private final Logger logger;
private final Logger loggerThroughput;
private final TOMConfiguration replicaConf;
private ServiceReplica replica = null;
// Own MSP artifacts
private String mspid = null;
private PrivateKey privKey = null;
private X509Certificate certificate = null;
private byte[] serializedCert = null;
private Identities.SerializedIdentity ident;
//envelope validation stuff
private boolean bothSigs;
private boolean envValidation;
private boolean filterMalformed;
private long timeWindow;
//signature thread stuff
private int parallelism;
LinkedBlockingQueue<BlockWorkerThread> queue;
private ExecutorService executor = null;
private int blocksPerThread;
private int sigIndex = 0;
private BlockWorkerThread currentSST = null;
//measurements
private int interval;
private long envelopeMeasurementStartTime = -1;
private long blockMeasurementStartTime = -1;
private int countEnvelopes = 0;
private int countBlocks = 0;
//used to avoid the block worker threads from accessing a null pointer in 'replica'
private final Lock replicaLock;
private final Condition replicaReady;
//these attributes are the state of this replicated state machine
private BlockCutter blockCutter;
private int sequence = 0;
private MSPManager mspManager = null;
private Map<String,Common.BlockHeader> lastBlockHeaders;
// these are treated as SMR state, but so far they are updated only at replica start up or upon system channel creation.
private String sysChannel = "";
private Common.Block sysGenesis;
private Set<Integer> receivers;
public BFTNode(int id) throws IOException, InvalidArgumentException, CryptoException, NoSuchAlgorithmException, NoSuchProviderException, InterruptedException, ClassNotFoundException, IllegalAccessException, InstantiationException, CertificateException, InvalidKeySpecException {
this.replicaLock = new ReentrantLock();
this.replicaReady = replicaLock.newCondition();
this.id = id;
this.crypto = new CryptoPrimitives();
this.crypto.init();
BFTCommon.init(crypto);
ECDSAKeyLoader loader = new ECDSAKeyLoader(this.id, this.configDir, this.crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
this.replicaConf = new TOMConfiguration(this.id, this.configDir, loader, Security.getProvider("BC"));
loadConfig();
privKey = loader.loadPrivateKey();
certificate = loader.loadCertificate();
serializedCert = BFTCommon.getSerializedCertificate(certificate);
ident = BFTCommon.getSerializedIdentity(mspid, serializedCert);
this.logger = LoggerFactory.getLogger(BFTNode.class);
this.loggerThroughput = LoggerFactory.getLogger("throughput");
this.queue = new LinkedBlockingQueue<>();
this.executor = Executors.newWorkStealingPool(this.parallelism);
for (int i = 0; i < parallelism; i++) {
this.executor.execute(new BlockWorkerThread(this.queue));
}
this.sequence = 0;
this.lastBlockHeaders = new TreeMap<>();
//this.lastConfigs = new TreeMap<>();
//this.chanConfigs = new TreeMap<>();
this.blockCutter = BlockCutter.getInstance();
logger.info("Starting up ordering node with system channel " + this.sysChannel);
logger.info("This is the signature algorithm: " + this.crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
logger.info("This is the hash algorithm: " + this.crypto.getProperties().getProperty(Config.HASH_ALGORITHM));
this.mspManager = MSPManager.getInstance(mspid, sysChannel);
this.replica = new ServiceReplica(this.id, this.configDir, this, this, null,
new DefaultReplier() {
@Override
public void manageReply(TOMMessage tomm, MessageContext mc) {
// send reply only if it is one of the clients from the connection pool or if it is the first message of the proxy
if (!receivers.contains(tomm.getSender()) || (receivers.contains(tomm.getSender()) && tomm.getSequence() == 0)) {
super.manageReply(tomm, mc);
}
}
}, loader, Security.getProvider("BC"));
this.replicaLock.lock();
this.replicaReady.signalAll();
this.replicaLock.unlock();
}
private void loadConfig() throws IOException, CertificateException {
LineIterator it = FileUtils.lineIterator(new File(this.configDir + "node.config"), "UTF-8");
Map<String,String> configs = new TreeMap<>();
while (it.hasNext()) {
String line = it.nextLine();
if (!line.startsWith("#") && line.contains("=")) {
String[] params = line.split("\\=");
configs.put(params[0], params[1]);
}
}
it.close();
mspid = configs.get("MSPID");
parallelism = Integer.parseInt(configs.get("PARELLELISM"));
blocksPerThread = Integer.parseInt(configs.get("BLOCKS_PER_THREAD"));
bothSigs = Boolean.parseBoolean(configs.get("BOTH_SIGS"));
envValidation = Boolean.parseBoolean(configs.get("ENV_VALIDATION"));
interval = Integer.parseInt(configs.get("THROUGHPUT_INTERVAL"));
filterMalformed = Boolean.parseBoolean(configs.get("FILTER_MALFORMED"));
FileInputStream input = new FileInputStream(new File(configs.get("GENESIS")));
sysGenesis = Common.Block.parseFrom(IOUtils.toByteArray(input));
Common.Envelope env = Common.Envelope.parseFrom(sysGenesis.getData().getData(0));
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.ChannelHeader chanHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
sysChannel = chanHeader.getChannelId();
String window = configs.get("TIME_WINDOW");
timeWindow = BFTCommon.parseDuration(window).toMillis();
String[] IDs = configs.get("RECEIVERS").split("\\,");
int[] recvs = Arrays.asList(IDs).stream().mapToInt(Integer::parseInt).toArray();
this.receivers = new TreeSet<>();
for (int o : recvs) {
this.receivers.add(o);
}
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Use: java bft.BFTNode <processId>");
System.exit(-1);
}
configDir = BFTCommon.getBFTSMaRtConfigDir("NODE_CONFIG_DIR");
if (System.getProperty("logback.configurationFile") == null)
System.setProperty("logback.configurationFile", configDir + "logback.xml");
Security.addProvider(new BouncyCastleProvider());
new BFTNode(Integer.parseInt(args[0]));
}
@Override
public void installSnapshot(byte[] state) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(state);
DataInputStream in = new DataInputStream(bis);
sysChannel = in.readUTF();
sequence = in.readInt();
receivers = new TreeSet<Integer>();
int n = in.readInt();
for (int i = 0; i < n; i++) {
receivers.add(new Integer(in.readInt()));
}
byte[] headers = new byte[0];
n = in.readInt();
if (n > 0) {
headers = new byte[n];
in.read(headers);
}
byte[] sysBytes = new byte[0];
n = in.readInt();
if (n > 0) {
sysBytes = new byte[n];
in.read(sysBytes);
}
n = in.readInt();
if (n > 0) {
byte[] b = new byte[n];
in.read(b);
blockCutter = BlockCutter.deserialize(b);
}
n = in.readInt();
if (n > 0) {
byte[] b = new byte[n];
in.read(b);
mspManager = MSPManager.deserialize(mspid, sysChannel, b);
}
//deserialize headers
ByteArrayInputStream b = new ByteArrayInputStream(headers);
ObjectInput i = new ObjectInputStream(b);
this.lastBlockHeaders = (Map<String,Common.BlockHeader>) i.readObject();
i.close();
b.close();
//deserialize system genesis block
b = new ByteArrayInputStream(sysBytes);
i = new ObjectInputStream(b);
this.sysGenesis = (Common.Block) i.readObject();
i.close();
b.close();
} catch (Exception ex) {
logger.error("Failed to install snapshot", ex);
}
}
@Override
public byte[] getSnapshot() {
try {
//serialize block headers
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutput o = new ObjectOutputStream(b);
o.writeObject(lastBlockHeaders);
o.flush();
byte[] headers = b.toByteArray();
b.close();
o.close();
//serialize system genesis block
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(sysGenesis);
o.flush();
byte[] sysBytes = b.toByteArray();
b.close();
o.close();
//serialize receivers
Integer[] orderers;
if (this.receivers != null) {
orderers = new Integer[this.receivers.size()];
this.receivers.toArray(orderers);
} else {
orderers = new Integer[0];
}
//serialize block cutter
byte[] blockcutter = (blockCutter != null ? blockCutter.serialize() : new byte[0]);
//serialize MSP manager
byte[] mspmanager = (mspManager != null ? mspManager.serialize() : new byte[0]);
//concatenate bytes
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeUTF(sysChannel);
out.writeInt(sequence);
out.writeInt(orderers.length);
out.flush();
bos.flush();
for (int i = 0; i < orderers.length; i++) {
out.writeInt(orderers[i].intValue());
out.flush();
bos.flush();
}
out.writeInt(headers.length);
if (headers.length > 0) out.write(headers);
out.flush();
bos.flush();
out.writeInt(sysBytes.length);
if (sysBytes.length > 0) out.write(sysBytes);
out.flush();
bos.flush();
out.writeInt(blockcutter.length);
if (blockcutter.length > 0) out.write(blockcutter);
out.flush();
bos.flush();
out.writeInt(mspmanager.length);
if (mspmanager.length > 0) out.write(mspmanager);
out.flush();
bos.flush();
out.close();
bos.close();
return bos.toByteArray();
} catch (IOException ex) {
logger.error("Failed to fetch snapshot", ex);
}
return new byte[0];
}
@Override
public byte[][] appExecuteBatch(byte[][] commands, MessageContext[] msgCtxs, boolean fromConsensus) {
byte[][] replies = new byte[commands.length][];
for (int i = 0; i < commands.length; i++) {
if (msgCtxs != null && msgCtxs[i] != null) {
replies[i] = executeSingle(commands[i], msgCtxs[i], fromConsensus);
}
}
return replies;
}
private void waitforReplica() throws InterruptedException {
while (replica == null) {
replicaLock.lock();
replicaReady.await(1000, TimeUnit.MILLISECONDS);
replicaLock.lock();
}
}
private byte[] executeSingle(byte[] command, MessageContext msgCtx, boolean fromConsensus) {
//make sure system channel is created, since we cannot do it at start up due to not having a timestamp yet
//this is only done once
if (mspManager.getChanConfig(this.sysChannel) == null) {
MSPManager mspManager = this.mspManager.clone();
BlockCutter blockCutter = this.blockCutter.clone();
Map<String,Common.BlockHeader> lastBlockHeaders = new TreeMap<>();
lastBlockHeaders.putAll(this.lastBlockHeaders);
try {
newChannel(mspManager, blockCutter, lastBlockHeaders, this.sysChannel, this.sysGenesis, msgCtx.getTimestamp());
} catch (Exception ex) {
//TODO: handle error
logger.error("Failed to create new channel", ex);
return new byte[0];
}
this.mspManager = mspManager;
this.blockCutter = blockCutter;
this.lastBlockHeaders = lastBlockHeaders;
}
BlockCutter blockCutter = this.blockCutter.clone();
MSPManager mspManager = null;
Map<String,Common.BlockHeader> lastBlockHeaders = new TreeMap<>();
try {
if (receivers.contains(msgCtx.getSender())) {
BFTCommon.RequestTuple tuple = BFTCommon.deserializeSignedRequest(command);
if (tuple.id != msgCtx.getSender() || !BFTCommon.verifyFrontendSignature(msgCtx.getSender(),
replicaConf.getPublicKey(msgCtx.getSender()), tuple)) return new byte[0];
if (tuple.type.equals("GETSVIEW")) {
logger.info("A proxy is trying to fetch the most current view");
return new byte[0];
}
if (tuple.type.equals("SEQUENCE")) {
byte[][] reply = new byte[2][];
reply[0] = "SEQUENCE".getBytes();
reply[1] = ByteBuffer.allocate(4).putInt(this.sequence).array();
return BFTCommon.serializeContents(reply);
}
if (tuple.type.equals("TIMEOUT")) {
logger.info("Purging blockcutter for channel " + tuple.channelID);
byte[][] batch = blockCutter.cut(tuple.channelID);
if (batch.length > 0) {
mspManager = this.mspManager.clone();
lastBlockHeaders.putAll(this.lastBlockHeaders);
processEnvelopes(batch, blockCutter, mspManager, lastBlockHeaders, msgCtx, fromConsensus, tuple.channelID, false);
//if we are here, we can atomically update the replica state
this.mspManager = mspManager;
this.lastBlockHeaders = lastBlockHeaders;
}
this.blockCutter = blockCutter;
return new byte[0];
}
return new byte[0];
}
if (envelopeMeasurementStartTime == -1) {
envelopeMeasurementStartTime = System.currentTimeMillis();
}
countEnvelopes++;
if (countEnvelopes % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - envelopeMeasurementStartTime));
loggerThroughput.info("envelopes/second\t" + tp);
envelopeMeasurementStartTime = System.currentTimeMillis();
}
logger.debug("Envelopes received: " + countEnvelopes);
BFTCommon.RequestTuple tuple = BFTCommon.deserializeRequest(command);
boolean isConfig = tuple.type.equals("CONFIG");
logger.debug("Received envelope" + Arrays.toString(tuple.payload) + " for channel id " + tuple.channelID + (isConfig ? " (type config)" : " (type normal)"));
try { //filter malformed envelopes, if option is enabled
Common.Envelope.parseFrom(tuple.payload);
} catch (Exception e) {
if (filterMalformed) {
logger.info("Discarding malformed envelope");
return new byte[0];
}
}
List<byte[][]> batches = blockCutter.ordered(tuple.channelID, tuple.payload, isConfig);
if (batches.size() > 0) {
mspManager = this.mspManager.clone();
lastBlockHeaders.putAll(this.lastBlockHeaders);
for (int i = 0; i < batches.size(); i++) {
processEnvelopes(batches.get(i), blockCutter, mspManager, lastBlockHeaders, msgCtx, fromConsensus, tuple.channelID, isConfig);
}
//if we are here, we can atomically update the replica state
this.mspManager = mspManager;
this.lastBlockHeaders = lastBlockHeaders;
}
this.blockCutter = blockCutter;
} catch (Exception ex) {
//TODO: handle error
logger.error("Failed to process envelope", ex);
return new byte[0];
}
return "ACK".getBytes();
}
private void newChannel(MSPManager mspManager, BlockCutter blockCutter, Map<String,Common.BlockHeader> lastBlockHeaders, String channelID, Common.Block genesis, long timestamp) throws BFTCommon.BFTException {
if (channelID != null && genesis != null && lastBlockHeaders.get(channelID) == null) {
logger.info("Creating channel " + channelID);
long preferredMaxBytes = -1;
long maxMessageCount = -1;
try{
Configtx.ConfigEnvelope conf = BFTCommon.extractConfigEnvelope(genesis);
Configuration.BatchSize batchSize = BFTCommon.extractBachSize(conf.getConfig());
preferredMaxBytes = batchSize.getPreferredMaxBytes();
maxMessageCount = batchSize.getMaxMessageCount();
mspManager.newChannel(channelID, genesis.getHeader().getNumber(), conf, timestamp);
} catch (BFTCommon.BFTException ex) {
throw ex;
} catch (Exception ex) {
throw new BFTCommon.BFTException("Failed to update channel " + channelID + ": " + ex.getLocalizedMessage());
}
// if we are here, we will successfully atomically update the channel
if (preferredMaxBytes > -1 && maxMessageCount > -1) {
lastBlockHeaders.put(channelID, genesis.getHeader());
blockCutter.setBatchParms(channelID, preferredMaxBytes , maxMessageCount);
}
logger.info("New channel ID: " + channelID);
logger.info("Genesis header number: " + lastBlockHeaders.get(channelID).getNumber());
//logger.info("Genesis header previous hash: " + Hex.encodeHexString(lastBlockHeaders.get(channelID).getPreviousHash().toByteArray()));
logger.info("Genesis header data hash: " + Hex.encodeHexString(lastBlockHeaders.get(channelID).getDataHash().toByteArray()));
//logger.info("Genesis header ASN1 encoding: " + Arrays.toString(BFTCommon.encodeBlockHeaderASN1(lastBlockHeaders.get(channelID))));
}
}
private void updateChannel(MSPManager mspManager, BlockCutter blockCutter, String channel, long number, Configtx.ConfigEnvelope newConfEnv, Configtx.Config newConfig, long timestamp) throws BFTCommon.BFTException {
long preferredMaxBytes = -1;
long maxMessageCount = -1;
try {
logger.info("Updating state for channel " + channel);
Map<String,Configtx.ConfigGroup> groups = newConfig.getChannelGroup().getGroupsMap();
Configuration.BatchSize batchsize = Configuration.BatchSize.parseFrom(groups.get("Orderer").getValuesMap().get("BatchSize").getValue());
preferredMaxBytes = batchsize.getPreferredMaxBytes();
maxMessageCount = batchsize.getMaxMessageCount();
mspManager.updateChannel(channel, number, newConfEnv, newConfig, timestamp);
} catch (BFTCommon.BFTException ex) {
throw ex;
} catch (Exception ex) {
throw new BFTCommon.BFTException("Failed to update channel " + channel + ": " + ex.getLocalizedMessage());
}
// if we are here, we will successfully atomically update the channel
if (preferredMaxBytes > -1 && maxMessageCount > -1) {
blockCutter.setBatchParms(channel, preferredMaxBytes , maxMessageCount);
}
logger.info("Latest block with config update for "+ channel +": #" + number);
}
private void processEnvelopes(byte[][] batch, BlockCutter blockCutter, MSPManager mspManager, Map<String,Common.BlockHeader> lastBlockHeaders, MessageContext msgCtx, boolean fromConsensus, String channel, boolean isConfig) throws BFTCommon.BFTException {
Common.Block block = null;
try {
block = BFTCommon.createNextBlock(lastBlockHeaders.get(channel).getNumber() + 1, crypto.hash(BFTCommon.encodeBlockHeaderASN1(lastBlockHeaders.get(channel))), batch);
if (isConfig) {
Common.Envelope env = Common.Envelope.parseFrom(block.getData().getData(0));
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Configtx.ConfigUpdateEnvelope confEnv = Configtx.ConfigUpdateEnvelope.parseFrom(payload.getData());
Configtx.ConfigUpdate confUpdate = Configtx.ConfigUpdate.parseFrom(confEnv.getConfigUpdate());
boolean isConfigUpdate = confUpdate.getChannelId().equals(channel);
if (isConfigUpdate) {
mspManager.verifyPolicies(channel, false, confUpdate.getReadSet(), confUpdate.getWriteSet(), confEnv, msgCtx.getTimestamp());
if (envValidation) mspManager.validateEnvelope(env, channel, msgCtx.getTimestamp(), timeWindow);
logger.info("Reconfiguration envelope for channel "+ channel +" is valid, generating configuration with readset and writeset");
Configtx.Config newConfig = mspManager.generateNextConfig(channel, confUpdate.getReadSet(), confUpdate.getWriteSet());
Configtx.ConfigEnvelope newConfEnv = BFTCommon.makeConfigEnvelope(newConfig, env);
//The fabric codebase inserts the lastupdate structure into a signed envelope. I cannot do this here because the signatures
//are different for each replica, thus producing different blocks. Even if I modified the frontend to be aware of this corner
//case just like it is done for block signatures, envelopes are supposed to contain only one signature rather than a set of them.
//My solution was to simply not sign the envelope. At least until Fabric v1.2, the codebase seems to accept unsigned envelopes.
Common.Envelope newEnvelope = BFTCommon.makeUnsignedEnvelope(newConfEnv.toByteString(), ByteString.EMPTY, Common.HeaderType.CONFIG, 0, channel, 0,
msgCtx.getTimestamp());
block = BFTCommon.createNextBlock(block.getHeader().getNumber(), block.getHeader().getPreviousHash().toByteArray(), new byte[][] { newEnvelope.toByteArray() });
updateChannel(mspManager, blockCutter, channel, block.getHeader().getNumber(), newConfEnv, newConfig, msgCtx.getTimestamp());
}
else if (!isConfigUpdate && channel.equals(sysChannel)) {
mspManager.verifyPolicies(channel, true, confUpdate.getReadSet(), confUpdate.getWriteSet(), confEnv, msgCtx.getTimestamp());
// We do not perform envelope validation for the envelope that is going to be appended to the system channel, since it is created by
// its own organization/msp. The fabric codebase does re-apply the filters and hence authenticates the envelope to perform a sanity
// check, but the the prime reason for re-applying the filters is to check that the size of the envelope is still within the size
// limit. Furthermore, since this ordering service cannot sign the envelope, it should not validate it either (see comments below
// regarding why the envelope is not signed)
//if (envValidation) mspManager.validateEnvelope(env, channel, msgCtx.getTimestamp(), timeWindow);
logger.info("Orderer transaction envelope for system channel is valid, generating genesis with readset and writeset for channel "+ confUpdate.getChannelId());
Configtx.Config newConfig = mspManager.newChannelConfig(channel,confUpdate.getReadSet(),confUpdate.getWriteSet());
Configtx.ConfigEnvelope newConfEnv = BFTCommon.makeConfigEnvelope(newConfig, env);
//The fabric codebase inserts the lastupdate structure into a signed envelope. We cannot do this here because the signatures
//are different for each replica, thus producing different blocks. Even if I modified the frontend to be aware of this corner
//case just like it is done for block signatures, envelopes are supposed to contain only one signature rather than a set of them.
//My solution was to simply not sign the envelope. At least until Fabric v1.2, the codebase seems to accept unsigned envelopes.
Common.Envelope envelopeClone = BFTCommon.makeUnsignedEnvelope(newConfEnv.toByteString(), ByteString.EMPTY, Common.HeaderType.CONFIG, 0, confUpdate.getChannelId(), 0,
msgCtx.getTimestamp());
Common.Block genesis = BFTCommon.createNextBlock(0, null, new byte[][]{envelopeClone.toByteArray()});
envelopeClone = BFTCommon.makeUnsignedEnvelope(envelopeClone.toByteString(), ByteString.EMPTY, Common.HeaderType.ORDERER_TRANSACTION, 0, channel, 0,
msgCtx.getTimestamp());
block = BFTCommon.createNextBlock(block.getHeader().getNumber(), block.getHeader().getPreviousHash().toByteArray(), new byte[][] { envelopeClone.toByteArray() });
newChannel(mspManager, blockCutter, lastBlockHeaders, confUpdate.getChannelId(), genesis, msgCtx.getTimestamp());
} else {
String msg = "Envelope contained channel creation request, but was submitted to a non-system channel (" + channel + ")";
logger.info(msg);
throw new BFTCommon.BFTException(msg);
}
}
//optimization to parellise signatures and sending
if (fromConsensus) { //if this is from the state transfer, there is no point in signing and sending yet again
if (sigIndex % blocksPerThread == 0) {
if (currentSST != null) {
currentSST.input(null, null, -1, null, false, null);
}
currentSST = this.queue.take(); // fetch the first SSThread that is idle
}
currentSST.input(block, msgCtx, this.sequence, channel, isConfig, mspManager);
sigIndex++;
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | true |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/BFTProxy.java | src/bft/BFTProxy.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft;
import bft.util.ProxyReplyListener;
import bft.util.BFTCommon;
import bft.util.ECDSAKeyLoader;
import bftsmart.communication.client.ReplyListener;
import bftsmart.tom.AsynchServiceProxy;
import bftsmart.tom.RequestContext;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.KeyLoader;
import com.etsy.net.JUDS;
import com.etsy.net.UnixDomainSocket;
import com.etsy.net.UnixDomainSocketServer;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.common.Configtx;
import org.hyperledger.fabric.protos.orderer.Configuration;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.helper.Config;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
/**
*
* @author joao
*/
public class BFTProxy {
private static UnixDomainSocketServer recvServer = null;
private static ServerSocket sendServer = null;
private static DataInputStream is;
private static UnixDomainSocket recvSocket = null;
private static Socket sendSocket = null;
private static ExecutorService executor = null;
private static Map<String, DataOutputStream> outputs;
private static Map<String, Timer> timers;
private static Map<String, Long> BatchTimeout;
private static int frontendID;
private static int nextID;
private static ProxyReplyListener sysProxy;
private static Logger logger;
private static String configDir;
private static CryptoPrimitives crypto;
//measurements
private static final int interval = 10000;
private static long envelopeMeasurementStartTime = -1;
private static final long blockMeasurementStartTime = -1;
private static final long sigsMeasurementStartTime = -1;
private static int countEnvelopes = 0;
private static final int countBlocks = 0;
private static final int countSigs = 0;
public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
if(args.length < 3) {
System.out.println("Use: java bft.BFTProxy <proxy id> <pool size> <send port>");
System.exit(-1);
}
int pool = Integer.parseInt(args[1]);
int sendPort = Integer.parseInt(args[2]);
Path proxy_ready = FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"), "hlf-proxy-"+sendPort+".ready");
Files.deleteIfExists(proxy_ready);
configDir = BFTCommon.getBFTSMaRtConfigDir("FRONTEND_CONFIG_DIR");
if (System.getProperty("logback.configurationFile") == null)
System.setProperty("logback.configurationFile", configDir + "logback.xml");
Security.addProvider(new BouncyCastleProvider());
BFTProxy.logger = LoggerFactory.getLogger(BFTProxy.class);
frontendID = Integer.parseInt(args[0]);
nextID = frontendID + 1;
crypto = new CryptoPrimitives();
crypto.init();
BFTCommon.init(crypto);
ECDSAKeyLoader loader = new ECDSAKeyLoader(frontendID, configDir, crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
sysProxy = new ProxyReplyListener(frontendID, configDir, loader, Security.getProvider("BC"));
try {
logger.info("Creating UNIX socket...");
Path socket_file = FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"), "hlf-pool-"+sendPort+".sock");
Files.deleteIfExists(socket_file);
recvServer = new UnixDomainSocketServer(socket_file.toString(), JUDS.SOCK_STREAM, pool);
sendServer = new ServerSocket(sendPort);
FileUtils.touch(proxy_ready.toFile()); //Indicate the Go component that the java component is ready
logger.info("Waiting for local connections and parameters...");
recvSocket = recvServer.accept();
is = new DataInputStream(recvSocket.getInputStream());
executor = Executors.newFixedThreadPool(pool);
for (int i = 0; i < pool; i++) {
UnixDomainSocket socket = recvServer.accept();
executor.execute(new ReceiverThread(socket, nextID));
nextID++;
}
outputs = new TreeMap<>();
timers = new TreeMap<>();
BatchTimeout = new TreeMap<>();
// request latest reply sequence from the ordering nodes
sysProxy.invokeAsynchRequest(BFTCommon.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getPrivateKey(), frontendID, "SEQUENCE", "", new byte[]{}), null, TOMMessageType.ORDERED_REQUEST);
new SenderThread().start();
logger.info("Java component is ready");
while (true) { // wait for the creation of new channels
sendSocket = sendServer.accept();
DataOutputStream os = new DataOutputStream(sendSocket.getOutputStream());
String channel = readString(is);
//byte[] bytes = readBytes(is);
outputs.put(channel, os);
BatchTimeout.put(channel, readLong(is));
logger.info("Read BatchTimeout: " + BatchTimeout.get(channel));
//sysProxy.invokeAsynchRequest(BFTUtil.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getRSAPrivateKey(), "NEWCHANNEL", channel, bytes), null, TOMMessageType.ORDERED_REQUEST);
Timer timer = new Timer();
timer.schedule(new BatchTimeout(channel), (BatchTimeout.get(channel) / 1000000));
timers.put(channel, timer);
logger.info("Setting up system for new channel '" + channel + "'");
nextID++;
}
} catch (IOException e) {
logger.error("Failed to launch frontend", e);
System.exit(1);
}
}
private static String readString(DataInputStream is) throws IOException {
byte[] bytes = readBytes(is);
return new String(bytes);
}
private static boolean readBoolean(DataInputStream is) throws IOException {
byte[] bytes = readBytes(is);
return bytes[0] == 1;
}
private static byte[] readBytes(DataInputStream is) throws IOException {
long size = readLong(is);
logger.debug("Read number of bytes: " + size);
byte[] bytes = new byte[(int) size];
is.read(bytes);
logger.debug("Read all bytes!");
return bytes;
}
private static long readLong(DataInputStream is) throws IOException {
byte[] buffer = new byte[8];
is.read(buffer);
//This is for little endian
//long value = 0;
//for (int i = 0; i < by.length; i++)
//{
// value += ((long) by[i] & 0xffL) << (8 * i);
//}
//This is for big endian
long value = 0;
for (int i = 0; i < buffer.length; i++) {
value = (value << 8) + (buffer[i] & 0xff);
}
return value;
}
private static long readInt() throws IOException {
byte[] buffer = new byte[4];
long value = 0;
is.read(buffer);
for (int i = 0; i < buffer.length; i++) {
value = (value << 8) + (buffer[i] & 0xff);
}
return value;
}
private static synchronized void resetTimer(String channel) {
if (timers.get(channel) != null) timers.get(channel).cancel();
Timer timer = new Timer();
timer.schedule(new BatchTimeout(channel), (BatchTimeout.get(channel) / 1000000));
timers.put(channel, timer);
}
private static class ReceiverThread extends Thread {
private int id;
private UnixDomainSocket recv;
private DataInputStream input;
private AsynchServiceProxy out;
public ReceiverThread(UnixDomainSocket recv, int id) throws IOException {
this.id = id;
this.recv = recv;
this.input = new DataInputStream(this.recv.getInputStream());
this.out = new AsynchServiceProxy(this.id, configDir, new KeyLoader() {
@Override
public PublicKey loadPublicKey(int i) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return null;
}
@Override
public PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return null;
}
@Override
public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return null;
}
@Override
public String getSignatureAlgorithm() {
return null;
}
}, Security.getProvider("BC"));
}
public void run() {
String channelID;
boolean isConfig;
byte[] env;
while (true) {
try {
channelID = readString(this.input);
isConfig = readBoolean(this.input);
env = readBytes(this.input);
resetTimer(channelID);
logger.debug("Received envelope" + Arrays.toString(env) + " for channel id " + channelID + (isConfig ? " (type config)" : " (type normal)"));
this.out.invokeAsynchRequest(BFTCommon.serializeRequest(this.id, (isConfig ? "CONFIG" : "REGULAR"), channelID, env), new ReplyListener(){
private int replies = 0;
@Override
public void reset() {
replies = 0;
}
@Override
public void replyReceived(RequestContext rc, TOMMessage tomm) {
if (Arrays.equals(tomm.getContent(), "ACK".getBytes())) replies++;
double q = Math.ceil((double) (out.getViewManager().getCurrentViewN() + out.getViewManager().getCurrentViewF() + 1) / 2.0);
if (replies >= q) {
out.cleanAsynchRequest(rc.getOperationId());
}
}
}, TOMMessageType.ORDERED_REQUEST);
} catch (IOException ex) {
logger.error("Error while receiving envelope from Go component", ex);
continue;
}
if (envelopeMeasurementStartTime == -1) {
envelopeMeasurementStartTime = System.currentTimeMillis();
}
countEnvelopes++;
if (countEnvelopes % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - envelopeMeasurementStartTime));
logger.info("Throughput = " + tp + " envelopes/sec");
envelopeMeasurementStartTime = System.currentTimeMillis();
}
//byte[] reply = proxy.invokeOrdered(bytes);
//by = new byte[8];
//by[0] = (byte) ((byte) value>>56);
//by[1] = (byte) ((byte) value>>48);
//by[2] = (byte) ((byte) value>>40);
//by[3] = (byte) ((byte) value>>32);
//by[4] = (byte) ((byte) value>>24);
//by[5] = (byte) ((byte) value>>16);
//by[6] = (byte) ((byte) value>>8);
//by[7] = (byte) ((byte) value>>0);
}
}
}
private static class SenderThread extends Thread {
public void run() {
while (true) {
Map.Entry<String,Common.Block> reply = sysProxy.getNext();
logger.info("Received block # " + reply.getValue().getHeader().getNumber());
if (reply != null) {
try {
String[] params = reply.getKey().split("\\:");
boolean isConfig = Boolean.parseBoolean(params[1]);
if (isConfig) { //if config block, make sure to update the timeout in case it was changed
Common.Envelope env = Common.Envelope.parseFrom(reply.getValue().getData().getData(0));
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.ChannelHeader chanHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
if (chanHeader.getType() == Common.HeaderType.CONFIG_VALUE) {
Configtx.ConfigEnvelope confEnv = Configtx.ConfigEnvelope.parseFrom(payload.getData());
Map<String,Configtx.ConfigGroup> groups = confEnv.getConfig().getChannelGroup().getGroupsMap();
Configuration.BatchTimeout timeout = Configuration.BatchTimeout.parseFrom(groups.get("Orderer").getValuesMap().get("BatchTimeout").getValue());
Duration duration = BFTCommon.parseDuration(timeout.getTimeout());
BatchTimeout.put(params[0], duration.toNanos());
}
}
byte[] bytes = reply.getValue().toByteArray();
DataOutputStream os = outputs.get(params[0]);
os.writeLong(bytes.length);
os.write(bytes);
os.writeLong(1);
os.write(isConfig ? (byte) 1 : (byte) 0);
} catch (IOException ex) {
logger.error("Error while sending block to Go component", ex);
}
}
}
}
}
private static class BatchTimeout extends TimerTask {
String channel;
BatchTimeout(String channel) {
this.channel = channel;
}
@Override
public void run() {
try {
int reqId = sysProxy.invokeAsynchRequest(BFTCommon.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getPrivateKey(), frontendID, "TIMEOUT", this.channel,new byte[0]), null, TOMMessageType.ORDERED_REQUEST);
sysProxy.cleanAsynchRequest(reqId);
Timer timer = new Timer();
timer.schedule(new BatchTimeout(this.channel), (BatchTimeout.get(channel) / 1000000));
timers.put(this.channel, timer);
} catch (IOException ex) {
logger.error("Failed to send envelope to nodes", ex);
}
}
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/OUIdentifier.java | src/bft/util/OUIdentifier.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import java.io.Serializable;
import org.apache.commons.codec.binary.Hex;
/**
*
* @author joao
*/
class OUIdentifier implements Serializable {
// CertifiersIdentifier is the hash of certificates chain of trust
// related to this organizational unit
byte[] certifiersIdentifier;
// OrganizationUnitIdentifier defines the organizational unit under the
// MSP identified with MSPIdentifier
String organizationalUnitIdentifier;
OUIdentifier (byte[] certifiersIdentifier, String organizationalUnitIdentifier) {
this.certifiersIdentifier = certifiersIdentifier;
this.organizationalUnitIdentifier = organizationalUnitIdentifier;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.certifiersIdentifier.hashCode();
hash = 31 * hash + this.organizationalUnitIdentifier.hashCode();
return hash;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
OUIdentifier i = (OUIdentifier) o;
return this.certifiersIdentifier.equals(i.certifiersIdentifier) &&
this.organizationalUnitIdentifier.equals(i.organizationalUnitIdentifier);
}
@Override
public String toString(){
return "["+ Hex.encodeHexString(this.certifiersIdentifier) + ":" + this.organizationalUnitIdentifier+"]";
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/MSPManager.java | src/bft/util/MSPManager.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import bft.util.BFTCommon.BFTException;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.PKIXCertPathBuilderResult;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.common.Configtx;
import org.hyperledger.fabric.protos.common.Configuration;
import org.hyperledger.fabric.protos.common.MspPrincipal;
import org.hyperledger.fabric.protos.common.Policies;
import org.hyperledger.fabric.protos.msp.Identities;
import org.hyperledger.fabric.protos.msp.MspConfig;
import org.hyperledger.fabric.sdk.exception.CryptoException;
/**
*
* @author joao
*/
public class MSPManager {
private static Logger logger;
//internal state
private String mspid;
private String sysChannel;
//fundamental for the state transfer protocol
private Map<String, Configtx.ConfigEnvelope> chanConfigs = new TreeMap<>();
private Map<String, Long> lastConfigs = new TreeMap<>();
// these two are fundamental because requie the state machine timestamp everytime they are updated
private Map<String, OUIdentifier> clientOUs = new TreeMap<>();
private Map<String, OUIdentifier> peerOUs = new TreeMap<>();
//not necessary for state transfer, but useful for channel management and authentication
private Map<String,MspConfig.FabricMSPConfig> MSPs = new TreeMap<>();
private Map<String,Set<String>> chanMSPs = new TreeMap<>();
private Map<String,Policy> chanWriters = new TreeMap<>();
private Map<String,Set<X509Certificate>> rootCerts = new TreeMap<>();
private Map<String,Set<X509Certificate>> intermediateCerts = new TreeMap<>();
private Map<String,Set<X509Certificate>> adminCerts = new TreeMap<>();
private Map<String,Set<X509Certificate>> revokedCerts = new TreeMap<>();
private Map<String,Map<X509Certificate,List<X509Certificate>>> validatedCerts = new TreeMap<>();
//constants related to channel reconfiguration
private static final String rootGroupKey = "Channel";
private static final String groupPrefix = "[Group] ";
private static final String valuePrefix = "[Value] ";
private static final String policyPrefix = "[Policy] ";
private static final String pathSeparator = "/";
private static final String consortiumKey = "Consortium";
private static final String consortiumsGroupKey = "Consortiums";
private static final String channelCreationPolicyKey = "ChannelCreationPolicy";
private static final String applicationGroupKey = "Application";
private static final String ordererGroupKey = "Orderer";
private static final String adminsPolicyKey = "Admins";
// Hacky fix constants, used in recurseConfigMap
private static final String hackyFixOrdererCapabilities = "[Value] /Channel/Orderer/Capabilities";
private static final String hackyFixNewModPolicy = "Admins";
private class ConfigItem {
Configtx.ConfigGroup group;
Configtx.ConfigPolicy policy;
Configtx.ConfigValue value = null;
String key = null;
String[] path = null;
ConfigItem(Configtx.ConfigGroup group, String key, String[] path) {
this.group = group;
this.key = key;
this.path = path;
}
ConfigItem(Configtx.ConfigPolicy policy, String key, String[] path) {
this.policy = policy;
this.key = key;
this.path = path;
}
ConfigItem(Configtx.ConfigValue value, String key, String[] path) {
this.value = value;
this.key = key;
this.path = path;
}
long getVersion() {
if (this.group != null) return group.getVersion();
else if (this.policy != null) return policy.getVersion();
else return this.value.getVersion();
}
String getModPolicy() {
if (this.group != null) return group.getModPolicy();
else if (this.policy != null) return policy.getModPolicy();
else return this.value.getModPolicy();
}
}
public class SignedData {
byte[] data;
byte[] identity;
byte[] signature;
SignedData(byte[] data, byte[] identity, byte[] signature) {
this.data = data;
this.identity = identity;
this.signature = signature;
}
}
public abstract class Policy {
protected abstract BFTCommon.BFTException evaluate(SignedData[] signedData, boolean[] used, String channel, long timestamp);
public abstract String getPath();
public void evaluate(SignedData[] signedData, String channel, long timestamp) throws BFTCommon.BFTException {
logger.info("Evaluating policy " + getPath());
boolean[] used = new boolean[signedData.length];
Arrays.fill(used, Boolean.FALSE);
BFTException ex = evaluate(deduplicate(channel, signedData), used, channel, timestamp);
if (ex != null) {
logger.info("Evaluation of policy " + getPath() + " failed: " + ex.getLocalizedMessage());
throw ex;
}
logger.info("Evaluation of policy " + getPath() + " succeeded");
}
private SignedData[] deduplicate(String channel, SignedData[] signedData) {
Set<String> ids = new HashSet<>();
LinkedList<SignedData> deduplicated = new LinkedList<>();
for (SignedData sd : signedData) {
Identity id = null;
try {
id = deserializeIdentity(channel, sd.identity);
} catch (Exception ex) {
logger.debug("Failed to deserialize principal during deduplication: " + ex.getMessage());
continue;
}
String key = (id.id+id.msp);
if (ids.contains(key)) {
logger.debug("De-duplicating identity " + id + " in signature set");
} else {
deduplicated.add(sd);
ids.add(key);
}
}
SignedData[] result = new SignedData[deduplicated.size()];
deduplicated.toArray(result);
return result;
}
}
class Identity {
String msp;
String id;
String channel;
X509Certificate certificate;
byte[] serializedCert;
Identity(String msp, String id,String channel, X509Certificate certificate, byte[] serializedCert) {
this.msp = msp;
this.id = id;
this.channel = channel;
this.certificate = certificate;
this.serializedCert = serializedCert;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.msp.hashCode();
hash = 31 * hash + this.id.hashCode();
hash = 31 * hash + this.channel.hashCode();
return hash;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
Identity i = (Identity) o;
return this.id.equals(i.id) && this.msp.equals(i.msp) &&
this.channel.equals(i.channel) && Arrays.equals(this.serializedCert, i.serializedCert);
}
@Override
public String toString(){
return "["+this.id + ":" + this.msp+"]";
}
public boolean verify(byte[] data, byte[] signature) throws CertificateEncodingException, CryptoException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, BFTException, KeyStoreException {
//Fabric v1.1 implementation fetches the signature hash family and supplies it to the hashing function, but the
//implemetation of the hashing function ignores that option when it type to compute the hash. Nonetheless, X509
//certificates have information about the signature algorithm, hence we use those.
//String sigHashFamily = MSPs.get(this.msp).getCryptoConfig().getSignatureHashFamily();
//String defaultFamily = crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM);
return BFTCommon.verifySignature(this.certificate, data, signature);
}
private List<X509Certificate> validate(long timestamp) throws BFTException {
logger.debug("Verifying certificate chain for identity "+ this);
List<X509Certificate> certPath = verifyCertificate(this.certificate,this.msp,timestamp);
if (MSPs.get(this.msp).getFabricNodeOus().getEnable()) {
logger.debug("Fetching OU identifiers for identity " + this);
OUIdentifier[] OUIDs = getOrganizationalUnits(certPath);
logger.debug("Obtained the following OU identifiers for identity " +this+": " + Arrays.deepToString(OUIDs));
int counter = 0;
for (OUIdentifier OU : OUIDs) {
OUIdentifier nodeOU = null;
if (OU.organizationalUnitIdentifier.equals(clientOUs.get(this.msp).organizationalUnitIdentifier)) {
nodeOU = clientOUs.get(this.msp);
}
else if (OU.organizationalUnitIdentifier.equals(peerOUs.get(this.msp).organizationalUnitIdentifier)) {
nodeOU = peerOUs.get(this.msp);
}
else {
continue;
}
if (nodeOU.certifiersIdentifier.length != 0 && !Arrays.equals(nodeOU.certifiersIdentifier, OU.certifiersIdentifier)) {
throw new BFTCommon.BFTException("CID does not match: OUs: " + Arrays.deepToString(OUIDs) +", MSP: " + this.msp);
}
counter++;
if (counter > 1) {
break;
}
}
if (counter != 1) {
String msg = null;
if (counter > 0) msg = "Identity " + this + " must be a client, a peer or an orderer identity to be valid, not a combination of them.";
else msg = "Identity " + this + " does not have a OU matching the identifier for either a client or a peer of the MSP.";
throw new BFTCommon.BFTException(msg + " OUs: " + Arrays.deepToString(OUIDs) +", MSP: " + this.msp);
}
}
return certPath;
}
private void parseRoleMember(MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
logger.debug("Parsing MSP principal "+ principal + " as role member");
validate(timestamp);
}
private void parseRoleAdmin(MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
logger.debug("Parsing MSP principal "+ principal + " as role admin");
if (adminCerts.get(this.msp).contains(this.certificate)) {
validate(timestamp);
} else throw new BFTCommon.BFTException("Identity " + this + " is not an admin");
}
private void parseRolePeer(MspPrincipal.MSPPrincipal principal, MspPrincipal.MSPRole mspRole, long timestamp) throws BFTException {
logger.debug("Parsing MSP principal "+ principal + " as role peer");
List<X509Certificate> certPath = validate(timestamp);
if (MSPs.get(this.msp).getFabricNodeOus().getEnable()) {
String nodeOUValue = null;
switch (mspRole.getRole()) {
case CLIENT:
nodeOUValue = clientOUs.get(this.msp).organizationalUnitIdentifier;
break;
case PEER:
nodeOUValue = peerOUs.get(this.msp).organizationalUnitIdentifier;
break;
default:
throw new BFTCommon.BFTException("Invalid MSPRoleType. It must be CLIENT, PEER or ORDERER");
}
OUIdentifier[] OUs = getOrganizationalUnits(certPath);
for (OUIdentifier OU : OUs) {
if (OU.organizationalUnitIdentifier.equals(nodeOUValue)) return;
}
throw new BFTCommon.BFTException("Identity "+ this +" does not contain OU " + nodeOUValue);
}
}
private void parseIdentity(String channel, MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
logger.debug("Parsing MSP principal "+ principal + " as identity");
Identity identPrincipal = null;
try {
identPrincipal = deserializeIdentity(channel, principal.getPrincipal().toByteArray());
} catch (Exception ex) {
throw new BFTCommon.BFTException("Unable to deserialize principal's identity: " + ex.getMessage());
}
if (Arrays.equals(this.serializedCert, identPrincipal.serializedCert)) {
identPrincipal.validate(timestamp);
} else throw new BFTCommon.BFTException("Principal's identity does not match with identity " + this);
}
private void parseOU(MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
logger.debug("Parsing MSP principal "+ principal + " as OU");
MspPrincipal.OrganizationUnit OU = null;
try {
OU = MspPrincipal.OrganizationUnit.parseFrom(principal.getPrincipal());
} catch (InvalidProtocolBufferException ex) {
throw new BFTCommon.BFTException("Could not parse OrganizationUnit from principal " + principal);
}
if (!OU.getMspIdentifier().equals(this.msp))
throw new BFTCommon.BFTException("Identity " + this + "is a member of a different MSP (expected " + this.msp + ", got " + OU.getMspIdentifier());
List<X509Certificate> certPath = validate(timestamp);
OUIdentifier[] OUs = getOrganizationalUnits(certPath);
for (OUIdentifier ou : OUs) {
if (ou.organizationalUnitIdentifier.equals(OU.getOrganizationalUnitIdentifier()) &&
Arrays.equals(ou.certifiersIdentifier, OU.getCertifiersIdentifier().toByteArray())) {
return;
}
}
throw new BFTCommon.BFTException("The identities do not match");
}
void satisfiesPrincipal(MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
MspPrincipal.MSPPrincipal[] principals = collectPrincipals(principal);
for (MspPrincipal.MSPPrincipal p : principals) {
satisfiesPrincipalInternal(p, timestamp);
}
}
private MspPrincipal.MSPPrincipal[] collectPrincipals(MspPrincipal.MSPPrincipal principal) throws BFTException {
switch(principal.getPrincipalClassification()) {
case COMBINED:
try {
MspPrincipal.CombinedPrincipal principals = MspPrincipal.CombinedPrincipal.parseFrom(principal.getPrincipal());
if (principals.getPrincipalsCount() == 0) {
throw new BFTCommon.BFTException("No principals in CombinedPrincipal");
}
LinkedList principalsSlice = new LinkedList();
for (MspPrincipal.MSPPrincipal cp : principals.getPrincipalsList()) {
MspPrincipal.MSPPrincipal[] internalSlice = collectPrincipals(cp);
principalsSlice.addAll(Arrays.asList(internalSlice));
}
MspPrincipal.MSPPrincipal[] result = new MspPrincipal.MSPPrincipal[principalsSlice.size()];
principalsSlice.toArray(result);
return result;
} catch (InvalidProtocolBufferException ex) {
throw new BFTCommon.BFTException("Unable to parse principal: " + ex.getMessage());
}
default:
return new MspPrincipal.MSPPrincipal[] { principal };
}
}
private void satisfiesPrincipalInternal(MspPrincipal.MSPPrincipal principal, long timestamp) throws BFTException {
switch (principal.getPrincipalClassification()){
case COMBINED:
throw new BFTCommon.BFTException("SatisfiesPrincipalInternal can not be called with a CombinedPrincipal");
case ANONYMITY:
try {
MspPrincipal.MSPIdentityAnonymity anon = MspPrincipal.MSPIdentityAnonymity.parseFrom(principal.getPrincipal());
switch (anon.getAnonymityType()) {
case ANONYMOUS:
throw new BFTCommon.BFTException("Principal is anonymous, but X.509 MSP does not support anonymous identities");
case NOMINAL:
//Fabric v1.2 performs no validation in this case, so neither will we
break;
default:
throw new BFTCommon.BFTException("Unknown principal anonymity type: " + anon.getAnonymityType());
}
} catch (InvalidProtocolBufferException ex) {
throw new BFTCommon.BFTException("Unable to parse principal: " + ex.getMessage());
}
break;
case ROLE:
MspPrincipal.MSPRole mspRole = null;
try {
mspRole = MspPrincipal.MSPRole.parseFrom(principal.getPrincipal());
} catch (InvalidProtocolBufferException ex) {
throw new BFTCommon.BFTException("Unable to parse principal: " + ex.getMessage());
}
logger.debug("Checking identity MSP agaisnt principal MSP (expected "+ this.msp +", got "+ mspRole.getMspIdentifier() +")");
if (!mspRole.getMspIdentifier().equals(this.msp))
throw new BFTCommon.BFTException("Identity is a member of a different MSP (expected " + this.msp + ", got " + mspRole.getMspIdentifier());
switch (mspRole.getRole()){
case MEMBER:
parseRoleMember(principal, timestamp);
break;
case ADMIN:
parseRoleAdmin(principal, timestamp);
break;
case CLIENT: //same verifications for both cases
case PEER:
parseRolePeer(principal, mspRole, timestamp);
break;
default:
throw new BFTCommon.BFTException("Invalid MSP role type: "+ mspRole.getRole());
}
break;
case IDENTITY:
parseIdentity(this.channel, principal, timestamp);
break;
case ORGANIZATION_UNIT:
parseOU(principal, timestamp);
break;
default:
throw new BFTCommon.BFTException("Invalid principal type: "+ principal.getPrincipalClassification());
}
}
private OUIdentifier[] getOrganizationalUnits(List<X509Certificate> certPath) throws BFTException {
byte[] cid = BFTCommon.getCertificationChainIdentifierFromChain(
MSPs.get(this.msp).getCryptoConfig().getIdentityIdentifierHashFunction(), certPath);
String[] OUs = BFTCommon.extractOUsFronCertificate(this.certificate);
OUIdentifier[] result = new OUIdentifier[OUs.length];
for (int i = 0; i < OUs.length; i++) {
result[i] = new OUIdentifier(cid, OUs[i]);
}
return result;
}
}
private MSPManager() {
}
private MSPManager(String mspid, String sysChannel) throws NoSuchAlgorithmException, NoSuchProviderException {
this.mspid = mspid;
this.sysChannel = sysChannel;
logger = LoggerFactory.getLogger(MSPManager.class);
}
public static MSPManager getInstance(String mspid, String sysChannel) throws NoSuchAlgorithmException, NoSuchProviderException {
return new MSPManager(mspid, sysChannel);
}
public Map<String, Configtx.ConfigEnvelope> getChanConfigs() {
return chanConfigs;
}
public Configtx.ConfigEnvelope getChanConfig(String channel) {
return chanConfigs.get(channel);
}
public Map<String, Long> getLastConfigs() {
return lastConfigs;
}
public Long getLastConfig(String channel) {
return lastConfigs.get(channel);
}
public byte[] serialize() throws IOException {
//serialize channel configs
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutput o = new ObjectOutputStream(b);
o.writeObject(chanConfigs);
o.flush();
byte[] chanConfs = b.toByteArray();
b.close();
o.close();
//serialize channel last configs
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(lastConfigs);
o.flush();
byte[] lastConfs = b.toByteArray();
b.close();
o.close();
//serialize clients IO identifiers
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(clientOUs);
o.flush();
byte[] cOUs = b.toByteArray();
b.close();
o.close();
//serialize peers IO identifiers
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(peerOUs);
o.flush();
byte[] pOUs = b.toByteArray();
b.close();
o.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(chanConfs.length);
out.write(chanConfs);
out.flush();
bos.flush();
out.writeInt(lastConfs.length);
out.write(lastConfs);
out.flush();
bos.flush();
out.writeInt(cOUs.length);
out.write(cOUs);
out.flush();
bos.flush();
out.writeInt(pOUs.length);
out.write(pOUs);
out.flush();
bos.flush();
out.close();
bos.close();
return bos.toByteArray();
}
public static MSPManager deserialize(String mspid, String sysChannel, byte[] bytes) throws CertificateException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, BFTException {
MSPManager instance = getInstance(mspid, sysChannel);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bis);
byte[] chanConfs = new byte[0];
int n = in.readInt();
if (n > 0) {
chanConfs = new byte[n];
in.read(chanConfs);
}
byte[] lastConfs = new byte[0];
n = in.readInt();
if (n > 0) {
lastConfs = new byte[n];
in.read(lastConfs);
}
byte[] cOUs = new byte[0];
n = in.readInt();
if (n > 0) {
cOUs = new byte[n];
in.read(cOUs);
}
byte[] pOUs = new byte[0];
n = in.readInt();
if (n > 0) {
pOUs = new byte[n];
in.read(pOUs);
}
in.close();
bis.close();
ByteArrayInputStream b = new ByteArrayInputStream(chanConfs);
ObjectInput i = null;
i = new ObjectInputStream(b);
instance.chanConfigs = (Map<String,Configtx.ConfigEnvelope>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(lastConfs);
i = new ObjectInputStream(b);
instance.lastConfigs = (Map<String,Long>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(cOUs);
i = new ObjectInputStream(b);
instance.clientOUs = (Map<String,OUIdentifier>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(pOUs);
i = new ObjectInputStream(b);
instance.peerOUs = (Map<String,OUIdentifier>) i.readObject();
i.close();
b.close();
instance.setup();
return instance;
}
private void setup() throws CertificateException, IOException, BFTException {
this.MSPs = new TreeMap<>();
this.chanWriters = new TreeMap<>();
this.adminCerts = new TreeMap<>();
this.revokedCerts = new TreeMap<>();
this.intermediateCerts = new TreeMap<>();
this.rootCerts = new TreeMap<>();
this.validatedCerts = new TreeMap<>();
Set<String> chans = this.chanConfigs.keySet();
for (String chan : chans) {
Configtx.ConfigEnvelope conf = this.chanConfigs.get(chan);
Set<MspConfig.FabricMSPConfig> msps = extractMSPs(conf.getConfig(), chan.equals(sysChannel));
Set<String> mspIDs = new TreeSet<>();
for (MspConfig.FabricMSPConfig msp : msps) {
mspIDs.add(msp.getName());
MSPs.put(msp.getName(), msp);
adminCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getAdminsList()));
revokedCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getRevocationListList()));
intermediateCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getIntermediateCertsList()));
rootCerts.put(msp.getName(), BFTCommon.selectSelfSigned(BFTCommon.extractCertificates(msp.getRootCertsList())));
validatedCerts.put(msp.getName(), new HashMap<>());
}
Map<String,ConfigItem> confMap = configGroupToConfigMap(conf.getConfig().getChannelGroup(), rootGroupKey);
String path = policyPrefix + pathSeparator + rootGroupKey;
Policy policy = parsePolicy(chan, path, path + pathSeparator + "Writers", "Writers", confMap);
chanWriters.put(chan, policy);
chanMSPs.put(chan, mspIDs);
}
}
public void newChannel(String channelID, long sequence, Configtx.ConfigEnvelope conf, long timestamp) throws BFTException {
Set<MspConfig.FabricMSPConfig> msps = extractMSPs(conf.getConfig(), channelID.equals(sysChannel));
Set<String> mspIDs = new TreeSet<>();
try {
for (MspConfig.FabricMSPConfig msp : msps) {
mspIDs.add(msp.getName());
this.MSPs.put(msp.getName(), msp);
this.adminCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getAdminsList()));
this.revokedCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getRevocationListList()));
this.intermediateCerts.put(msp.getName(), BFTCommon.extractCertificates(msp.getIntermediateCertsList()));
this.rootCerts.put(msp.getName(), BFTCommon.selectSelfSigned(BFTCommon.extractCertificates(msp.getRootCertsList())));
this.validatedCerts.put(msp.getName(), new HashMap<>());
for (X509Certificate adminCert : this.adminCerts.get(msp.getName())) {
logger.debug("Verifying admin certificate for channel " + channelID + " and MSP " + msp.getName());
this.verifyCertificate(adminCert, msp.getName(), timestamp);
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | true |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/ECDSAKeyLoader.java | src/bft/util/ECDSAKeyLoader.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import bftsmart.tom.util.KeyLoader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
/**
*
* @author joao
*/
public class ECDSAKeyLoader implements KeyLoader {
private String path;
private int myId;
private String sigAlgorithm;
public ECDSAKeyLoader(int myId, String configHome, String sigAlgorithm) {
this.myId = myId;
this.path = configHome + "keys" + System.getProperty("file.separator");
this.sigAlgorithm = sigAlgorithm;
}
public X509Certificate loadCertificate() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return loadCertificate(this.myId);
}
public X509Certificate loadCertificate(int id) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return BFTCommon.getCertificate(path + "cert" + id + ".pem");
}
@Override
public PublicKey loadPublicKey(int id) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return loadCertificate(id).getPublicKey();
}
@Override
public PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return loadCertificate(this.myId).getPublicKey();
}
@Override
public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return BFTCommon.getPemPrivateKey(path + "keystore.pem");
}
@Override
public String getSignatureAlgorithm() {
return this.sigAlgorithm;
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/BlockCutter.java | src/bft/util/BlockCutter.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hyperledger.fabric.protos.common.Common;
/**
*
* @author joao
*/
public class BlockCutter {
//These maps comprise the state of the blockcutter relevant to the state machine
private Map<String, List<byte[]>> pendingBatches;
private Map<String, Long> PreferredMaxBytes;
private Map<String, Long> MaxMessageCount;
private Map<String, Integer> pendingBatchSizeBytes;
private static Logger logger;
private BlockCutter() { //used for state transfer
pendingBatches = new TreeMap<>();
pendingBatchSizeBytes = new TreeMap<>();
PreferredMaxBytes = new TreeMap<>();
MaxMessageCount = new TreeMap<>();
logger = LoggerFactory.getLogger(BlockCutter.class);
}
@Override
public BlockCutter clone() {
BlockCutter clone = new BlockCutter();
Map<String, List<byte[]>> clonePendingBatches = new TreeMap<>();
pendingBatches.forEach((channel, envelopes) ->{
List<byte[]> clonedEnvs = new LinkedList<>();
clonedEnvs.addAll(envelopes);
clonePendingBatches.put(channel, clonedEnvs);
});
Map<String, Long> clonedPreferredMaxBytes = new TreeMap<>();
clonedPreferredMaxBytes.putAll(PreferredMaxBytes);
Map<String, Long> clonedMaxMessageCount = new TreeMap<>();
clonedMaxMessageCount.putAll(MaxMessageCount);
Map<String, Integer> clonedPendingBatchSizeBytes = new TreeMap<>();
clonedPendingBatchSizeBytes.putAll(pendingBatchSizeBytes);
clone.pendingBatches = clonePendingBatches;
clone.PreferredMaxBytes = clonedPreferredMaxBytes;
clone.MaxMessageCount = clonedMaxMessageCount;
clone.pendingBatchSizeBytes = clonedPendingBatchSizeBytes;
return clone;
}
public static BlockCutter getInstance() {
return new BlockCutter();
}
/*public BlockCutter(byte [] bytes) {
logger = LogFactory.getLog(BlockCutter.class);
pendingBatches = new TreeMap<>();
pendingBatchSizeBytes = new TreeMap<>();
setBatchParms(bytes);
}*/
public List<byte[][]> ordered(String channel, byte [] env, boolean isolated) throws IOException {
if (pendingBatches.get(channel) == null) {
pendingBatches.put(channel, new LinkedList<>());
pendingBatchSizeBytes.put(channel, 0);
}
LinkedList batches = new LinkedList<>();
int messageSizeBytes = messageSizeBytes(env);
if (isolated || messageSizeBytes > PreferredMaxBytes.get(channel)) {
if (isolated) {
logger.debug("Found message which requested to be isolated, cutting into its own batch");
} else {
logger.debug("The current message, with " + messageSizeBytes + " bytes, is larger than the preferred batch size of " + PreferredMaxBytes + " bytes and will be isolated.");
}
// cut pending batch, if it has any messages
if (pendingBatches.get(channel).size() > 0) {
batches.add(cut(channel));
}
// create new batch with single message
pendingBatches.get(channel).add(env);
pendingBatchSizeBytes.put(channel, (pendingBatchSizeBytes.get(channel) + messageSizeBytes));
batches.add(cut(channel));
return batches;
}
//int messageSizeBytes = (env != null ? env.length : 0);
boolean messageWillOverflowBatchSizeBytes = pendingBatchSizeBytes.get(channel) + messageSizeBytes > PreferredMaxBytes.get(channel);
if (messageWillOverflowBatchSizeBytes && pendingBatches.get(channel).size() > 0) {
logger.debug("The current message, with " + messageSizeBytes + " bytes, will overflow the pending batch of " + pendingBatchSizeBytes + " bytes.");
logger.debug("Pending batch would overflow if current message is added, cutting batch now.");
batches.add(cut(channel));
}
logger.debug("Enqueuing message into batch");
pendingBatches.get(channel).add(env);
pendingBatchSizeBytes.put(channel, (pendingBatchSizeBytes.get(channel) + messageSizeBytes));
if (pendingBatches.get(channel).size() >= MaxMessageCount.get(channel)) {
logger.debug("Batch size met, cutting batch");
batches.add(cut(channel));
}
return batches;
}
public byte[][] cut(String channel) {
if (pendingBatches.get(channel) == null) pendingBatches.put(channel, new LinkedList<>());
byte[][] batch = new byte[pendingBatches.get(channel).size()][];
if (batch.length > 0) pendingBatches.get(channel).toArray(batch);
pendingBatches.get(channel).clear();
pendingBatchSizeBytes.put(channel, 0);
return batch;
}
private int messageSizeBytes(byte[] bytes) {
try {
Common.Envelope env = Common.Envelope.parseFrom(bytes);
return env.getPayload().size() + env.getSignature().size();
} catch (Exception e) {
logger.warn("Invalid envelope, using native 'length' attribute");
return bytes.length;
}
}
public void setBatchParms(String channel, long preferredMaxBytes, long maxMessageCount) {
PreferredMaxBytes.put(channel, preferredMaxBytes);
MaxMessageCount.put(channel, maxMessageCount);
logger.info("Updated PreferredMaxBytes: " + PreferredMaxBytes);
logger.info("Updated MaxMessageCount: " + MaxMessageCount);
}
public byte[] serialize() throws IOException {
//serialize pending envelopes
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutput o = new ObjectOutputStream(b);
o.writeObject(pendingBatches);
o.flush();
byte[] envs = b.toByteArray();
b.close();
o.close();
//serialize pending batch sizes
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(pendingBatchSizeBytes);
o.flush();
byte[] sizes = b.toByteArray();
b.close();
o.close();
//serialize max bytes
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(PreferredMaxBytes);
o.flush();
byte[] max = b.toByteArray();
b.close();
o.close();
//serialize message count
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(MaxMessageCount);
o.flush();
byte[] count = b.toByteArray();
b.close();
o.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(envs.length);
out.write(envs);
out.flush();
bos.flush();
out.writeInt(sizes.length);
out.write(sizes);
out.flush();
bos.flush();
out.writeInt(max.length);
out.write(max);
out.flush();
bos.flush();
out.writeInt(count.length);
out.write(count);
out.flush();
bos.flush();
out.close();
bos.close();
return bos.toByteArray();
}
public static BlockCutter deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
BlockCutter instance = getInstance();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bis);
byte[] envs = new byte[0];
int n = in.readInt();
if (n > 0) {
envs = new byte[n];
in.read(envs);
}
byte[] sizes = new byte[0];
n = in.readInt();
if (n > 0) {
sizes = new byte[n];
in.read(sizes);
}
byte[] max = new byte[0];
n = in.readInt();
if (n > 0) {
max = new byte[n];
in.read(max);
}
byte[] count = new byte[0];
n = in.readInt();
if (n > 0) {
count = new byte[n];
in.read(count);
}
in.close();
bis.close();
ByteArrayInputStream b = new ByteArrayInputStream(envs);
ObjectInput i = null;
i = new ObjectInputStream(b);
instance.pendingBatches = (Map<String,List<byte[]>>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(sizes);
i = new ObjectInputStream(b);
instance.pendingBatchSizeBytes = (Map<String,Integer>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(max);
i = new ObjectInputStream(b);
instance.PreferredMaxBytes = (Map<String,Long>) i.readObject();
i.close();
b.close();
b = new ByteArrayInputStream(count);
i = new ObjectInputStream(b);
instance.MaxMessageCount = (Map<String,Long>) i.readObject();
i.close();
b.close();
return instance;
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/ProxyReplyListener.java | src/bft/util/ProxyReplyListener.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import bftsmart.reconfiguration.views.View;
import bftsmart.tom.AsynchServiceProxy;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.Extractor;
import bftsmart.tom.util.KeyLoader;
import bftsmart.tom.util.TOMUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.Provider;
import java.util.AbstractMap.SimpleEntry;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hyperledger.fabric.protos.common.Common;
/**
*
* @author joao
*/
public class ProxyReplyListener extends AsynchServiceProxy {
private int id;
private Map<Integer, BFTCommon.ReplyTuple[]> replies;
private Map<Integer, Entry<String, Common.Block>> responses;
private Comparator<BFTCommon.ReplyTuple> comparator;
private int replyQuorum;
private int next;
private Lock inputLock;
private Condition blockAvailable;
private Logger logger;
//used to detected updates to the view
private int nextView;
private View[] views;
//used to extract latest sequence number
private int[] sequences;
public ProxyReplyListener(int id) {
super(id);
this.id = id;
init();
}
public ProxyReplyListener(int id, String configHome) {
super(id, configHome);
this.id = id;
init();
}
public ProxyReplyListener(int id, String configHome, KeyLoader loader, Provider provider) {
super(id, configHome, loader, provider);
this.id = id;
init();
}
public ProxyReplyListener(int id, String configHome,
Comparator<byte[]> replyComparator, Extractor replyExtractor, KeyLoader loader, Provider provider) {
super(id, configHome, replyComparator, replyExtractor, loader, provider);
this.id = id;
init();
}
private void init() {
logger = LoggerFactory.getLogger(ProxyReplyListener.class);
responses = new ConcurrentHashMap<>();
replies = new HashMap<>();
replyQuorum = getReplyQuorum();
comparator = (BFTCommon.ReplyTuple o1, BFTCommon.ReplyTuple o2) -> o1.block.equals(o2.block) && // compare entire block
o1.metadata[0].getValue().equals(o2.metadata[0].getValue()) && // compare block signature value
o1.metadata[1].getValue().equals(o2.metadata[1].getValue()) && // compare config signature value
o1.channel.equals(o2.channel) && // compare channel id
o1.config == o2.config // compare block type
? 0 : -1
;
this.inputLock = new ReentrantLock();
this.blockAvailable = inputLock.newCondition();
nextView = getViewManager().getCurrentViewId();
views = new View[getViewManager().getCurrentViewN()];
sequences = new int[getViewManager().getCurrentViewN()];
for (int i = 0; i < sequences.length; i++) {
sequences[i] = -1;
}
}
private View newView(byte[] bytes) {
Object o = TOMUtil.getObject(bytes);
return (o != null && o instanceof View ? (View) o : null);
}
private int newSequence(byte[] bytes) {
try {
byte[][] contents = BFTCommon.deserializeContents(bytes);
return ((new String(contents[0])).equals("SEQUENCE") ? ByteBuffer.wrap(contents[1]).getInt() : -1);
} catch (IOException ex) {
return -1;
}
}
@Override
public void replyReceived(TOMMessage tomm) {
View v = null;
int s = -1;
try {
canReceiveLock.lock();
if ((v = newView(tomm.getContent())) != null) { // am I receiving a new view?
processReplyView(tomm, v);
} else if ((s = newSequence(tomm.getContent())) != -1) { // am I being updated on the sequence number?
processReplySequence(tomm, s);
} else { // I am receiving blocks
processReplyBlock(tomm);
}
}
finally {
canReceiveLock.unlock();
}
}
private void processReplySequence(TOMMessage tomm, int s) {
int sameContent = 1;
int pos = getViewManager().getCurrentViewPos(tomm.getSender());
sequences[pos] = s;
for (int i = 0; i < sequences.length; i++) {
if ((sequences[i] != -1) && (i != pos || getViewManager().getCurrentViewN() == 1)
&& (tomm.getReqType() != TOMMessageType.ORDERED_REQUEST || sequences[i] == s)) {
sameContent++;
}
}
if (sameContent >= replyQuorum) {
logger.info("Updating ProxyListener to sequence " + s);
next = s;
sequences = new int[getViewManager().getCurrentViewN()];
for (int i = 0; i < sequences.length; i++) {
sequences[i] = -1;
}
}
}
private void processReplyView (TOMMessage tomm, View v) {
int sameContent = 1;
int pos = getViewManager().getCurrentViewPos(tomm.getSender());
views[pos] = v;
for (int i = 0; i < views.length; i++) {
if ((views[i] != null) && (i != pos || getViewManager().getCurrentViewN() == 1)
&& (tomm.getReqType() != TOMMessageType.ORDERED_REQUEST || views[i].equals(v))) {
sameContent++;
}
}
if (sameContent >= replyQuorum && v.getId() > getViewManager().getCurrentViewId()) {
logger.info("Updating ProxyListener to view " + v.getId());
reconfigureTo(v);
replyQuorum = getReplyQuorum();
views = new View[getViewManager().getCurrentViewN()];
// this message is sent again to make all replicas not from the previous view aware of the client
askForView();
}
}
private void processReplyBlock (TOMMessage tomm) {
if (tomm.getSequence() < next) { // ignore replies that no longer matter
replies.remove(tomm.getSequence());
responses.remove(tomm.getSequence());
return;
}
int pos = getViewManager().getCurrentViewPos(tomm.getSender());
if (pos < 0) { //ignore messages that don't come from replicas
return;
}
if (replies.get(tomm.getSequence()) == null) //avoid nullpointer exception
replies.put(tomm.getSequence(), new BFTCommon.ReplyTuple[getViewManager().getCurrentViewN()]);
byte[][] contents = null;
Common.Block block = null;
Common.Metadata metadata[] = new Common.Metadata[2];
String channel = null;
boolean config = false;
try {
contents = BFTCommon.deserializeContents(tomm.getContent());
if (contents == null || contents.length < 5) return;
block = Common.Block.parseFrom(contents[0]);
if (block == null) return;
metadata[0] = Common.Metadata.parseFrom(contents[1]);
if (metadata[0] == null) return;
metadata[1] = Common.Metadata.parseFrom(contents[2]);
if (metadata[1] == null) return;
channel = new String(contents[3]);
config = (contents[4][0] == 1);
} catch (IOException ex) {
logger.error("Failed to deserialize block and metadata", ex);
return;
}
BFTCommon.ReplyTuple[] reps = replies.get(tomm.getSequence());
reps[pos] = BFTCommon.getReplyTuple(block,metadata,channel,config);
int sameContent = 1;
for (int i = 0; i < reps.length; i++) {
if ((i != pos || getViewManager().getCurrentViewN() == 1) && reps[i] != null
&& (comparator.compare(reps[i], reps[pos]) == 0)) {
sameContent++;
if (sameContent >= replyQuorum) {
Common.Block response = getBlock(reps, pos);
responses.put(tomm.getSequence(), new SimpleEntry<>(channel + ":" + config, response));
if (tomm.getViewID() > nextView) {
nextView = tomm.getViewID();
views = new View[getViewManager().getCurrentViewN()];
// this is needed to fetch the current view from the replicas
askForView();
}
}
}
}
this.inputLock.lock();
if (responses.get(next) != null) this.blockAvailable.signalAll();
this.inputLock.unlock();
}
private void askForView() {
Thread t = new Thread() {
@Override
public void run() {
try {
invokeAsynchRequest(BFTCommon.assembleSignedRequest(getViewManager().getStaticConf().getPrivateKey(), id, "GETVIEW", "", new byte[0]), getViewManager().getCurrentViewProcesses(),
null, TOMMessageType.ORDERED_REQUEST);
} catch (IOException ex) {
logger.error("Failed to send GETVIEW request to nodes", ex);
}
}
};
t.start();
}
public Entry<String,Common.Block> getNext() {
Entry<String,Common.Block> ret = null;
this.inputLock.lock();
while ((ret = responses.get(next)) == null) {
this.blockAvailable.awaitUninterruptibly();
}
this.inputLock.unlock();
next++;
return ret;
}
private Common.Block getBlock(BFTCommon.ReplyTuple[] replies, int lastReceived) {
Common.Block.Builder block = replies[lastReceived].block.toBuilder();
Common.BlockMetadata.Builder blockMetadata = block.getMetadata().toBuilder();
Common.Metadata[] blockSigs = new Common.Metadata[replies.length];
Common.Metadata[] configSigs = new Common.Metadata[replies.length];
Common.Metadata.Builder allBlockSig = Common.Metadata.newBuilder();
Common.Metadata.Builder allConfigSig = Common.Metadata.newBuilder();
for (int i = 0; i < replies.length; i++) {
if (replies[i] != null) {
blockSigs[i] = replies[i].metadata[0];
configSigs[i] = replies[i].metadata[1];
}
}
allBlockSig.setValue(blockSigs[lastReceived].getValue());
for (Common.Metadata sig : blockSigs) {
if (sig != null) {
allBlockSig.addSignatures(sig.getSignatures(0));
}
}
allConfigSig.setValue(configSigs[lastReceived].getValue());
for (Common.Metadata sig : configSigs) {
if (sig != null) {
allConfigSig.addSignatures(sig.getSignatures(0));
}
}
blockMetadata.setMetadata(Common.BlockMetadataIndex.SIGNATURES_VALUE, allBlockSig.build().toByteString());
blockMetadata.setMetadata(Common.BlockMetadataIndex.LAST_CONFIG_VALUE, allConfigSig.build().toByteString());
block.setMetadata(blockMetadata.build());
return block.build();
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/FabricVMServices.java | src/bft/util/FabricVMServices.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import bftsmart.reconfiguration.VMServices;
import bftsmart.tom.util.KeyLoader;
import java.security.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.helper.Config;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
/**
*
* @author joao
*/
public class FabricVMServices extends VMServices {
private static KeyLoader keyLoader;
private static Provider provider;
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, IllegalAccessException, InstantiationException, CryptoException, InvalidArgumentException {
String configDir = BFTCommon.getBFTSMaRtConfigDir("RECONFIG_DIR");
if (System.getProperty("logback.configurationFile") == null)
System.setProperty("logback.configurationFile", configDir + "logback.xml");
provider = new BouncyCastleProvider();
CryptoPrimitives crypto = new CryptoPrimitives();
crypto.init();
if (args.length == 1) {
System.out.println("####Tpp Service[Disjoint]####");
int id = Integer.parseInt(args[0]);
keyLoader = new ECDSAKeyLoader(id, configDir, crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
VMServices vm = new VMServices(keyLoader, provider, configDir);
vm.removeServer(id);
}else if (args.length == 3) {
System.out.println("####Tpp Service[Join]####");
int id = Integer.parseInt(args[0]);
String ipAddress = args[1];
int port = Integer.parseInt(args[2]);
keyLoader = new ECDSAKeyLoader(id, configDir, crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
VMServices vm = new VMServices(keyLoader, provider, configDir);
vm.addServer(id, ipAddress, port);
}else{
System.out.println("Usage: java FabricVMServices <replica id> [ip address] [port]");
System.out.println("If the ip address and port number are given, the replica will be added to the group, otherwise it will be removed.");
System.exit(1);
}
Thread.sleep(2000);//2s
System.exit(0);
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/util/BFTCommon.java | src/bft/util/BFTCommon.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.util;
import bftsmart.tom.MessageContext;
import bftsmart.tom.util.TOMUtil;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Timestamp;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertStore;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.PKIXCertPathBuilderResult;
import java.security.cert.TrustAnchor;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x500.style.IETFUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.common.Configtx;
import org.hyperledger.fabric.protos.msp.Identities;
import org.hyperledger.fabric.protos.msp.MspConfig;
import org.hyperledger.fabric.protos.orderer.Configuration;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
/**
*
* @author joao
*/
public class BFTCommon {
private static Logger logger;
private static CryptoPrimitives crypto;
public final static String DEFAULT_CONFIG_DIR = "./config/";
public static class BFTException extends Exception {
public BFTException(String msg) {
super(msg);
}
}
public class BFTTuple {
public Common.Block block = null;
public MessageContext msgContext = null;
public int sequence = -1;
public String channelID = null;
public boolean config = false;
public MSPManager clonedManager = null;
private BFTTuple(Common.Block block, MessageContext msgCtx, int sequence, String channelID, boolean config, MSPManager clonedManager) {
this.block = block;
this.msgContext = msgCtx;
this.sequence = sequence;
this.channelID = channelID;
this.config = config;
this.clonedManager = clonedManager;
}
}
public class RequestTuple {
public int id = -1;
public String type = null;
public String channelID = null;
public byte[] payload = null;
public byte[] signature = null;
private RequestTuple(int id, String type, String channelID, byte[] payload, byte[] signature) {
this.id = id;
this.type = type;
this.channelID = channelID;
this.payload = payload;
this.signature = signature;
}
}
public class ReplyTuple {
public Common.Block block;
public Common.Metadata[] metadata;
public String channel;
public boolean config;
private ReplyTuple (Common.Block block, Common.Metadata[] metadata, String channel, boolean config) {
this.block = block;
this.metadata = metadata;
this.channel = channel;
this.config = config;
}
}
public static RequestTuple getRequestTuple(int id, String type, String channelID, byte[] payload, byte[] signature){
BFTCommon t = new BFTCommon();
RequestTuple r = t.new RequestTuple(id, type, channelID, payload, signature);
return r;
}
public static BFTTuple getBFTTuple(Common.Block block, MessageContext msgCtx, int sequence, String channelID, boolean config, MSPManager clonedManager) {
BFTCommon t = new BFTCommon();
BFTTuple r = t.new BFTTuple(block, msgCtx, sequence, channelID, config, clonedManager);
return r;
}
public static ReplyTuple getReplyTuple(Common.Block block, Common.Metadata[] metadata, String channel, boolean config) {
BFTCommon t = new BFTCommon();
ReplyTuple r = t.new ReplyTuple(block, metadata, channel, config);
return r;
}
public static void init(CryptoPrimitives crypt) throws NoSuchAlgorithmException, NoSuchProviderException{
crypto = crypt;
logger = LoggerFactory.getLogger(Common.class);
}
public static String getBFTSMaRtConfigDir(String envVar) {
String configDir = BFTCommon.DEFAULT_CONFIG_DIR;
String envDir = System.getenv(envVar);
if (envDir != null) {
File path = new File(envDir);
if (path.exists() && path.isDirectory()) configDir = envDir;
}
if (!configDir.endsWith("/")) configDir = configDir + "/";
return configDir;
}
public static Duration parseDuration(String s) {
return Duration.parse("PT"+s.trim().replaceAll("\\s+",""));
}
public static BFTCommon.RequestTuple deserializeRequest(byte[] request) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(request);
DataInput in = new DataInputStream(bis);
int id = in.readInt();
String type = in.readUTF();
String channelID = in.readUTF();
int l = in.readInt();
byte[] payload = new byte[l];
in.readFully(payload);
bis.close();
return BFTCommon.getRequestTuple(id, type, channelID, payload, null);
}
public static BFTCommon.RequestTuple deserializeSignedRequest(byte[] request) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(request);
DataInput in = new DataInputStream(bis);
int l = in.readInt();
byte[] msg = new byte[l];
in.readFully(msg);
l = in.readInt();
byte[] sig = new byte[l];
in.readFully(sig);
bis.close();
bis = new ByteArrayInputStream(msg);
in = new DataInputStream(bis);
int id = in.readInt();
String type = in.readUTF();
String channelID = in.readUTF();
l = in.readInt();
byte[] payload = new byte[l];
in.readFully(payload);
bis.close();
return BFTCommon.getRequestTuple(id, type, channelID, payload, sig);
}
public static byte[] serializeRequest(int id, String type, String channelID, byte[] payload) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(type.length() + channelID.length() + payload.length);
DataOutput out = new DataOutputStream(bos);
out.writeInt(id);
out.writeUTF(type);
out.writeUTF(channelID);
out.writeInt(payload.length);
out.write(payload);
bos.flush();
bos.close();
return bos.toByteArray();
}
public static byte[] assembleSignedRequest(PrivateKey key, int id, String type, String channelID, byte[] payload) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(type.length() + channelID.length() + payload.length);
DataOutput out = new DataOutputStream(bos);
out.writeInt(id);
out.writeUTF(type);
out.writeUTF(channelID);
out.writeInt(payload.length);
out.write(payload);
bos.flush();
bos.close();
byte[] msg = bos.toByteArray();
byte[] sig = TOMUtil.signMessage(key, msg);
bos = new ByteArrayOutputStream(msg.length+sig.length);
out = new DataOutputStream(bos);
out.writeInt(msg.length);
out.write(msg);
out.writeInt(sig.length);
out.write(sig);
bos.flush();
bos.close();
return bos.toByteArray();
}
public static Common.Block createNextBlock(long number, byte[] previousHash, byte[][] envs) throws NoSuchAlgorithmException, NoSuchProviderException, BFTException {
if (crypto == null) throw new BFTException("No CryptoPrimitive object suplied");
//initialize
Common.BlockHeader.Builder blockHeaderBuilder = Common.BlockHeader.newBuilder();
Common.BlockData.Builder blockDataBuilder = Common.BlockData.newBuilder();
Common.BlockMetadata.Builder blockMetadataBuilder = Common.BlockMetadata.newBuilder();
Common.Block.Builder blockBuilder = Common.Block.newBuilder();
//create header
blockHeaderBuilder.setNumber(number);
if (previousHash != null) blockHeaderBuilder.setPreviousHash(ByteString.copyFrom(previousHash));
blockHeaderBuilder.setDataHash(ByteString.copyFrom(crypto.hash(BFTCommon.concatenate(envs))));
//create metadata
int numIndexes = Common.BlockMetadataIndex.values().length;
for (int i = 0; i < numIndexes; i++) {
blockMetadataBuilder.addMetadata(ByteString.EMPTY);
}
//create data
for (int i = 0; i < envs.length; i++) {
blockDataBuilder.addData(ByteString.copyFrom(envs[i]));
}
//crete block
blockBuilder.setHeader(blockHeaderBuilder.build());
blockBuilder.setMetadata(blockMetadataBuilder.build());
blockBuilder.setData(blockDataBuilder.build());
return blockBuilder.build();
}
public static Common.SignatureHeader createSignatureHeader(byte[] creator, byte[] nonce) {
Common.SignatureHeader.Builder signatureHeaderBuilder = Common.SignatureHeader.newBuilder();
signatureHeaderBuilder.setCreator(ByteString.copyFrom(creator));
signatureHeaderBuilder.setNonce(ByteString.copyFrom(nonce));
return signatureHeaderBuilder.build();
}
public static Common.Metadata createMetadataSignature(PrivateKey privKey, byte[] creator, byte[] nonce, byte[] plaintext, Common.BlockHeader blockHeader) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException, CryptoException, BFTException {
if (crypto == null) throw new BFTException("No CryptoPrimitive object suplied");
Common.Metadata.Builder metadataBuilder = Common.Metadata.newBuilder();
Common.MetadataSignature.Builder metadataSignatureBuilder = Common.MetadataSignature.newBuilder();
Common.SignatureHeader sigHeader = createSignatureHeader(creator, nonce);
metadataSignatureBuilder.setSignatureHeader(sigHeader.toByteString());
byte[][] concat = {plaintext, sigHeader.toByteString().toByteArray(), encodeBlockHeaderASN1(blockHeader)};
//byte[] sig = sign(concatenate(concat));
byte[] sig = crypto.sign(privKey, BFTCommon.concatenate(concat));
logger.debug("Signature for block #" + blockHeader.getNumber() + ": " + Arrays.toString(sig) + "\n");
//parseSig(sig);
metadataSignatureBuilder.setSignature(ByteString.copyFrom(sig));
metadataBuilder.setValue((plaintext != null ? ByteString.copyFrom(plaintext) : ByteString.EMPTY));
metadataBuilder.addSignatures(metadataSignatureBuilder);
return metadataBuilder.build();
}
public static byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException {
//convert long to byte array
//ByteArrayOutputStream bos = new ByteArrayOutputStream();
//ObjectOutput out = new ObjectOutputStream(bos);
//out.writeLong(header.getNumber());
//out.flush();
//bos.flush();
//out.close();
//bos.close();
//byte[] number = bos.toByteArray();
// encode the header in ASN1 format
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ASN1OutputStream asnos = new ASN1OutputStream(bos);
asnos.writeObject(new ASN1Integer((int) header.getNumber()));
//asnos.writeObject(new DERInteger((int) header.getNumber()));
asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray()));
asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray()));
asnos.flush();
bos.flush();
asnos.close();
bos.close();
byte[] buffer = bos.toByteArray();
//Add golang idiosyncrasies
byte[] bytes = new byte[buffer.length + 2];
bytes[0] = 48; // no idea what this means, but golang's encoding uses it
bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang
for (int i = 0; i < buffer.length; i++) { // concatenate
bytes[i + 2] = buffer[i];
}
return bytes;
}
public static String extractMSPID(byte[] bytes) {
try {
Common.Envelope env = Common.Envelope.parseFrom(bytes);
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.SignatureHeader sigHeader = Common.SignatureHeader.parseFrom(payload.getHeader().getSignatureHeader());
Identities.SerializedIdentity ident = Identities.SerializedIdentity.parseFrom(sigHeader.getCreator());
return ident.getMspid();
} catch (InvalidProtocolBufferException ex) {
//ex.printStackTrace();
return null;
}
}
public static Set<MspConfig.FabricMSPConfig> extractFabricMSPConfigs(Set<String> orgs, Map<String, Configtx.ConfigGroup> groups) throws InvalidProtocolBufferException {
Set<MspConfig.FabricMSPConfig> msps = new HashSet<>();
for (String org : orgs) {
Configtx.ConfigGroup group = groups.get(org);
//Configtx.ConfigGroup group = groups.get(OrdererGroupKey).getGroupsMap().get(org);
Configtx.ConfigValue value = group.getValuesMap().get("MSP");
MspConfig.MSPConfig mspConf = MspConfig.MSPConfig.parseFrom(value.getValue());
MspConfig.FabricMSPConfig fabMspConf = MspConfig.FabricMSPConfig.parseFrom(mspConf.getConfig());
msps.add(fabMspConf);
}
return msps;
}
public static long extractTimestamp(Common.Payload payload) throws InvalidProtocolBufferException {
Common.ChannelHeader header = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
return Instant.ofEpochSecond(header.getTimestamp().getSeconds()).plusNanos(header.getTimestamp().getNanos()).toEpochMilli();
}
public static Configuration.BatchSize extractBachSize(Configtx.Config conf) throws InvalidProtocolBufferException {
Map<String,Configtx.ConfigGroup> groups = conf.getChannelGroup().getGroupsMap();
return Configuration.BatchSize.parseFrom(groups.get("Orderer").getValuesMap().get("BatchSize").getValue());
}
public static Configtx.ConfigEnvelope extractConfigEnvelope(Common.Block block) throws InvalidProtocolBufferException {
Common.Envelope env = Common.Envelope.parseFrom(block.getData().getData(0));
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.ChannelHeader chanHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
if (chanHeader.getType() == Common.HeaderType.CONFIG_VALUE) {
return Configtx.ConfigEnvelope.parseFrom(payload.getData());
}
else return null;
}
public static Configtx.ConfigEnvelope makeConfigEnvelope (Configtx.Config config, Common.Envelope lastUpdate) {
Configtx.ConfigEnvelope.Builder newConfEnvBuilder = Configtx.ConfigEnvelope.newBuilder();
newConfEnvBuilder.setConfig(config);
newConfEnvBuilder.setLastUpdate(lastUpdate);
return newConfEnvBuilder.build();
}
public static Common.Envelope makeUnsignedEnvelope(ByteString dataMsg, ByteString sigHeader, Common.HeaderType headerType, int version, String chainID, long epoch, long timestamp) throws CryptoException {
//if (crypto == null) throw new BFTException("No CryptoPrimitive object suplied");
Common.ChannelHeader chanHeader = makeChannelHeader(headerType, version, chainID, epoch, timestamp);
//Common.SignatureHeader sigHeader = createSignatureHeader(creator, nonce);
Common.Header.Builder header = Common.Header.newBuilder();
header.setChannelHeader(chanHeader.toByteString());
//header.setSignatureHeader(sigHeader.toByteString());
header.setSignatureHeader(sigHeader);
Common.Payload.Builder payload = Common.Payload.newBuilder();
payload.setData(dataMsg);
payload.setHeader(header);
byte[] bytes = payload.build().toByteArray();
//byte[] sig = crypto.sign(privKey, bytes);
Common.Envelope.Builder env = Common.Envelope.newBuilder();
env.setPayload(ByteString.copyFrom(bytes));
//env.setSignature(ByteString.copyFrom(sig));
env.setSignature(ByteString.EMPTY);
return env.build();
}
public static Common.ChannelHeader makeChannelHeader(Common.HeaderType headerType, int version, String chainID, long epoch, long timestamp) {
Timestamp.Builder ts = Timestamp.newBuilder();
ts.setSeconds(timestamp / 1000);
ts.setNanos(0);
Common.ChannelHeader.Builder result = Common.ChannelHeader.newBuilder();
result.setType(headerType.getNumber());
result.setVersion(version);
result.setEpoch(epoch);
result.setChannelId(chainID);
result.setTimestamp(ts);
result.setTlsCertHash(ByteString.EMPTY);
return result.build();
}
public static boolean verifyFrontendSignature(int id, PublicKey key, RequestTuple tuple) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(bos);
out.writeInt(tuple.id);
out.writeUTF(tuple.type);
out.writeUTF(tuple.channelID);
out.writeInt(tuple.payload.length);
out.write(tuple.payload);
bos.flush();
bos.close();
return TOMUtil.verifySignature(key, bos.toByteArray(), tuple.signature);
} catch (IOException ex) {
logger.error("Failed to verify frontend signature", ex);
return false;
}
}
public static Set<X509Certificate> selectSelfSigned(Set<X509Certificate> roots ) {
// Try to verify root certificate signature with its own public key
Set<X509Certificate> selfSigned = new HashSet<>();
for (X509Certificate root : roots) {
PublicKey key = root.getPublicKey();
try {
root.verify(key);
selfSigned.add(root);
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) {
logger.error("Failed to select self-signed certificates", ex);
}
}
return selfSigned;
}
public static Set<X509Certificate> extractCertificates(List<ByteString> list) throws CertificateException, IOException {
Set<X509Certificate> certs = new HashSet<>();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
for (ByteString bt : list) {
InputStream in = new ByteArrayInputStream(bt.toByteArray());
certs.add((X509Certificate)certFactory.generateCertificate(in));
in.close();
}
return certs;
}
public static Map<String,Set<String>> cloneChanMSPs(Map<String,Set<String>> original) {
Map<String,Set<String>> cloneMap = new TreeMap<>();
Set<String> keys = original.keySet();
keys.forEach((key) -> {
Set<String> cloneSet = new HashSet<>();
Set<String> originalSet = original.get(key);
originalSet.forEach((msp) -> {
cloneSet.add(msp);
});
cloneMap.put(key, cloneSet);
});
return cloneMap;
}
public static byte[] concatenate(byte[][] bytes) {
int totalLength = 0;
for (byte[] b : bytes) {
if (b != null) {
totalLength += b.length;
}
}
byte[] concat = new byte[totalLength];
int last = 0;
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != null) {
for (int j = 0; j < bytes[i].length; j++) {
concat[last + j] = bytes[i][j];
}
last += bytes[i].length;
}
}
return concat;
}
public static PrivateKey getPemPrivateKey(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
PEMParser pp = new PEMParser(br);
Object obj = pp.readObject();
pp.close();
br.close();
if (obj instanceof PrivateKeyInfo) {
PrivateKeyInfo keyInfo = (PrivateKeyInfo) obj;
return (new JcaPEMKeyConverter().getPrivateKey(keyInfo));
} else {
PEMKeyPair pemKeyPair = (PEMKeyPair) obj;
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
return kp.getPrivate();
}
}
//public static X509CertificateHolder getCertificate(String filename) throws IOException {
public static X509Certificate getCertificate(String filename) throws IOException, CertificateException {
/*BufferedReader br = new BufferedReader(new FileReader(filename));
PEMParser pp = new PEMParser(br);
X509CertificateHolder ret = (X509CertificateHolder) pp.readObject();
br.close();
pp.close();*/
File file = new File(filename);
InputStream is = new FileInputStream(file);
return getCertificate(IOUtils.toByteArray(is));
}
public static X509Certificate getCertificate(byte[] serializedCert) throws IOException, CertificateException {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(serializedCert);
X509Certificate ret = (X509Certificate)certFactory.generateCertificate(in);
in.close();
return ret;
}
public static byte[] getSerializedCertificate(X509Certificate certificate) throws IOException, CertificateEncodingException {
PemObject pemObj = (new PemObject("", certificate.getEncoded()));
StringWriter strWriter = new StringWriter();
PemWriter writer = new PemWriter(strWriter);
writer.writeObject(pemObj);
writer.close();
strWriter.close();
return strWriter.toString().getBytes();
/*Base64 base64 = new Base64();
StringWriter strWriter = new StringWriter();
strWriter.write(X509Factory.BEGIN_CERT);
strWriter.write(base64.encodeAsString(certificate.getEncoded()));
strWriter.write(X509Factory.END_CERT);
return strWriter.toString().getBytes();*/
}
public static Identities.SerializedIdentity getSerializedIdentity(String Mspid, byte[] serializedCert) {
Identities.SerializedIdentity.Builder ident = Identities.SerializedIdentity.newBuilder();
ident.setMspid(Mspid);
ident.setIdBytes(ByteString.copyFrom(serializedCert));
return ident.build();
}
public static byte[] serializeContents(byte[][] contents) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(contents.length);
out.flush();
bos.flush();
for (int i = 0; i < contents.length; i++) {
out.writeInt(contents[i].length);
out.write(contents[i]);
out.flush();
bos.flush();
}
out.close();
bos.close();
return bos.toByteArray();
}
public static byte[][] deserializeContents(byte[] bytes) throws IOException {
byte[][] batch = null;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bis);
int nContents = in.readInt();
batch = new byte[nContents][];
for (int i = 0; i < nContents; i++) {
int length = in.readInt();
batch[i] = new byte[length];
in.read(batch[i]);
}
in.close();
bis.close();
return batch;
}
public static PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, Set<X509Certificate> trustedRootCerts,
Set<X509Certificate> intermediateCerts, Date date) throws GeneralSecurityException {
// Create the selector that specifies the starting certificate
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(cert);
// Create the trust anchors (set of root CA certificates)
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate trustedRootCert : trustedRootCerts) {
trustAnchors.add(new TrustAnchor(trustedRootCert, null));
}
// Configure the PKIX certificate builder algorithm parameters
PKIXBuilderParameters pkixParams =
new PKIXBuilderParameters(trustAnchors, selector);
// Disable CRL checks (this is done manually as additional step)
pkixParams.setRevocationEnabled(false);
pkixParams.setSigProvider("BC");
pkixParams.setDate(date); // necessary for determinism
// Specify a list of intermediate certificates
CertStore intermediateCertStore = CertStore.getInstance("Collection",
new CollectionCertStoreParameters(intermediateCerts),"BC");
pkixParams.addCertStore(intermediateCertStore);
// Build and verify the certification chain
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX","BC");
PKIXCertPathBuilderResult result =
(PKIXCertPathBuilderResult) builder.build(pkixParams);
return result;
}
public static byte[] getCertificationChainIdentifierFromChain(String hashFunction, List<X509Certificate> path) throws BFTException {
try{
MessageDigest digestEngine = MessageDigest.getInstance(hashFunction, "BC");
for (X509Certificate cert : path) {
digestEngine.update(cert.getEncoded());
}
return digestEngine.digest();
} catch (Exception ex) {
throw new BFTCommon.BFTException("Failed to compute certificate chain ID for certificate chain: " + ex.getMessage());
}
}
public static String[] extractOUsFronCertificate(X509Certificate cert) throws BFTException {
LinkedList<String> OUs = new LinkedList<>();
try {
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
for (RDN rdn : x500name.getRDNs(BCStyle.OU)) {
for (AttributeTypeAndValue atv : rdn.getTypesAndValues()) {
OUs.add(IETFUtils.valueToString(atv.getValue()));
}
}
} catch (Exception ex) {
throw new BFTException("Error fetching OUs from certificate: " + ex.getMessage());
}
String[] result = new String[OUs.size()];
OUs.toArray(result);
return result;
}
public static boolean verifySignature(X509Certificate cert, byte[] payload, byte[] signature) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, BFTCommon.BFTException {
Signature sigEngine = Signature.getInstance(cert.getSigAlgName(), "BC");
sigEngine.initVerify(cert.getPublicKey());
sigEngine.update(payload);
return sigEngine.verify(signature);
}
public static byte[] hash(byte[] bytes, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest digestEngine = MessageDigest.getInstance(algorithm,"BC");
return digestEngine.digest(bytes);
}
public static Date toDate(long timestamp){
return Date.from(Instant.ofEpochMilli(timestamp));
}
/*private void parseSig(byte[] sig) throws IOException {
ASN1InputStream input = new ASN1InputStream(sig);
ASN1Primitive p;
while ((p = input.readObject()) != null) {
ASN1Sequence asn1 = ASN1Sequence.getInstance(p);
ASN1Integer r = ASN1Integer.getInstance(asn1.getObjectAt(0));
ASN1Integer s = ASN1Integer.getInstance(asn1.getObjectAt(1));
logger.info("r (int): " + r.getValue().toString());
logger.info("s (int): " + s.getValue().toString());
logger.info("r (bytes): " + Arrays.toString(r.getValue().toByteArray()));
logger.info("s (bytes): " + Arrays.toString(s.getValue().toByteArray()));
}
}
private byte[] sign(byte[] text) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException, CryptoException {
Signature signEngine = Signature.getInstance("SHA256withECDSA", BouncyCastleProvider.PROVIDER_NAME);
signEngine.initSign(privKey);
signEngine.update(text);
return signEngine.sign();
}
private boolean verify(byte[] text, byte[] signature) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException, PEMException {
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | true |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/test/WorkloadClient.java | src/bft/test/WorkloadClient.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.test;
import bft.util.BFTCommon;
import bft.util.ECDSAKeyLoader;
import bft.util.ProxyReplyListener;
import bftsmart.communication.client.ReplyListener;
import bftsmart.tom.AsynchServiceProxy;
import bftsmart.tom.RequestContext;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.KeyLoader;
import com.google.protobuf.ByteString;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.msp.Identities;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.helper.Config;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author joao
*/
public class WorkloadClient {
private static Logger logger;
private static Logger loggerLatency;
private static String configDir;
private static CryptoPrimitives crypto;
private static ProxyReplyListener proxy = null;
//arguments
private enum TxType {
random, unsigned, signed
}
private static int frontendID;
private static String channelID;
private static int clients;
private static int envSize;
private static int txsPerWorker;
private static TxType txType;
private static int delay;
// Own MSP artifacts
private static String mspid = null;
private static PrivateKey privKey = null;
private static X509Certificate certificate = null;
private static byte[] serializedCert = null;
private static Identities.SerializedIdentity ident;
//timestamps for latencies
private static Map<Integer,Long> timestamps;
public static void main(String[] args) throws Exception{
if(args.length < 7) {
System.out.println("Use: java bft.test.WorkloadClient <frontend ID> <channel ID> <num workers> <payload size> <txs per worker> <random|unsigned|signed> <delay (ms)>");
System.exit(-1);
}
configDir = BFTCommon.getBFTSMaRtConfigDir("WORKLOAD_CONFIG_DIR");
if (System.getProperty("logback.configurationFile") == null)
System.setProperty("logback.configurationFile", configDir + "logback.xml");
Security.addProvider(new BouncyCastleProvider());
logger = LoggerFactory.getLogger(WorkloadClient.class);
loggerLatency = LoggerFactory.getLogger("latency");
WorkloadClient.crypto = new CryptoPrimitives();
WorkloadClient.crypto.init();
BFTCommon.init(WorkloadClient.crypto);
frontendID = Integer.parseInt(args[0]);
channelID = args[1];
clients = Integer.parseInt(args[2]);
envSize = Integer.parseInt(args[3]);
txsPerWorker = Integer.parseInt(args[4]);
txType = TxType.valueOf(args[5]);
delay = Integer.parseInt(args[6]);
loadConfig();
timestamps = new ConcurrentHashMap<>();
if (proxy != null) {
int reqId = proxy.invokeAsynchRequest(BFTCommon.assembleSignedRequest(proxy.getViewManager().getStaticConf().getPrivateKey(),
frontendID, "SEQUENCE", "", new byte[]{}), null, TOMMessageType.ORDERED_REQUEST);
proxy.cleanAsynchRequest(reqId);
new ProxyThread().start();
}
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < clients; i++) {
executor.execute(new WorkerThread(i + frontendID + 1));
}
}
private static void loadConfig() throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException {
LineIterator it = FileUtils.lineIterator(new File(WorkloadClient.configDir + "node.config"), "UTF-8");
Map<String,String> configs = new TreeMap<>();
while (it.hasNext()) {
String line = it.nextLine();
if (!line.startsWith("#") && line.contains("=")) {
String[] params = line.split("\\=");
configs.put(params[0], params[1]);
}
}
it.close();
ECDSAKeyLoader loader = new ECDSAKeyLoader(frontendID, configDir, crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM));
mspid = configs.get("MSPID");
privKey = loader.loadPrivateKey();
certificate = loader.loadCertificate();
serializedCert = BFTCommon.getSerializedCertificate(certificate);
ident = BFTCommon.getSerializedIdentity(mspid, serializedCert);
String[] IDs = configs.get("RECEIVERS").split("\\,");
int[] recvs = Arrays.asList(IDs).stream().mapToInt(Integer::parseInt).toArray();
for (int o : recvs) {
if (o == frontendID) {
proxy = new ProxyReplyListener(frontendID, configDir, loader, Security.getProvider("BC"));
break;
}
}
}
private static class WorkerThread implements Runnable {
int id;
AsynchServiceProxy worker;
long count;
Random rand = new Random(System.nanoTime());
public WorkerThread (int id) {
this.id = id;
this.worker = new AsynchServiceProxy(this.id, configDir, new KeyLoader() {
@Override
public PublicKey loadPublicKey(int i) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return null;
}
@Override
public PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
return null;
}
@Override
public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return null;
}
@Override
public String getSignatureAlgorithm() {
return null;
}
}, Security.getProvider("BC"));
this.count = 0;
}
@Override
public void run() {
while (this.count < txsPerWorker) {
try {
int hash = 7;
hash = 31 * hash + this.id;
hash = 31 * hash + Long.hashCode(this.count);
int size = Math.max(envSize, Integer.BYTES);
ByteBuffer buffer = ByteBuffer.allocate(size);
buffer.putInt(hash);
while (buffer.remaining() > 0) {
buffer.put((byte) rand.nextInt());
}
byte[] array = buffer.array();
byte[] req = array;
if (txType != TxType.random) {
byte[] nonce = new byte[10];
rand.nextBytes(nonce);
Common.SignatureHeader sigHeader = BFTCommon.createSignatureHeader(ident.toByteArray(), nonce);
Common.Envelope.Builder env = BFTCommon.makeUnsignedEnvelope(ByteString.copyFrom(array),
sigHeader.toByteString(), Common.HeaderType.MESSAGE, 0, channelID, 0,System.currentTimeMillis()).toBuilder();
/*Common.Payload.Builder payload = Common.Payload.parseFrom(env.getPayload()).toBuilder();
Common.Header.Builder header = payload.getHeader().toBuilder();
header.setSignatureHeader(sigHeader.toByteString());
payload.setHeader(header);
env.setPayload(payload.build().toByteString());*/
if (txType == TxType.signed) {
byte[] sig = crypto.sign(privKey, env.getPayload().toByteArray());
env.setSignature(ByteString.copyFrom(sig));
} else {
env.setSignature(ByteString.EMPTY);
}
req = env.build().toByteArray();
}
timestamps.put(hash, System.currentTimeMillis());
this.worker.invokeAsynchRequest(BFTCommon.serializeRequest(this.id, "REGULAR", channelID, req), new ReplyListener(){
private int replies = 0;
@Override
public void reset() {
replies = 0;
}
@Override
public void replyReceived(RequestContext rc, TOMMessage tomm) {
if (Arrays.equals(tomm.getContent(), "ACK".getBytes())) replies++;
double q = Math.ceil((double) (worker.getViewManager().getCurrentViewN() + worker.getViewManager().getCurrentViewF() + 1) / 2.0);
if (replies >= q) {
worker.cleanAsynchRequest(rc.getOperationId());
}
}
}, TOMMessageType.ORDERED_REQUEST);
//this.worker.cleanAsynchRequest(reqId);
logger.debug("[{}]Sent envelope #{} with {} bytes", this.id, this.count, req.length);
this.count++;
if (delay > 0) {
Thread.sleep(delay);
}
} catch (CryptoException | IOException ex) {
logger.error("Failed to send payload to nodes", ex);
} catch (InterruptedException ex) {
logger.error("Interruption while sleeping", ex);
}
}
logger.info("[{}] finished", this.id);
}
}
private static class ProxyThread extends Thread {
public void run() {
while (true) {
try {
Map.Entry<String,Common.Block> reply = proxy.getNext();
Common.BlockData data = reply.getValue().getData();
for (ByteString env : data.getDataList()) {
byte[] req = env.toByteArray();
if (txType != TxType.random) {
Common.Payload payload = Common.Payload.parseFrom(Common.Envelope.parseFrom(env).getPayload());
req = payload.getData().toByteArray();
}
ByteBuffer buffer = ByteBuffer.wrap(req);
int hash = buffer.getInt();
Long ts = timestamps.remove(hash);
if (ts != null)
loggerLatency.info("block#" + reply.getValue().getHeader().getNumber() + "\t" + (System.currentTimeMillis() - ts));
else logger.debug("Envelope with latency id " + hash + " at block#" + reply.getValue().getHeader().getNumber() + " not for me");
}
logger.debug("Finished processing block#" + reply.getValue().getHeader().getNumber());
} catch (Exception ex) {
logger.error("Failed to fetch latency result", ex);
}
}
}
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
bft-smart/fabric-orderingservice | https://github.com/bft-smart/fabric-orderingservice/blob/8e1c9dd7226793efbbee791357f196ea507a9a49/src/bft/test/TestSignatures.java | src/bft/test/TestSignatures.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bft.test;
import com.google.protobuf.ByteString;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.msp.Identities;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
/**
*
* @author joao
*/
public class TestSignatures {
private static CryptoPrimitives crypto;
private static final int NUM_BATCHES = 1000;
private static final String Mspid = "DEFAULT";
private static Random rand;
private static ExecutorService executor = null;
private static PrivateKey privKey = null;
private static byte[] serializedCert = null;
private static Identities.SerializedIdentity ident;
//measurements
private static long sigsMeasurementStartTime = -1;
private static int interval;
private static int countSigs = 0;
public static void main(String[] args) throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, IOException, InterruptedException, ClassNotFoundException, IllegalAccessException, InstantiationException {
if(args.length < 7) {
System.out.println("Use: java TestSignatures <privKey> <certificate> <batch size> <envelope size> <two sigs?> <parallelism> <sig thread batch>");
System.exit(-1);
}
TestSignatures.crypto = new CryptoPrimitives();
TestSignatures.crypto.init();
TestSignatures.rand = new Random(System.nanoTime());
String privKey = args[0];
String cert = args[1];
int batchSize = Integer.parseInt(args[2]);
int envSize =Integer.parseInt(args[3]);
boolean twoSigs = Boolean.parseBoolean(args[4]);
int parallelism = Integer.parseInt(args[5]);
int sigBatch = Integer.parseInt(args[6]);
/*TestSignatures.executor = Executors.newFixedThreadPool(parallelism, (Runnable r) -> {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
});*/
/*TestSignatures.executor = Executors.newCachedThreadPool((Runnable r) -> {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
});*/
TestSignatures.executor = Executors.newWorkStealingPool(parallelism);
TestSignatures.privKey = getPemPrivateKey(privKey);
parseCertificate(cert);
TestSignatures.ident = getSerializedIdentity();
interval = 100 * sigBatch;
//Generate pool of batches
System.out.print("Generating " + NUM_BATCHES + " batches with " + batchSize + " envelopes each... ");
byte[][][] batches = new byte[NUM_BATCHES][batchSize][];
for (int i = 0; i < NUM_BATCHES; i++) {
for (int j = 0; j < batchSize; j++) {
batches[i][j] = new byte[envSize];
rand.nextBytes(batches[i][j]);
}
}
System.out.println(" done!");
System.out.print("Generating batch pool of " + NUM_BATCHES + " blocks... ");
Common.Block[] blocks = new Common.Block[NUM_BATCHES];
for (int i = 0; i < NUM_BATCHES; i++) {
byte[] dummyDigest = new byte[rand.nextInt(1000)];
rand.nextBytes(dummyDigest);
dummyDigest = TestSignatures.crypto.hash(dummyDigest);
blocks[i] = createNextBlock(i, dummyDigest, batches[rand.nextInt(batches.length)]);
}
System.out.println(" done!");
System.out.println("Generating signatures with a pool of " + NUM_BATCHES + " blocks... ");
LinkedBlockingQueue<SignerThread> queue = new LinkedBlockingQueue<>();
sigsMeasurementStartTime = System.currentTimeMillis();
for (int i = 0 ; i < parallelism; i++) {
SignerThread s = new SignerThread(queue, twoSigs);
LinkedList<Common.Block> l = new LinkedList<>();
for (int j = 0; j < sigBatch; j++) {
// Force the code to always sign different data
Common.Block.Builder block = blocks[rand.nextInt(NUM_BATCHES)].toBuilder();
block.setHeader(blocks[rand.nextInt(NUM_BATCHES)].getHeader());
l.add(block.build());
}
s.input(l);
TestSignatures.executor.execute(s);
}
while (true) {
//if (multiThread) {
SignerThread s = queue.take();
countSigs += sigBatch;
if (countSigs % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - sigsMeasurementStartTime));
System.out.println("Throughput = " + tp + " sigs/sec");
sigsMeasurementStartTime = System.currentTimeMillis();
}
LinkedList<Common.Block> l = new LinkedList<>();
for (int i = 0; i < sigBatch; i++) {
Common.Block.Builder block = blocks[rand.nextInt(NUM_BATCHES)].toBuilder();
block.setHeader(blocks[rand.nextInt(NUM_BATCHES)].getHeader());
l.add(block.build());
}
s.input(l);
//}
}
}
private static void parseCertificate(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
PEMParser pp = new PEMParser(br);
X509CertificateHolder certificate = (X509CertificateHolder) pp.readObject();
PemObject pemObj = (new PemObject("", certificate.getEncoded()));
StringWriter strWriter = new StringWriter();
PemWriter writer = new PemWriter(strWriter);
writer.writeObject(pemObj);
writer.close();
strWriter.close();
TestSignatures.serializedCert = strWriter.toString().getBytes();
}
private static Identities.SerializedIdentity getSerializedIdentity() {
Identities.SerializedIdentity.Builder ident = Identities.SerializedIdentity.newBuilder();
ident.setMspid(Mspid);
ident.setIdBytes(ByteString.copyFrom(serializedCert));
return ident.build();
}
private static PrivateKey getPemPrivateKey(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
//Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
br.close();
return kp.getPrivate();
//samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
}
private static Common.Block createNextBlock(long number, byte[] previousHash, byte[][] envs) throws NoSuchAlgorithmException, NoSuchProviderException {
//initialize
Common.BlockHeader.Builder blockHeaderBuilder = Common.BlockHeader.newBuilder();
Common.BlockData.Builder blockDataBuilder = Common.BlockData.newBuilder();
Common.BlockMetadata.Builder blockMetadataBuilder = Common.BlockMetadata.newBuilder();
Common.Block.Builder blockBuilder = Common.Block.newBuilder();
//create header
blockHeaderBuilder.setNumber(number);
blockHeaderBuilder.setPreviousHash(ByteString.copyFrom(previousHash));
blockHeaderBuilder.setDataHash(ByteString.copyFrom(crypto.hash(concatenate(envs))));
//create metadata
int numIndexes = Common.BlockMetadataIndex.values().length;
for (int i = 0; i < numIndexes; i++) blockMetadataBuilder.addMetadata(ByteString.EMPTY);
//create data
for (int i = 0; i < envs.length; i++)
blockDataBuilder.addData(ByteString.copyFrom(envs[i]));
//crete block
blockBuilder.setHeader(blockHeaderBuilder.build());
blockBuilder.setMetadata(blockMetadataBuilder.build());
blockBuilder.setData(blockDataBuilder.build());
return blockBuilder.build();
}
private static byte[] concatenate(byte[][] bytes) {
int totalLength = 0;
for (byte[] b : bytes) {
if (b != null) {
totalLength += b.length;
}
}
byte[] concat = new byte[totalLength];
int last = 0;
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != null) {
for (int j = 0; j < bytes[i].length; j++) {
concat[last + j] = bytes[i][j];
}
last += bytes[i].length;
}
}
return concat;
}
private static class SignerThread implements Runnable {
//private Common.Block block;
private LinkedBlockingQueue<Common.Block> input;
private LinkedBlockingQueue<SignerThread> output;
private boolean twoSigs;
private final Lock inputLock = new ReentrantLock();
private final Condition notEmptyInput = inputLock.newCondition();
/*SignerThread(Common.Block block) {
this.block = block;
}*/
SignerThread(LinkedBlockingQueue<SignerThread> output, boolean twoSigs) throws InterruptedException {
this.input = new LinkedBlockingQueue<>();
this.output = output;
this.twoSigs = twoSigs;
//LinkedList<Common.Block> l = new LinkedList<>();
//l.add(firstBlock);
//input(l);
}
public void input(Collection<Common.Block> blocks) throws InterruptedException {
inputLock.lock();
input.addAll(blocks);
notEmptyInput.signalAll();
inputLock.unlock();
}
private byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException {
// encode the header in ASN1 format
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ASN1OutputStream asnos = new ASN1OutputStream(bos);
asnos.writeObject(new ASN1Integer((int) header.getNumber()));
//asnos.writeObject(new DERInteger((int) header.getNumber()));
asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray()));
asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray()));
asnos.flush();
bos.flush();
asnos.close();
bos.close();
byte[] buffer = bos.toByteArray();
//Add golang idiocracies
byte[] bytes = new byte[buffer.length+2];
bytes[0] = 48; // no idea what this means, but golang's encoding uses it
bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang
for (int i = 0; i < buffer.length; i++) { // concatenate
bytes[i+2] = buffer[i];
}
return bytes;
}
private Common.Metadata createMetadataSignature(byte[] creator, byte[] nonce, byte[] plaintext, Common.BlockHeader blockHeader) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException, CryptoException {
Common.Metadata.Builder metadataBuilder = Common.Metadata.newBuilder();
Common.MetadataSignature.Builder metadataSignatureBuilder = Common.MetadataSignature.newBuilder();
Common.SignatureHeader.Builder signatureHeaderBuilder = Common.SignatureHeader.newBuilder();
signatureHeaderBuilder.setCreator(ByteString.copyFrom(creator));
signatureHeaderBuilder.setNonce(ByteString.copyFrom(nonce));
Common.SignatureHeader sigHeader = signatureHeaderBuilder.build();
metadataSignatureBuilder.setSignatureHeader(sigHeader.toByteString());
byte[][] concat = {plaintext, sigHeader.toByteString().toByteArray(), encodeBlockHeaderASN1(blockHeader)};
//byte[] sig = sign(concatenate(concat));
byte[] sig = crypto.sign(privKey, concatenate(concat));
//parseSig(sig);
metadataSignatureBuilder.setSignature(ByteString.copyFrom(sig));
metadataBuilder.setValue((plaintext != null ? ByteString.copyFrom(plaintext) : ByteString.EMPTY));
metadataBuilder.addSignatures(metadataSignatureBuilder);
return metadataBuilder.build();
}
@Override
public void run() {
while (true) {
try {
ArrayList<Common.Block> blocks = new ArrayList<>();
inputLock.lock();
if(input.isEmpty()) {
notEmptyInput.await();
}
input.drainTo(blocks);
inputLock.unlock();
for (Common.Block block : blocks) {
//create nonce
byte[] nonces = new byte[rand.nextInt(10)];
rand.nextBytes(nonces);
//create signatures
Common.Metadata blockSig = createMetadataSignature(ident.toByteArray(), nonces, null, block.getHeader());
if (twoSigs) {
byte[] dummyConf = {0, 0, 0, 0, 0, 0, 0, 1}; //TODO: find a way to implement the check that is done in the golang code
Common.Metadata configSig = createMetadataSignature(ident.toByteArray(), nonces, dummyConf, block.getHeader());
}
}
output.put(this);
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException | IOException | CryptoException | InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
| java | Apache-2.0 | 8e1c9dd7226793efbbee791357f196ea507a9a49 | 2026-01-05T02:40:27.346805Z | false |
9001/party-up | https://github.com/9001/party-up/blob/d2e1d7c32ac02f7f663a02f28c0020e3c3b35557/app/src/test/java/me/ocv/partyup/ExampleUnitTest.java | app/src/test/java/me/ocv/partyup/ExampleUnitTest.java | package me.ocv.partyup;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | java | MIT | d2e1d7c32ac02f7f663a02f28c0020e3c3b35557 | 2026-01-05T02:40:42.627768Z | false |
9001/party-up | https://github.com/9001/party-up/blob/d2e1d7c32ac02f7f663a02f28c0020e3c3b35557/app/src/main/java/me/ocv/partyup/MainActivity.java | app/src/main/java/me/ocv/partyup/MainActivity.java | package me.ocv.partyup;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String txt = "<p><em>Hello from <a href=\"https://github.com/9001/party-up\">Party UP!</a> <b>version " + BuildConfig.VERSION_NAME + "</b></em></p>" +
"<p>This app lets you upload files (images, videos) to a <a href=\"https://github.com/9001/copyparty#quickstart\">copyparty</a> server.</p>" +
"<hr />" +
"<p><b>Use your favorite gallery app to open a picture or video you'd like to upload, then hit the share button and select \"Party UP!\" \uD83C\uDF89</b></p>" +
"<p>You can also share things like youtube videos; the app will then upload a message with the link. The copyparty server can be configured to log these for later viewing.</p>" +
"<p>Funfact: You can run the copyparty server itself on any device where Python is available -- and thanks to <a href=\"https://f-droid.org/en/packages/com.termux/\">Termux</a> this also means Android phones :^)</p>";
TextView tv = ((TextView)findViewById(R.id.textView4));
tv.setText(Html.fromHtml(txt, Html.FROM_HTML_MODE_LEGACY));
tv.setMovementMethod(LinkMovementMethod.getInstance());
((Button)findViewById(R.id.settingsBtn)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
}
});
}
}
| java | MIT | d2e1d7c32ac02f7f663a02f28c0020e3c3b35557 | 2026-01-05T02:40:42.627768Z | false |
9001/party-up | https://github.com/9001/party-up/blob/d2e1d7c32ac02f7f663a02f28c0020e3c3b35557/app/src/main/java/me/ocv/partyup/XferActivity.java | app/src/main/java/me/ocv/partyup/XferActivity.java | package me.ocv.partyup;
import static java.lang.String.format;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.preference.PreferenceManager;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import me.ocv.partyup.databinding.ActivityXferBinding;
class F {
public Uri handle;
public String name;
public long size;
public String full_url;
public String share_url;
public String desc;
}
public class XferActivity extends AppCompatActivity {
ActivityXferBinding binding;
SharedPreferences prefs;
Intent the_intent;
String password;
String base_url;
String share_url;
Bitmap share_qr;
boolean upping;
String the_msg;
long bytes_done, bytes_total, t0;
F[] files;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upping = false;
share_url = null;
share_qr = null;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
binding = ActivityXferBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
the_intent = getIntent();
String etype = the_intent.getType();
String action = the_intent.getAction();
boolean one = Intent.ACTION_SEND.equals(action);
boolean many = Intent.ACTION_SEND_MULTIPLE.equals(action);
if (etype == null || (!one && !many)) {
show_msg("cannot share content;\naction: " + action + "\ntype: " + etype);
return;
}
Uri[] handles = null;
if (many) {
ArrayList<Uri> x = the_intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
handles = x.toArray(new Uri[0]);
} else if (one) {
Uri uri = (Uri) the_intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null)
handles = new Uri[]{uri};
else
the_msg = the_intent.getStringExtra(Intent.EXTRA_TEXT);
}
if (handles != null) {
files = new F[handles.length];
for (int a = 0; a < handles.length; a++) {
F f = new F();
f.handle = handles[a];
f.name = null;
f.size = -1;
files[a] = f;
}
handleSendImage();
} else if (the_msg != null) {
handleSendText();
} else {
show_msg("cannot decide on what to send for " + the_intent.getType());
return;
}
password = prefs.getString("server_password", "");
if (password == null || password.isEmpty() || password.equals("Default value"))
password = null;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(v -> {
fab.setVisibility(View.GONE);
do_up();
});
}
private void show_msg(String txt) {
((TextView) findViewById(R.id.upper_info)).setText(txt);
}
private void tshow_msg(String txt) {
final TextView tv = (TextView) findViewById(R.id.upper_info);
tv.post(() -> tv.setText(txt));
}
void need_storage(String exmsg) {
if (Build.VERSION.SDK_INT > 29 && exmsg.contains("EACCES"))
show_msg(exmsg + "\n\nYou must update the app you shared the file from; it is using a dead/forbidden API for sharing files, and Android is preventing new versions of PartyUP! from using this API. Older versions of PartyUP! such as 1.6.0 may work.");
String perm = Manifest.permission.READ_EXTERNAL_STORAGE;
if (this.checkSelfPermission(perm) == PackageManager.PERMISSION_GRANTED)
return; // already have it, so that's not why it failed
if (!shouldShowRequestPermissionRationale(perm)) {
request_storage();
return;
}
AlertDialog.Builder ab = new AlertDialog.Builder(findViewById(R.id.upper_info).getContext());
ab.setMessage("PartyUP! needs additional permissions to read that file, because the app you shared it from is using old APIs."
).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
request_storage();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
void request_storage() {
String perm = Manifest.permission.READ_EXTERNAL_STORAGE;
requestPermissions(new String[]{perm}, 573);
}
@Override
public void onRequestPermissionsResult(int permRequestCode, String perms[], int[] grantRes) {
String perm = Manifest.permission.READ_EXTERNAL_STORAGE;
if (permRequestCode != 573)
return;
for (int a = 0; a < grantRes.length; a++) {
if (!perms[a].equals(perm))
continue;
if (grantRes[a] != PackageManager.PERMISSION_GRANTED)
return;
handleSendImage();
}
}
String getext(String mime) {
if (mime == null)
return "bin";
mime = mime.replace(';', ' ').split(" ")[0];
switch (mime) {
case "audio/ogg":
return "ogg";
case "audio/mpeg":
return "mp3";
case "audio/mp4":
return "m4a";
case "image/jpeg":
return "jpg";
}
if (mime.startsWith("text/"))
return "txt";
if (mime.contains("/")) {
mime = mime.split("/")[1];
if (mime.matches("^[a-zA-Z0-9]{1,8}$"))
return mime;
}
return "bin";
}
int[] parseExpiration(String value) {
// Returns [number, unit] where unit: 0=minutes, 1=hours, 2=days, -1=invalid/empty
if (value == null || value.trim().isEmpty())
return new int[]{0, -1};
value = value.trim().toLowerCase();
if (!value.matches("^\\d+[mhd]?$"))
return new int[]{0, -1};
char unit = value.charAt(value.length() - 1);
int num;
int unitType;
if (Character.isDigit(unit)) {
num = Integer.parseInt(value);
unitType = 0; // minutes
} else {
num = Integer.parseInt(value.substring(0, value.length() - 1));
switch (unit) {
case 'h': unitType = 1; break;
case 'd': unitType = 2; break;
default: unitType = 0; break;
}
}
return new int[]{num, unitType};
}
String getExpirationMinutes() {
String value = prefs.getString("link_expiration", "");
int[] parsed = parseExpiration(value);
if (parsed[1] < 0)
return "";
int minutes = parsed[0];
if (parsed[1] == 1) minutes *= 60; // hours
else if (parsed[1] == 2) minutes *= 1440; // days
return String.valueOf(minutes);
}
String getExpirationLabel() {
String value = prefs.getString("link_expiration", "");
int[] parsed = parseExpiration(value);
if (parsed[1] < 0)
return "never expires";
int num = parsed[0];
switch (parsed[1]) {
case 0: return num + " minute" + (num != 1 ? "s" : "");
case 1: return num + " hour" + (num != 1 ? "s" : "");
case 2: return num + " day" + (num != 1 ? "s" : "");
default: return "never expires";
}
}
private void handleSendText() {
show_msg("Post the following link?\n\n" + the_msg);
showShareSettings();
if (prefs.getBoolean("autosend", false))
do_up();
}
private void showShareSettings() {
if (prefs.getBoolean("use_share_url", false)) {
findViewById(R.id.share_settings).setVisibility(View.VISIBLE);
EditText expField = findViewById(R.id.share_expiration);
EditText pwField = findViewById(R.id.share_password);
String defaultExp = prefs.getString("link_expiration", "");
String defaultPw = prefs.getString("share_password", "");
expField.setText(defaultExp != null ? defaultExp : "");
pwField.setText(defaultPw != null ? defaultPw : "");
}
}
@SuppressLint("DefaultLocale")
private void handleSendImage() {
for (F f : files) {
Log.d("me.ocv.partyup", format("handle [%s]", f.handle));
if (f.handle.toString().startsWith("file:///")) {
f.name = Paths.get(f.handle.getPath()).getFileName().toString();
} else {
// contentresolver returns the wrong filesize (off by 626 bytes)
// but we want the name so lets go
try {
Cursor cur = getContentResolver().query(f.handle, null, null, null, null);
assert cur != null;
int iname = cur.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int isize = cur.getColumnIndex(OpenableColumns.SIZE);
cur.moveToFirst();
f.name = cur.getString(iname);
f.size = cur.getLong(isize);
cur.close();
} catch (Exception ex) {
Log.w("me.ocv.partyup", "contentresolver: " + ex.toString());
}
}
MessageDigest md = null;
if (f.name == null) {
try {
md = MessageDigest.getInstance("SHA-512");
} catch (Exception ex) {
}
}
// get correct filesize
try {
InputStream ins = getContentResolver().openInputStream(f.handle);
assert ins != null;
byte[] buf = new byte[128 * 1024];
long sz = 0;
while (true) {
int n = ins.read(buf);
if (n <= 0)
break;
sz += n;
if (md != null)
md.update(buf, 0, n);
}
f.size = sz;
} catch (Exception ex) {
String exmsg = "Error3: " + ex.toString();
show_msg(exmsg);
need_storage(exmsg);
return;
}
if (md != null) {
String csum = new String(Base64.getUrlEncoder().encode(md.digest())).substring(0, 15);
f.name = format("mystery-file-%s.%s", csum, getext(the_intent.getType()));
}
f.desc = format("%s\n\nsize: %,d byte\ntype: %s", f.name, f.size, the_intent.getType());
}
String msg;
bytes_done = bytes_total = 0;
if (files.length == 1) {
msg = "Upload the following file?\n\n" + files[0].desc;
bytes_total = files[0].size;
} else {
msg = "Upload the following " + files.length + " files?\n\n";
for (int a = 0; a < Math.min(10, files.length); a++) {
msg += " ► " + files[a].name + "\n";
bytes_total += files[a].size;
}
if (files.length > 10)
msg += "[...]\n";
msg += format("\n(total %,d bytes)", bytes_total);
}
show_msg(msg);
showShareSettings();
if (prefs.getBoolean("autosend", false))
do_up();
}
private void do_up() {
if (upping)
return;
upping = true;
new Thread(this::do_up2).start();
}
private void do_up2() {
try {
base_url = prefs.getString("server_url", "");
if (base_url == null)
throw new Exception("server_url config is invalid");
if (!base_url.startsWith("http"))
base_url = "http://" + base_url;
if (!base_url.endsWith("/"))
base_url += "/";
if (base_url.contains("%")) {
String[] dtc = "%Y %q %m %d %j %H %M %S".split(" ");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy Q MM dd DDD HH mm ss");
String[] dtp = dtf.withZone(ZoneId.from(ZoneOffset.UTC)).format(Instant.now()).split(" ");
for (int a = 0; a < dtc.length; a++)
base_url = base_url.replace(dtc[a], dtp[a]);
}
t0 = System.currentTimeMillis();
tshow_msg("Sending to " + base_url + " ...");
int nfiles = files == null ? 1 : files.length;
for (int a = 0; a < nfiles; a++) {
String full_url = base_url;
if (files != null) {
F f = files[a];
full_url += URLEncoder.encode(f.name, "UTF-8");
tshow_msg("Sending to " + base_url + " ...\n\n" + f.desc);
f.full_url = full_url;
}
URL url = new URL(full_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
if (password != null)
conn.setRequestProperty("PW", password);
if (files == null)
do_textmsg(conn);
else if (!do_fileput(conn, a))
return;
}
if (prefs.getBoolean("use_share_url", false))
createShareUrl(files);
findViewById(R.id.upper_info).post(() -> onsuccess());
} catch (Exception ex) {
tshow_msg("Error2: " + ex.toString() + "\n\nmaybe wrong password?");
}
}
String read_err(HttpURLConnection conn) {
try {
byte[] buf = new byte[1024];
int n = Math.max(0, conn.getErrorStream().read(buf));
return new String(buf, 0, n, StandardCharsets.UTF_8);
} catch (Exception ex) {
return ex.toString();
}
}
private void do_textmsg(HttpURLConnection conn) throws Exception {
byte[] body = ("msg=" + URLEncoder.encode(the_msg, "UTF-8")).getBytes(StandardCharsets.UTF_8);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(body.length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(body);
os.flush();
int rc = conn.getResponseCode();
if (rc >= 300) {
tshow_msg("Server error " + rc + ":\n" + read_err(conn));
conn.disconnect();
return;
}
conn.disconnect();
}
@SuppressLint("DefaultLocale")
private boolean do_fileput(HttpURLConnection conn, int nfile) throws Exception {
F f = files[nfile];
conn.setRequestMethod("PUT");
conn.setFixedLengthStreamingMode(f.size);
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.connect();
final TextView tv = (TextView) findViewById(R.id.upper_info);
final ProgressBar pb = (ProgressBar) findViewById(R.id.progbar);
OutputStream os = conn.getOutputStream();
InputStream ins = getContentResolver().openInputStream(f.handle);
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] buf = new byte[128 * 1024];
assert ins != null;
while (true) {
int n = ins.read(buf);
if (n <= 0)
break;
bytes_done += n;
os.write(buf, 0, n);
md.update(buf, 0, n);
tv.post(() -> {
double perc = ((double) bytes_done * 1000) / bytes_total;
long td = 1 + System.currentTimeMillis() - t0;
double spd = bytes_done / (td / 1000.0);
long left = (long) ((bytes_total - bytes_done) / spd);
tv.setText(format("Sending to %s ...\n\nFile %d of %d:\n%s\n\nbytes done: %,d\nbytes left: %,d\nspeed: %.2f MiB/s\nprogress: %.2f %%\nETA: %d sec",
base_url,
nfile + 1,
files.length,
f.desc,
bytes_done,
bytes_total - bytes_done,
spd / 1024 / 1024,
perc / 10,
left
));
pb.setProgress((int) Math.round(perc));
});
}
os.flush();
int rc = conn.getResponseCode();
if (rc >= 300) {
tshow_msg("Server error " + rc + ":\n" + read_err(conn));
conn.disconnect();
return false;
}
String sha = "";
byte[] bsha = md.digest();
for (int a = 0; a < 28; a++)
sha += format("%02x", bsha[a]);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] lines = br.lines().toArray(String[]::new);
conn.disconnect();
if (lines.length < 3) {
tshow_msg("SERVER ERROR:\n" + lines[0]);
return false;
}
if (lines[2].indexOf(sha) != 0) {
tshow_msg("ERROR:\nFile got corrupted during the upload;\n\n" + lines[2] + " expected\n" + sha + " from server");
return false;
}
if (lines.length > 3 && !lines[3].isEmpty())
f.share_url = lines[3];
else
f.share_url = f.full_url.split("\\?")[0];
return true;
}
void createShareUrl(F[] f) {
try {
// Generate random key
String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom random = new SecureRandom();
StringBuilder key = new StringBuilder();
for (int i = 0; i < 12; i++)
key.append(chars.charAt(random.nextInt(chars.length())));
URL url = new URL(f[0].full_url);
// Build share API URL (base URL without file path)
String shareApiUrl = url.getProtocol() + "://" + url.getHost();
if (url.getPort() != -1)
shareApiUrl += ":" + url.getPort();
shareApiUrl += "/?share";
// Get expiration
EditText expField = findViewById(R.id.share_expiration);
String expValue = expField.getText().toString();
int[] parsed = parseExpiration(expValue);
String expiration = "";
if (parsed[1] >= 0) {
int minutes = parsed[0];
if (parsed[1] == 1) minutes *= 60;
else if (parsed[1] == 2) minutes *= 1440;
expiration = String.valueOf(minutes);
}
// Get password
EditText pwField = findViewById(R.id.share_password);
String sharePw = pwField.getText().toString();
StringBuilder sharedFilesPaths = new StringBuilder();
for (int i = 0; i < files.length; i++){
String filePath = java.net.URLDecoder.decode(new URL(f[i].full_url).getPath(), "UTF-8");
sharedFilesPaths.append("\"").append(filePath).append("\"");
if (i < files.length - 1){
sharedFilesPaths.append(",");
}
}
// Build JSON body
String jsonBody = format("{\"k\":\"%s\",\"vp\":[%s],\"pw\":\"%s\",\"exp\":\"%s\",\"perms\":[\"read\"]}",
key.toString(), sharedFilesPaths, sharePw, expiration);
URL apiUrl = new URL(shareApiUrl);
HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain");
if (password != null)
conn.setRequestProperty("PW", password);
byte[] body = jsonBody.getBytes(StandardCharsets.UTF_8);
conn.setFixedLengthStreamingMode(body.length);
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(body);
os.flush();
int rc = conn.getResponseCode();
if (rc >= 300) {
Log.w("me.ocv.partyup", "Share creation failed: " + rc);
conn.disconnect();
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = br.readLine();
conn.disconnect();
// Parse response: "created share: https://..."
if (response != null && response.startsWith("created share: "))
share_url = response.substring(15);
} catch (Exception ex) {
Log.w("me.ocv.partyup", "Share creation error: " + ex.toString());
}
}
void onsuccess() {
String msg = "✅ 👍\n\nCompleted successfully";
if (files != null) {
if (files.length == 1 && share_url == null) {
msg += "\n\n" + files[0].share_url;
} else if (share_url != null) {
msg += "\n\n" + share_url;
} else {
msg += "\n\n" + files.length + " files OK";
}
}
show_msg(msg);
((TextView) findViewById(R.id.upper_info)).setGravity(Gravity.CENTER);
String act = prefs.getString("on_up_ok", "menu");
if (act != null && !act.equals("menu")) {
if (act.equals("copy"))
copylink();
else if (act.equals("share"))
sharelink();
else
Toast.makeText(getApplicationContext(), "Upload OK", Toast.LENGTH_SHORT).show();
finishAndRemoveTask();
return;
}
findViewById(R.id.progbar).setVisibility(View.GONE);
findViewById(R.id.share_settings).setVisibility(View.GONE);
findViewById(R.id.successbuttons).setVisibility(View.VISIBLE);
Button btn = (Button) findViewById(R.id.btnExit);
btn.setOnClickListener(v -> finishAndRemoveTask());
Button vcopy = (Button) findViewById(R.id.btnCopyLink);
Button vqrcode = (Button) findViewById(R.id.btnQrCode);
Button vshare = (Button) findViewById(R.id.btnShareLink);
if (files == null) {
vcopy.setVisibility(View.GONE);
vshare.setVisibility(View.GONE);
return;
}
vcopy.setOnClickListener(v -> copylink());
vshare.setOnClickListener(v -> sharelink());
vqrcode.setOnClickListener(view -> showQr());
if (files.length > 1 && share_url == null){
vshare.setVisibility(View.GONE);
vqrcode.setVisibility(View.GONE);
}
}
void copylink() {
if (files == null)
return;
String links = "";
if (share_url != null) {
links = share_url;
} else {
for (F file : files)
links += file.share_url + "\n";
}
ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData cd = ClipData.newPlainText("copyparty upload", links);
cb.setPrimaryClip(cd);
Toast.makeText(getApplicationContext(), "Upload OK -- Link copied", Toast.LENGTH_SHORT).show();
}
void sharelink() {
if (files == null)
return;
String link_to_share;
if (share_url != null) {
link_to_share = share_url;
} else if (files.length > 1) {
return;
} else {
link_to_share = files[0].share_url;
}
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
send.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
send.putExtra(Intent.EXTRA_SUBJECT, "Uploaded file");
send.putExtra(Intent.EXTRA_TEXT, link_to_share);
//startActivity(Intent.createChooser(send, "Share file link"));
Intent view = new Intent(Intent.ACTION_VIEW);
view.setData(Uri.parse(link_to_share));
Intent i = Intent.createChooser(send, "Share file link");
i.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{view});
startActivity(i);
}
void showQr(){
if (share_qr == null){
String url_to_share;
if (share_url != null)
url_to_share = share_url;
else
url_to_share = files[0].full_url;
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
int size = 256;
BitMatrix bitMatrix = qrCodeWriter.encode(url_to_share, BarcodeFormat.QR_CODE, size, size);
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
bitmap.setPixel(x, y,
bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
share_qr = bitmap;
} catch (WriterException e) {
throw new RuntimeException(e);
}
}
AlertDialog.Builder ImageDialog = new AlertDialog.Builder(XferActivity.this);
ImageView shownImage = new ImageView(XferActivity.this);
shownImage.setImageBitmap(share_qr);
shownImage.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
shownImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
shownImage.setAdjustViewBounds(true);
ImageDialog.setView(shownImage);
ImageDialog.show();
}
}
| java | MIT | d2e1d7c32ac02f7f663a02f28c0020e3c3b35557 | 2026-01-05T02:40:42.627768Z | false |
9001/party-up | https://github.com/9001/party-up/blob/d2e1d7c32ac02f7f663a02f28c0020e3c3b35557/app/src/main/java/me/ocv/partyup/SettingsActivity.java | app/src/main/java/me/ocv/partyup/SettingsActivity.java | package me.ocv.partyup;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.MenuItem;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Toast;
import androidx.preference.EditTextPreference;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getString("on_up_ok", "menu").equals("menu")) {
SharedPreferences.Editor ed = prefs.edit();
ed.putString("on_up_ok", "menu");
ed.commit();
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
EditTextPreference passwd = findPreference("server_password");
if (passwd != null) {
passwd.setSummaryProvider(preference -> {
if (passwd.getText() == null || passwd.getText().isEmpty()) {
return "Password is not set";
} else {
return "Click to change password";
}
});
passwd.setOnBindEditTextListener(editText -> {
editText.setInputType(
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD
);
editText.setOnLongClickListener(view -> {
editText.setInputType(
InputType.TYPE_CLASS_TEXT
);
editText.setOnLongClickListener(null);
return true;
});
});
passwd.setDialogMessage("If server has enabled login using usernames, input \"<username>:<password>\" \n\n Long press to reveal the password");
}
EditTextPreference linkExp = findPreference("link_expiration");
if (linkExp != null) {
// Use SummaryProvider for dynamic summary
linkExp.setSummaryProvider(preference -> {
String value = ((EditTextPreference) preference).getText();
return getExpSummaryText(value);
});
// Validate on change
linkExp.setOnPreferenceChangeListener((preference, newValue) -> {
String value = (String) newValue;
String error = validateExpiration(value);
if (error != null) {
Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
return false;
}
return true;
});
}
}
private String validateExpiration(String value) {
if (value == null || value.trim().isEmpty())
return null; // Empty is valid (never expires)
value = value.trim().toLowerCase();
if (value.matches("^\\d+[mhd]?$"))
return null; // Valid format
return "Invalid format. Use: 30m, 2h, 7d, or empty for never";
}
private String getExpSummaryText(String value) {
if (value == null || value.trim().isEmpty())
return "Never expires";
value = value.trim().toLowerCase();
if (!value.matches("^\\d+[mhd]?$"))
return "Invalid format";
char unit = value.charAt(value.length() - 1);
int num;
if (Character.isDigit(unit)) {
num = Integer.parseInt(value);
unit = 'm';
} else {
num = Integer.parseInt(value.substring(0, value.length() - 1));
}
switch (unit) {
case 'm': return num + " minute" + (num != 1 ? "s" : "");
case 'h': return num + " hour" + (num != 1 ? "s" : "");
case 'd': return num + " day" + (num != 1 ? "s" : "");
default: return "Never expires";
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| java | MIT | d2e1d7c32ac02f7f663a02f28c0020e3c3b35557 | 2026-01-05T02:40:42.627768Z | false |
9001/party-up | https://github.com/9001/party-up/blob/d2e1d7c32ac02f7f663a02f28c0020e3c3b35557/app/src/androidTest/java/me/ocv/partyup/ExampleInstrumentedTest.java | app/src/androidTest/java/me/ocv/partyup/ExampleInstrumentedTest.java | package me.ocv.partyup;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("me.ocv.partyup", appContext.getPackageName());
}
} | java | MIT | d2e1d7c32ac02f7f663a02f28c0020e3c3b35557 | 2026-01-05T02:40:42.627768Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-transport/src/main/java/org/tinylcy/RpcResponse.java | buddha-transport/src/main/java/org/tinylcy/RpcResponse.java | package org.tinylcy;
/**
* Created by chenyangli.
*/
public class RpcResponse implements BasicMessage {
private Long requestId;
private Throwable error;
private Object result;
public Long getRequestId() {
return requestId;
}
public void setRequestId(Long requestId) {
this.requestId = requestId;
}
public Throwable getError() {
return error;
}
public void setError(Throwable error) {
this.error = error;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
@Override
public String toString() {
return "RpcResponse{" +
"requestId='" + requestId + '\'' +
", error=" + error +
", result=" + result +
'}';
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-transport/src/main/java/org/tinylcy/RpcRequest.java | buddha-transport/src/main/java/org/tinylcy/RpcRequest.java | package org.tinylcy;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by chenyangli.
*/
public class RpcRequest implements BasicMessage {
private static final AtomicLong REQUEST_ID = new AtomicLong(1L);
private Long requestId;
private String className;
private String methodName;
private Class<?>[] paramTypes;
private Object[] params;
public RpcRequest() {
this.requestId = REQUEST_ID.getAndIncrement();
}
public RpcRequest(String className, String methodName,
Class<?>[] paramTypes, Object[] params) {
this.requestId = REQUEST_ID.getAndIncrement();
this.className = className;
this.methodName = methodName;
this.paramTypes = paramTypes;
this.params = params;
}
public Long getRequestId() {
return requestId;
}
public void setRequestId(Long requestId) {
this.requestId = requestId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Class<?>[] getParamTypes() {
return paramTypes;
}
public void setParamTypes(Class<?>[] paramTypes) {
this.paramTypes = paramTypes;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
@Override
public String toString() {
return "RpcRequest{" +
"requestId='" + requestId + '\'' +
", className='" + className + '\'' +
", methodName='" + methodName + '\'' +
", paramTypes=" + Arrays.toString(paramTypes) +
", params=" + Arrays.toString(params) +
'}';
}
} | java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-transport/src/main/java/org/tinylcy/BasicMessage.java | buddha-transport/src/main/java/org/tinylcy/BasicMessage.java | package org.tinylcy;
/**
* Created by chenyangli.
*/
public interface BasicMessage {
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/test/java/org/tinylcy/fastjson/FastJsonSerializerTest.java | buddha-serialization/src/test/java/org/tinylcy/fastjson/FastJsonSerializerTest.java | package org.tinylcy.fastjson;
import org.junit.Test;
import org.tinylcy.RpcRequest;
import java.util.Arrays;
/**
* Created by chenyangli.
*/
public class FastJsonSerializerTest {
@Test
public void fastJsonTest() {
RpcRequest request = new RpcRequest("org.tinylcy.services.IHelloService", "hello",
new Class<?>[]{String.class}, new Object[]{"chenyang"});
FastJsonSerializer serializer = new FastJsonSerializer();
byte[] bytes = serializer.serialize(request);
System.out.println(Arrays.toString(bytes));
RpcRequest r = serializer.deserialize(bytes, RpcRequest.class);
System.out.println(r);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/test/java/org/tinylcy/kryo/KryoSerializerTest.java | buddha-serialization/src/test/java/org/tinylcy/kryo/KryoSerializerTest.java | package org.tinylcy.kryo;
import org.junit.Test;
import org.tinylcy.RpcRequest;
import java.util.Arrays;
/**
* Created by chenyangli.
*/
public class KryoSerializerTest {
@Test
public void kryoTest() {
RpcRequest request = new RpcRequest("org.tinylcy.services.IHelloService", "hello",
new Class<?>[]{String.class}, new Object[]{"chenyang"});
KryoSerializer serializer = new KryoSerializer();
byte[] bytes = serializer.serialize(request);
System.out.println(Arrays.toString(bytes));
RpcRequest r = (RpcRequest) serializer.deserialize(bytes, RpcRequest.class);
System.out.println(r);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/main/java/org/tinylcy/SerializerFactory.java | buddha-serialization/src/main/java/org/tinylcy/SerializerFactory.java | package org.tinylcy;
import java.util.ServiceLoader;
/**
* Created by chenyangli.
*/
public class SerializerFactory {
/**
* SPI
*
* @return
*/
public static Serializer load() {
return ServiceLoader.load(Serializer.class).iterator().next();
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/main/java/org/tinylcy/Serializer.java | buddha-serialization/src/main/java/org/tinylcy/Serializer.java | package org.tinylcy;
/**
* Created by chenyangli.
*/
public interface Serializer {
byte[] serialize(Object object);
<T> T deserialize(byte[] bytes, Class<T> clazz);
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/main/java/org/tinylcy/fastjson/FastJsonSerializer.java | buddha-serialization/src/main/java/org/tinylcy/fastjson/FastJsonSerializer.java | package org.tinylcy.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.tinylcy.Serializer;
/**
* Created by chenyangli.
*/
public class FastJsonSerializer implements Serializer {
public byte[] serialize(Object object) {
byte[] bytes = JSON.toJSONBytes(object, SerializerFeature.SortField);
return bytes;
}
/**
* Be careful: using fastjson v1.2.7(now v1.2.17) cannot deserialize the object with class fields.
*
* @param bytes
* @param clazz
* @return
*/
public <T> T deserialize(byte[] bytes, Class<T> clazz) {
T result = JSON.parseObject(bytes, clazz, Feature.SortFeidFastMatch);
return result;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-serialization/src/main/java/org/tinylcy/kryo/KryoSerializer.java | buddha-serialization/src/main/java/org/tinylcy/kryo/KryoSerializer.java | package org.tinylcy.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.tinylcy.Serializer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Created by chenyangli.
*/
public class KryoSerializer implements Serializer {
public byte[] serialize(Object object) {
Kryo kryo = new Kryo();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Output output = new Output(baos);
kryo.writeObject(output, object);
output.flush();
output.close();
byte[] bytes = baos.toByteArray();
try {
baos.flush();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
public <T> T deserialize(byte[] bytes, Class<T> clazz) {
Kryo kryo = new Kryo();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
Input input = new Input(bais);
T result = kryo.readObject(input, clazz);
input.close();
return result;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-codec/src/main/java/org/tinylcy/RpcRequestCodec.java | buddha-codec/src/main/java/org/tinylcy/RpcRequestCodec.java | package org.tinylcy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import java.util.List;
/**
* Created by chenyangli.
*/
public class RpcRequestCodec extends ByteToMessageCodec<RpcRequest> {
@Override
protected void encode(ChannelHandlerContext context, RpcRequest request, ByteBuf byteBuf)
throws Exception {
Serializer serializer = SerializerFactory.load();
byte[] bytes = serializer.serialize(request);
int len = bytes.length;
byteBuf.writeInt(len);
byteBuf.writeBytes(bytes);
}
@Override
protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list)
throws Exception {
if (byteBuf.readableBytes() < 4) {
return;
}
int len = byteBuf.readInt();
if (byteBuf.readableBytes() < len) {
throw new RuntimeException("Insufficient bytes to be read, expected: " + len);
}
byte[] bytes = new byte[len];
byteBuf.readBytes(bytes);
Serializer serializer = SerializerFactory.load();
Object object = serializer.deserialize(bytes, RpcRequest.class);
list.add(object);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.