text
stringlengths 7
1.01M
|
|---|
package org.jetbrains.annotations;
import java.lang.annotation.*;
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE_USE})
public @interface NotNull {
String value() default "";
Class<? extends Exception> exception() default Exception.class;
}
|
package net.minecraft.client.gui;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.context.ParsedArgument;
import com.mojang.brigadier.context.SuggestionContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestion;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.renderer.Rectangle2d;
import net.minecraft.client.resources.I18n;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.util.IReorderingProcessor;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector2f;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponentUtils;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class CommandSuggestionHelper {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(\\s+)");
private static final Style EMPTY_ERROR_STYLE = Style.EMPTY.setFormatting(TextFormatting.RED);
private static final Style EMPTY_PASS_STYLE = Style.EMPTY.setFormatting(TextFormatting.GRAY);
private static final List<Style> COMMAND_COLOR_STYLES = Stream.of(TextFormatting.AQUA, TextFormatting.YELLOW, TextFormatting.GREEN, TextFormatting.LIGHT_PURPLE, TextFormatting.GOLD).map(Style.EMPTY::setFormatting).collect(ImmutableList.toImmutableList());
private final Minecraft mc;
private final Screen screen;
private final TextFieldWidget inputField;
private final FontRenderer font;
private final boolean commandsOnly;
private final boolean hasCursor;
private final int minAmountRendered;
private final int maxAmountRendered;
private final boolean isChat;
private final int color;
private final List<IReorderingProcessor> exceptionList = Lists.newArrayList();
private int x;
private int width;
private ParseResults<ISuggestionProvider> parseResults;
private CompletableFuture<com.mojang.brigadier.suggestion.Suggestions> suggestionsFuture;
private CommandSuggestionHelper.Suggestions suggestions;
private boolean autoSuggest;
private boolean isApplyingSuggestion;
public CommandSuggestionHelper(Minecraft mc, Screen screen, TextFieldWidget inputField, FontRenderer font, boolean commandsOnly, boolean hasCursor, int minAmountRendered, int maxAmountRendered, boolean isChat, int color) {
this.mc = mc;
this.screen = screen;
this.inputField = inputField;
this.font = font;
this.commandsOnly = commandsOnly;
this.hasCursor = hasCursor;
this.minAmountRendered = minAmountRendered;
this.maxAmountRendered = maxAmountRendered;
this.isChat = isChat;
this.color = color;
inputField.setTextFormatter(this::getParsedSuggestion);
}
public void shouldAutoSuggest(boolean autoSuggest) {
this.autoSuggest = autoSuggest;
if (!autoSuggest) {
this.suggestions = null;
}
}
public boolean onKeyPressed(int keyCode, int scanCode, int modifiers) {
if (this.suggestions != null && this.suggestions.onKeyPressed(keyCode, scanCode, modifiers)) {
return true;
} else if (this.screen.getListener() == this.inputField && keyCode == 258) {
this.updateSuggestions(true);
return true;
} else {
return false;
}
}
public boolean onScroll(double delta) {
return this.suggestions != null && this.suggestions.onScroll(MathHelper.clamp(delta, -1.0D, 1.0D));
}
public boolean onClick(double mouseX, double mouseY, int mouseButton) {
return this.suggestions != null && this.suggestions.onClick((int)mouseX, (int)mouseY, mouseButton);
}
public void updateSuggestions(boolean narrateFirstSuggestion) {
if (this.suggestionsFuture != null && this.suggestionsFuture.isDone()) {
com.mojang.brigadier.suggestion.Suggestions suggestions = this.suggestionsFuture.join();
if (!suggestions.isEmpty()) {
int i = 0;
for(Suggestion suggestion : suggestions.getList()) {
i = Math.max(i, this.font.getStringWidth(suggestion.getText()));
}
int j = MathHelper.clamp(this.inputField.func_195611_j(suggestions.getRange().getStart()), 0, this.inputField.func_195611_j(0) + this.inputField.getAdjustedWidth() - i);
int k = this.isChat ? this.screen.height - 12 : 72;
this.suggestions = new CommandSuggestionHelper.Suggestions(j, k, i, this.getSuggestions(suggestions), narrateFirstSuggestion);
}
}
}
private List<Suggestion> getSuggestions(com.mojang.brigadier.suggestion.Suggestions suggestions) {
String s = this.inputField.getText().substring(0, this.inputField.getCursorPosition());
int i = getLastWhitespace(s);
String s1 = s.substring(i).toLowerCase(Locale.ROOT);
List<Suggestion> list = Lists.newArrayList();
List<Suggestion> list1 = Lists.newArrayList();
for(Suggestion suggestion : suggestions.getList()) {
if (!suggestion.getText().startsWith(s1) && !suggestion.getText().startsWith("minecraft:" + s1)) {
list1.add(suggestion);
} else {
list.add(suggestion);
}
}
list.addAll(list1);
return list;
}
public void init() {
String s = this.inputField.getText();
if (this.parseResults != null && !this.parseResults.getReader().getString().equals(s)) {
this.parseResults = null;
}
if (!this.isApplyingSuggestion) {
this.inputField.setSuggestion((String)null);
this.suggestions = null;
}
this.exceptionList.clear();
StringReader stringreader = new StringReader(s);
boolean flag = stringreader.canRead() && stringreader.peek() == '/';
if (flag) {
stringreader.skip();
}
boolean flag1 = this.commandsOnly || flag;
int i = this.inputField.getCursorPosition();
if (flag1) {
CommandDispatcher<ISuggestionProvider> commanddispatcher = this.mc.player.connection.getCommandDispatcher();
if (this.parseResults == null) {
this.parseResults = commanddispatcher.parse(stringreader, this.mc.player.connection.getSuggestionProvider());
}
int j = this.hasCursor ? stringreader.getCursor() : 1;
if (i >= j && (this.suggestions == null || !this.isApplyingSuggestion)) {
this.suggestionsFuture = commanddispatcher.getCompletionSuggestions(this.parseResults, i);
this.suggestionsFuture.thenRun(() -> {
if (this.suggestionsFuture.isDone()) {
this.recompileSuggestions();
}
});
}
} else {
String s1 = s.substring(0, i);
int k = getLastWhitespace(s1);
Collection<String> collection = this.mc.player.connection.getSuggestionProvider().getPlayerNames();
this.suggestionsFuture = ISuggestionProvider.suggest(collection, new SuggestionsBuilder(s1, k));
}
}
private static int getLastWhitespace(String text) {
if (Strings.isNullOrEmpty(text)) {
return 0;
} else {
int i = 0;
for(Matcher matcher = WHITESPACE_PATTERN.matcher(text); matcher.find(); i = matcher.end()) {
}
return i;
}
}
private static IReorderingProcessor parseException(CommandSyntaxException exception) {
ITextComponent itextcomponent = TextComponentUtils.toTextComponent(exception.getRawMessage());
String s = exception.getContext();
return s == null ? itextcomponent.func_241878_f() : (new TranslationTextComponent("command.context.parse_error", itextcomponent, exception.getCursor(), s)).func_241878_f();
}
private void recompileSuggestions() {
if (this.inputField.getCursorPosition() == this.inputField.getText().length()) {
if (this.suggestionsFuture.join().isEmpty() && !this.parseResults.getExceptions().isEmpty()) {
int i = 0;
for(Entry<CommandNode<ISuggestionProvider>, CommandSyntaxException> entry : this.parseResults.getExceptions().entrySet()) {
CommandSyntaxException commandsyntaxexception = entry.getValue();
if (commandsyntaxexception.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.literalIncorrect()) {
++i;
} else {
this.exceptionList.add(parseException(commandsyntaxexception));
}
}
if (i > 0) {
this.exceptionList.add(parseException(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().create()));
}
} else if (this.parseResults.getReader().canRead()) {
this.exceptionList.add(parseException(Commands.func_227481_a_(this.parseResults)));
}
}
this.x = 0;
this.width = this.screen.width;
if (this.exceptionList.isEmpty()) {
this.applyFormattingToCommand(TextFormatting.GRAY);
}
this.suggestions = null;
if (this.autoSuggest && this.mc.gameSettings.autoSuggestCommands) {
this.updateSuggestions(false);
}
}
private void applyFormattingToCommand(TextFormatting formatting) {
CommandContextBuilder<ISuggestionProvider> commandcontextbuilder = this.parseResults.getContext();
SuggestionContext<ISuggestionProvider> suggestioncontext = commandcontextbuilder.findSuggestionContext(this.inputField.getCursorPosition());
Map<CommandNode<ISuggestionProvider>, String> map = this.mc.player.connection.getCommandDispatcher().getSmartUsage(suggestioncontext.parent, this.mc.player.connection.getSuggestionProvider());
List<IReorderingProcessor> list = Lists.newArrayList();
int i = 0;
Style style = Style.EMPTY.setFormatting(formatting);
for(Entry<CommandNode<ISuggestionProvider>, String> entry : map.entrySet()) {
if (!(entry.getKey() instanceof LiteralCommandNode)) {
list.add(IReorderingProcessor.fromString(entry.getValue(), style));
i = Math.max(i, this.font.getStringWidth(entry.getValue()));
}
}
if (!list.isEmpty()) {
this.exceptionList.addAll(list);
this.x = MathHelper.clamp(this.inputField.func_195611_j(suggestioncontext.startPos), 0, this.inputField.func_195611_j(0) + this.inputField.getAdjustedWidth() - i);
this.width = i;
}
}
private IReorderingProcessor getParsedSuggestion(String command, int maxLength) {
return this.parseResults != null ? getFinalSuggestion(this.parseResults, command, maxLength) : IReorderingProcessor.fromString(command, Style.EMPTY);
}
@Nullable
private static String getMatchedSuggestionText(String inputText, String suggestionText) {
return suggestionText.startsWith(inputText) ? suggestionText.substring(inputText.length()) : null;
}
private static IReorderingProcessor getFinalSuggestion(ParseResults<ISuggestionProvider> provider, String command, int maxLength) {
List<IReorderingProcessor> list = Lists.newArrayList();
int i = 0;
int j = -1;
CommandContextBuilder<ISuggestionProvider> commandcontextbuilder = provider.getContext().getLastChild();
for(ParsedArgument<ISuggestionProvider, ?> parsedargument : commandcontextbuilder.getArguments().values()) {
++j;
if (j >= COMMAND_COLOR_STYLES.size()) {
j = 0;
}
int k = Math.max(parsedargument.getRange().getStart() - maxLength, 0);
if (k >= command.length()) {
break;
}
int l = Math.min(parsedargument.getRange().getEnd() - maxLength, command.length());
if (l > 0) {
list.add(IReorderingProcessor.fromString(command.substring(i, k), EMPTY_PASS_STYLE));
list.add(IReorderingProcessor.fromString(command.substring(k, l), COMMAND_COLOR_STYLES.get(j)));
i = l;
}
}
if (provider.getReader().canRead()) {
int i1 = Math.max(provider.getReader().getCursor() - maxLength, 0);
if (i1 < command.length()) {
int j1 = Math.min(i1 + provider.getReader().getRemainingLength(), command.length());
list.add(IReorderingProcessor.fromString(command.substring(i, i1), EMPTY_PASS_STYLE));
list.add(IReorderingProcessor.fromString(command.substring(i1, j1), EMPTY_ERROR_STYLE));
i = j1;
}
}
list.add(IReorderingProcessor.fromString(command.substring(i), EMPTY_PASS_STYLE));
return IReorderingProcessor.func_242241_a(list);
}
public void drawSuggestionList(MatrixStack matrixStack, int mouseX, int mouseY) {
if (this.suggestions != null) {
this.suggestions.drawSuggestions(matrixStack, mouseX, mouseY);
} else {
int i = 0;
for(IReorderingProcessor ireorderingprocessor : this.exceptionList) {
int j = this.isChat ? this.screen.height - 14 - 13 - 12 * i : 72 + 12 * i;
AbstractGui.fill(matrixStack, this.x - 1, j, this.x + this.width + 1, j + 12, this.color);
this.font.func_238407_a_(matrixStack, ireorderingprocessor, (float)this.x, (float)(j + 2), -1);
++i;
}
}
}
public String getSuggestionMessage() {
return this.suggestions != null ? "\n" + this.suggestions.getCurrentSuggestionMessage() : "";
}
@OnlyIn(Dist.CLIENT)
public class Suggestions {
private final Rectangle2d suggestionRenderBox;
private final String originalInputText;
private final List<Suggestion> suggestions;
private int lowestDisplayedSuggestionIndex;
private int selectedIndex;
private Vector2f lastMousePosition = Vector2f.ZERO;
private boolean changeSelectionOnNextTabInput;
private int lastObtainedSuggestionMessageIndex;
private Suggestions(int x, int y, int width, List<Suggestion> suggestions, boolean narrateFirstSuggestion) {
int i = x - 1;
int j = CommandSuggestionHelper.this.isChat ? y - 3 - Math.min(suggestions.size(), CommandSuggestionHelper.this.maxAmountRendered) * 12 : y;
this.suggestionRenderBox = new Rectangle2d(i, j, width + 1, Math.min(suggestions.size(), CommandSuggestionHelper.this.maxAmountRendered) * 12);
this.originalInputText = CommandSuggestionHelper.this.inputField.getText();
this.lastObtainedSuggestionMessageIndex = narrateFirstSuggestion ? -1 : 0;
this.suggestions = suggestions;
this.selectSuggestion(0);
}
public void drawSuggestions(MatrixStack matrixStack, int mouseX, int mouseY) {
int i = Math.min(this.suggestions.size(), CommandSuggestionHelper.this.maxAmountRendered);
int j = -5592406;
boolean flag = this.lowestDisplayedSuggestionIndex > 0;
boolean flag1 = this.suggestions.size() > this.lowestDisplayedSuggestionIndex + i;
boolean flag2 = flag || flag1;
boolean flag3 = this.lastMousePosition.x != (float)mouseX || this.lastMousePosition.y != (float)mouseY;
if (flag3) {
this.lastMousePosition = new Vector2f((float)mouseX, (float)mouseY);
}
if (flag2) {
AbstractGui.fill(matrixStack, this.suggestionRenderBox.getX(), this.suggestionRenderBox.getY() - 1, this.suggestionRenderBox.getX() + this.suggestionRenderBox.getWidth(), this.suggestionRenderBox.getY(), CommandSuggestionHelper.this.color);
AbstractGui.fill(matrixStack, this.suggestionRenderBox.getX(), this.suggestionRenderBox.getY() + this.suggestionRenderBox.getHeight(), this.suggestionRenderBox.getX() + this.suggestionRenderBox.getWidth(), this.suggestionRenderBox.getY() + this.suggestionRenderBox.getHeight() + 1, CommandSuggestionHelper.this.color);
if (flag) {
for(int k = 0; k < this.suggestionRenderBox.getWidth(); ++k) {
if (k % 2 == 0) {
AbstractGui.fill(matrixStack, this.suggestionRenderBox.getX() + k, this.suggestionRenderBox.getY() - 1, this.suggestionRenderBox.getX() + k + 1, this.suggestionRenderBox.getY(), -1);
}
}
}
if (flag1) {
for(int i1 = 0; i1 < this.suggestionRenderBox.getWidth(); ++i1) {
if (i1 % 2 == 0) {
AbstractGui.fill(matrixStack, this.suggestionRenderBox.getX() + i1, this.suggestionRenderBox.getY() + this.suggestionRenderBox.getHeight(), this.suggestionRenderBox.getX() + i1 + 1, this.suggestionRenderBox.getY() + this.suggestionRenderBox.getHeight() + 1, -1);
}
}
}
}
boolean flag4 = false;
for(int l = 0; l < i; ++l) {
Suggestion suggestion = this.suggestions.get(l + this.lowestDisplayedSuggestionIndex);
AbstractGui.fill(matrixStack, this.suggestionRenderBox.getX(), this.suggestionRenderBox.getY() + 12 * l, this.suggestionRenderBox.getX() + this.suggestionRenderBox.getWidth(), this.suggestionRenderBox.getY() + 12 * l + 12, CommandSuggestionHelper.this.color);
if (mouseX > this.suggestionRenderBox.getX() && mouseX < this.suggestionRenderBox.getX() + this.suggestionRenderBox.getWidth() && mouseY > this.suggestionRenderBox.getY() + 12 * l && mouseY < this.suggestionRenderBox.getY() + 12 * l + 12) {
if (flag3) {
this.selectSuggestion(l + this.lowestDisplayedSuggestionIndex);
}
flag4 = true;
}
CommandSuggestionHelper.this.font.drawStringWithShadow(matrixStack, suggestion.getText(), (float)(this.suggestionRenderBox.getX() + 1), (float)(this.suggestionRenderBox.getY() + 2 + 12 * l), l + this.lowestDisplayedSuggestionIndex == this.selectedIndex ? -256 : -5592406);
}
if (flag4) {
Message message = this.suggestions.get(this.selectedIndex).getTooltip();
if (message != null) {
CommandSuggestionHelper.this.screen.renderTooltip(matrixStack, TextComponentUtils.toTextComponent(message), mouseX, mouseY);
}
}
}
public boolean onClick(int mouseX, int mouseY, int mouseButton) {
if (!this.suggestionRenderBox.contains(mouseX, mouseY)) {
return false;
} else {
int i = (mouseY - this.suggestionRenderBox.getY()) / 12 + this.lowestDisplayedSuggestionIndex;
if (i >= 0 && i < this.suggestions.size()) {
this.selectSuggestion(i);
this.applySuggestionToInput();
}
return true;
}
}
public boolean onScroll(double delta) {
int i = (int)(CommandSuggestionHelper.this.mc.mouseHelper.getMouseX() * (double)CommandSuggestionHelper.this.mc.getMainWindow().getScaledWidth() / (double)CommandSuggestionHelper.this.mc.getMainWindow().getWidth());
int j = (int)(CommandSuggestionHelper.this.mc.mouseHelper.getMouseY() * (double)CommandSuggestionHelper.this.mc.getMainWindow().getScaledHeight() / (double)CommandSuggestionHelper.this.mc.getMainWindow().getHeight());
if (this.suggestionRenderBox.contains(i, j)) {
this.lowestDisplayedSuggestionIndex = MathHelper.clamp((int)((double)this.lowestDisplayedSuggestionIndex - delta), 0, Math.max(this.suggestions.size() - CommandSuggestionHelper.this.maxAmountRendered, 0));
return true;
} else {
return false;
}
}
public boolean onKeyPressed(int keyCode, int scanCode, int modifiers) {
if (keyCode == 265) {
this.changeSelection(-1);
this.changeSelectionOnNextTabInput = false;
return true;
} else if (keyCode == 264) {
this.changeSelection(1);
this.changeSelectionOnNextTabInput = false;
return true;
} else if (keyCode == 258) {
if (this.changeSelectionOnNextTabInput) {
this.changeSelection(Screen.hasShiftDown() ? -1 : 1);
}
this.applySuggestionToInput();
return true;
} else if (keyCode == 256) {
this.clearSuggestions();
return true;
} else {
return false;
}
}
public void changeSelection(int change) {
this.selectSuggestion(this.selectedIndex + change);
int i = this.lowestDisplayedSuggestionIndex;
int j = this.lowestDisplayedSuggestionIndex + CommandSuggestionHelper.this.maxAmountRendered - 1;
if (this.selectedIndex < i) {
this.lowestDisplayedSuggestionIndex = MathHelper.clamp(this.selectedIndex, 0, Math.max(this.suggestions.size() - CommandSuggestionHelper.this.maxAmountRendered, 0));
} else if (this.selectedIndex > j) {
this.lowestDisplayedSuggestionIndex = MathHelper.clamp(this.selectedIndex + CommandSuggestionHelper.this.minAmountRendered - CommandSuggestionHelper.this.maxAmountRendered, 0, Math.max(this.suggestions.size() - CommandSuggestionHelper.this.maxAmountRendered, 0));
}
}
public void selectSuggestion(int index) {
this.selectedIndex = index;
if (this.selectedIndex < 0) {
this.selectedIndex += this.suggestions.size();
}
if (this.selectedIndex >= this.suggestions.size()) {
this.selectedIndex -= this.suggestions.size();
}
Suggestion suggestion = this.suggestions.get(this.selectedIndex);
CommandSuggestionHelper.this.inputField.setSuggestion(CommandSuggestionHelper.getMatchedSuggestionText(CommandSuggestionHelper.this.inputField.getText(), suggestion.apply(this.originalInputText)));
if (NarratorChatListener.INSTANCE.isActive() && this.lastObtainedSuggestionMessageIndex != this.selectedIndex) {
NarratorChatListener.INSTANCE.say(this.getCurrentSuggestionMessage());
}
}
public void applySuggestionToInput() {
Suggestion suggestion = this.suggestions.get(this.selectedIndex);
CommandSuggestionHelper.this.isApplyingSuggestion = true;
CommandSuggestionHelper.this.inputField.setText(suggestion.apply(this.originalInputText));
int i = suggestion.getRange().getStart() + suggestion.getText().length();
CommandSuggestionHelper.this.inputField.clampCursorPosition(i);
CommandSuggestionHelper.this.inputField.setSelectionPos(i);
this.selectSuggestion(this.selectedIndex);
CommandSuggestionHelper.this.isApplyingSuggestion = false;
this.changeSelectionOnNextTabInput = true;
}
private String getCurrentSuggestionMessage() {
this.lastObtainedSuggestionMessageIndex = this.selectedIndex;
Suggestion suggestion = this.suggestions.get(this.selectedIndex);
Message message = suggestion.getTooltip();
return message != null ? I18n.format("narration.suggestion.tooltip", this.selectedIndex + 1, this.suggestions.size(), suggestion.getText(), message.getString()) : I18n.format("narration.suggestion", this.selectedIndex + 1, this.suggestions.size(), suggestion.getText());
}
public void clearSuggestions() {
CommandSuggestionHelper.this.suggestions = null;
}
}
}
|
package org.apache.spark.ml.feature;
// no position
class Dot$ implements org.apache.spark.ml.feature.InteractableTerm, scala.Product, scala.Serializable {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final Dot$ MODULE$ = null;
public Dot$ () { throw new RuntimeException(); }
}
|
/*
* Copyright (c) 2012-2020 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.client.jdbc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.api.client.util.Strings;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.*;
import net.minidev.json.JSONObject;
import net.snowflake.client.core.ObjectMapperFactory;
import net.snowflake.client.core.SFException;
import net.snowflake.client.core.SFSession;
import net.snowflake.client.jdbc.telemetry.Telemetry;
import net.snowflake.client.jdbc.telemetry.TelemetryData;
import net.snowflake.client.jdbc.telemetry.TelemetryField;
import net.snowflake.client.jdbc.telemetryOOB.TelemetryEvent;
import net.snowflake.client.jdbc.telemetryOOB.TelemetryService;
/**
* @author mknister
* <p>This SnowflakeSQLLoggedException class extends the SnowflakeSQLException class to add OOB
* telemetry data for sql exceptions. Not all sql exceptions require OOB telemetry logging so
* the exceptions in this class should only be thrown if there is a need for logging the
* exception with OOB telemetry.
*/
public class SnowflakeSQLLoggedException extends SnowflakeSQLException {
/*
OOB telemetry instance
*/
private TelemetryService oobInstance = TelemetryService.getInstance();
/*
IB telemtry instance
*/
private Telemetry ibInstance = null;
private static final ObjectMapper mapper = ObjectMapperFactory.getObjectMapper();
/**
* Function to create a TelemetryEvent log from the JSONObject and exception and send it via OOB
* telemetry
*
* @param value JSONnode containing relevant information specific to the exception constructor
* that should be included in the telemetry data, such as sqlState or vendorCode
* @param ex The exception being thrown
*/
private void sendOutOfBandTelemetryMessage(JSONObject value, SnowflakeSQLLoggedException ex) {
TelemetryEvent.LogBuilder logBuilder = new TelemetryEvent.LogBuilder();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String stackTrace = sw.toString();
value.put("Stacktrace", stackTrace);
TelemetryEvent log =
logBuilder.withName("Exception: " + ex.getClass().getSimpleName()).withValue(value).build();
oobInstance.report(log);
}
/**
* Function to create a TelemetryClient log and send it via in-band telemetry
*
* @param value ObjectNode containing information specific to the exception constructor that
* should be included in the telemetry log, such as SQLState or reason for the error
* @param ex The exception being thrown
* @return true if in-band telemetry log sent successfully or false if it did not
*/
private Future<Boolean> sendInBandTelemetryMessage(
ObjectNode value, SnowflakeSQLLoggedException ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String stackTrace = sw.toString();
value.put("Stacktrace", stackTrace);
value.put("Exception", ex.getClass().getSimpleName());
ibInstance.addLogToBatch(new TelemetryData(value, System.currentTimeMillis()));
return ibInstance.sendBatchAsync();
}
/**
* Helper function to create JSONObject node for OOB telemetry log
*
* @param queryId
* @param reason
* @param SQLState
* @param vendorCode
* @param errorCode
* @return JSONObject with data about SQLException
*/
private JSONObject createOOBValue(
String queryId, String reason, String SQLState, int vendorCode, ErrorCode errorCode) {
JSONObject oobValue = new JSONObject();
if (!Strings.isNullOrEmpty(queryId)) {
oobValue.put("Query ID", queryId);
}
if (!Strings.isNullOrEmpty(SQLState)) {
oobValue.put("SQLState", SQLState);
}
if (vendorCode != -1) {
oobValue.put("Vendor Code", vendorCode);
}
if (errorCode != null) {
oobValue.put("Error Code", errorCode.toString());
}
if (!Strings.isNullOrEmpty(reason)) {
oobValue.put("reason", reason);
}
return oobValue;
}
/**
* Function to construct log data based on possible exception inputs and send data through in-band
* telemetry, or oob if in-band does not work
*
* @param queryId query ID if exists
* @param reason reason for the exception
* @param SQLState SQLState
* @param vendorCode vendor code
* @param errorCode error code
* @param session session object, which is needed to send in-band telemetry but not oob. Might be
* null, in which case oob is used.
*/
public void sendTelemetryData(
String queryId,
String reason,
String SQLState,
int vendorCode,
ErrorCode errorCode,
SFSession session) {
// if session is not null, try sending data using in-band telemetry
if (session != null) {
ibInstance = session.getTelemetryClient();
}
// if in-band instance is successfully created, compile sql exception data into an in-band
// telemetry log
if (ibInstance != null) {
ObjectNode ibValue = mapper.createObjectNode();
ibValue.put("type", TelemetryField.SQL_EXCEPTION.toString());
if (!Strings.isNullOrEmpty(queryId)) {
ibValue.put("Query ID", queryId);
}
if (!Strings.isNullOrEmpty(SQLState)) {
ibValue.put("SQLState", SQLState);
}
if (vendorCode != -1) {
ibValue.put("Vendor Code", vendorCode);
}
if (errorCode != null) {
ibValue.put("Error Code", errorCode.toString());
}
if (!Strings.isNullOrEmpty(reason)) {
ibValue.put("reason", reason);
}
// try to send in-band data asynchronously
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(
() -> {
boolean inBandSuccess;
Future<Boolean> sendInBand = sendInBandTelemetryMessage(ibValue, this);
// record whether in band telemetry message sent with boolean value inBandSuccess
try {
inBandSuccess = sendInBand.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
inBandSuccess = false;
}
// In-band failed so send OOB telemetry instead
if (!inBandSuccess) {
logger.debug(
"In-band telemetry message failed to send. Sending out-of-band message instead");
JSONObject oobValue =
createOOBValue(queryId, reason, SQLState, vendorCode, errorCode);
sendOutOfBandTelemetryMessage(oobValue, this);
}
});
}
// In-band is not possible so send OOB telemetry instead
else {
JSONObject oobValue = createOOBValue(queryId, reason, SQLState, vendorCode, errorCode);
sendOutOfBandTelemetryMessage(oobValue, this);
}
}
public SnowflakeSQLLoggedException(
String queryId, String reason, String SQLState, int vendorCode, SFSession session) {
super(queryId, reason, SQLState, vendorCode);
sendTelemetryData(queryId, reason, SQLState, vendorCode, null, session);
}
public SnowflakeSQLLoggedException(String SQLState, int vendorCode, SFSession session) {
super(SQLState, vendorCode);
sendTelemetryData(null, null, SQLState, vendorCode, null, session);
}
public SnowflakeSQLLoggedException(String reason, String SQLState, SFSession session) {
super(reason, SQLState);
sendTelemetryData(null, reason, SQLState, -1, null, session);
}
public SnowflakeSQLLoggedException(
String SQLState, int vendorCode, SFSession session, Object... params) {
super(SQLState, vendorCode, params);
String reason =
errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params);
sendTelemetryData(null, reason, SQLState, vendorCode, null, session);
}
public SnowflakeSQLLoggedException(
Throwable ex, ErrorCode errorCode, SFSession session, Object... params) {
super(ex, errorCode, params);
// add telemetry
String reason =
errorResourceBundleManager.getLocalizedMessage(
String.valueOf(errorCode.getMessageCode()), params);
sendTelemetryData(
null, reason, errorCode.getSqlState(), errorCode.getMessageCode(), errorCode, session);
}
public SnowflakeSQLLoggedException(
Throwable ex, String SQLState, int vendorCode, SFSession session, Object... params) {
super(ex, SQLState, vendorCode, params);
// add telemetry
String reason =
errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params);
sendTelemetryData(null, reason, SQLState, vendorCode, null, session);
}
public SnowflakeSQLLoggedException(ErrorCode errorCode, SFSession session, Object... params) {
super(errorCode, params);
// add telemetry
String reason =
errorResourceBundleManager.getLocalizedMessage(
String.valueOf(errorCode.getMessageCode()), params);
sendTelemetryData(null, reason, null, -1, errorCode, session);
}
public SnowflakeSQLLoggedException(SFException e, SFSession session) {
super(e);
// add telemetry
sendTelemetryData(null, null, null, -1, null, session);
}
public SnowflakeSQLLoggedException(String reason, SFSession session) {
super(reason);
sendTelemetryData(null, reason, null, -1, null, session);
}
}
|
package ru.kwanza.dbtool.orm.annotations;
/*
* #%L
* dbtool-orm
* %%
* Copyright (C) 2015 Kwanza
* %%
* 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.
* #L%
*/
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Описание отношения между сущностями вида <b>один-ко-многим</b>
*
* Как правило тим поля для данного отношения представляет собой коллекцию.
* <p/>
* Например:
* <pre>{@code @Entity(name="EntityA", table="entity_A")
* public class EntityA{
* @literal @IdField("id")
* private Long id;
* @literal @OneToMany(relationProperty="entityAId", relationClass=EntityB.class)
* private Collection<EntityB> entitiesB
* .....
* }
*
* @author Guzanov Alexander
* @literal @Entity(name="EntityB", table="entity_B")
* public class EntityB{
* .....
* @literal @Field("entity_a_id")
* private Long entityAId;
* .....
* }
* }</pre>
*
* Стоит заметить, что поля связи являются немутабельными: т.е для установки связей нужно создавать сущность или указывать поле ссылки.
* Пример:
* <pre>{@code @Entity(name="EntityA", table="entity_A")
* EntityB entityB = ...;
* EntityA entityA = ...;
*
* entityA.getEntitiesB().add(entityB);// don't work
* entityB.setEntityAId(entityA.getId()); // work
* }
* </pre>
*
* @see ru.kwanza.dbtool.orm.annotations.Association
* @see ru.kwanza.dbtool.orm.annotations.ManyToOne
* @see ru.kwanza.dbtool.orm.annotations.Condition
* @see ru.kwanza.dbtool.orm.annotations.GroupBy
* @author Guzanov Alexander
*/
@Retention(RUNTIME)
@Target({FIELD, METHOD})
public @interface OneToMany {
/**
* Имя свойства класса, которое используется для выборки связанной сущности. </br>
* Сущность с которой устанавливается связь определяются по типу свойства, к которому указана эта аннотация,</br>
* или свойство {@link #relationClass()}, если результатом выборки является коллекция
* @see ru.kwanza.dbtool.orm.annotations.OneToMany
*/
String relationProperty();
/**
* Тип связанной сущности.
*
* Значения атрибута указывается, если поле связи представляет собой коллекцию
* @see ru.kwanza.dbtool.orm.annotations.OneToMany
*/
Class relationClass() default Object.class;
}
|
/*
* 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.aliyuncs.retailadvqa_public.model.v20200515;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.retailadvqa_public.transform.v20200515.SendSmsResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class SendSmsResponse extends AcsResponse {
private String data;
private String errorCode;
private String errorDesc;
private Boolean success;
private String traceId;
private String requestId;
public String getData() {
return this.data;
}
public void setData(String data) {
this.data = data;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorDesc() {
return this.errorDesc;
}
public void setErrorDesc(String errorDesc) {
this.errorDesc = errorDesc;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getTraceId() {
return this.traceId;
}
public void setTraceId(String traceId) {
this.traceId = traceId;
}
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
@Override
public SendSmsResponse getInstance(UnmarshallerContext context) {
return SendSmsResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.sql.calcite.view;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import io.druid.server.security.Escalator;
import io.druid.sql.calcite.planner.DruidPlanner;
import io.druid.sql.calcite.planner.PlannerFactory;
import io.druid.sql.calcite.schema.DruidSchema;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeImpl;
import org.apache.calcite.schema.FunctionParameter;
import org.apache.calcite.schema.TableMacro;
import org.apache.calcite.schema.TranslatableTable;
import org.apache.calcite.schema.impl.ViewTable;
import java.util.List;
public class DruidViewMacro implements TableMacro
{
private final PlannerFactory plannerFactory;
private final Escalator escalator;
private final String viewSql;
public DruidViewMacro(final PlannerFactory plannerFactory, final Escalator escalator, final String viewSql)
{
this.plannerFactory = plannerFactory;
this.escalator = escalator;
this.viewSql = viewSql;
}
@Override
public TranslatableTable apply(final List<Object> arguments)
{
final RelDataType rowType;
try (final DruidPlanner planner = plannerFactory.createPlanner(null)) {
// Using an escalator here is a hack, but it's currently needed to get the row type. Ideally, some
// later refactoring would make this unnecessary, since there is no actual query going out herem.
rowType = planner.plan(viewSql, escalator.createEscalatedAuthenticationResult()).rowType();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
return new ViewTable(
null,
RelDataTypeImpl.proto(rowType),
viewSql,
ImmutableList.of(DruidSchema.NAME),
null
);
}
@Override
public List<FunctionParameter> getParameters()
{
return ImmutableList.of();
}
}
|
package net.jsunit.action;
import net.jsunit.InvalidBrowserIdException;
import net.jsunit.XmlRenderable;
import net.jsunit.model.BrowserResult;
public class ResultDisplayerAction extends JsUnitBrowserTestRunnerAction {
public static final String TRANSFORM = "transform";
private String id;
private BrowserResult result;
private Integer browserId;
private boolean browserIdInvalid;
public void setId(String id) {
this.id = id;
}
public void setBrowserId(Integer browserId) {
this.browserId = browserId;
}
public String execute() throws Exception {
if (id == null || browserId == null)
return ERROR;
try {
result = runner.findResultWithId(id, browserId);
} catch (InvalidBrowserIdException e) {
browserIdInvalid = true;
return ERROR;
}
return SUCCESS;
}
public XmlRenderable getXmlRenderable() {
if (result != null)
return result;
String message;
if (browserIdInvalid)
message = "Invalid Browser ID '" + browserId + "'";
else if (id != null && browserId != null)
message = "No Test Result has been submitted with ID '" + id + "' for browser ID '" + browserId + "'";
else
message = "A Test Result ID and a browser ID must both be given";
return new ErrorXmlRenderable(message);
}
}
|
package com.tns.system.classloaders.impl;
import com.tns.system.classloaders.ClassLoadersCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public enum ClassLoadersCollectionImpl implements ClassLoadersCollection {
INSTANCE;
private Set<ClassLoader> classLoaders = Collections.synchronizedSet(new HashSet<ClassLoader>());
@Override
public void addClassLoader(ClassLoader classLoader) {
if (classLoader == null) {
throw new RuntimeException("Provided class loader should not be null");
}
classLoaders.add(classLoader);
}
@Override
public Collection<ClassLoader> getClassLoadersCollection() {
return Collections.unmodifiableCollection(classLoaders);
}
}
|
package dev.kamko.lnu_ass.core.domain.user.view;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseStatus;
@Service
public class UserInfoService {
private final UserInfoRepository repo;
public UserInfoService(UserInfoRepository repo) {
this.repo = repo;
}
List<UserInfo> listAll() {
return repo.findAll();
}
@Transactional
void handleNew(UserInfo ui) {
repo.save(ui);
}
@Transactional
void markLogin(String id, LocalDateTime time) {
var ui = repo.findById(id)
.orElseThrow(() -> new UserNotFound(id));
ui.setLastLoginAt(time);
repo.save(ui);
}
@ResponseStatus(code = HttpStatus.NOT_FOUND)
static class UserNotFound extends RuntimeException {
public UserNotFound(String id) {
super("No UserInfo with id " + id + " found!");
}
}
}
|
package org.devocative.ares.service.terminal;
import org.devocative.ares.iservice.ITerminalConnectionService;
import org.devocative.demeter.iservice.task.DTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope("prototype")
@Component("arsCloseIdleConnectionsDTask")
public class CloseIdleConnectionsDTask extends DTask<Void> {
@Autowired
private ITerminalConnectionService terminalConnectionService;
@Override
public void init() {
}
@Override
public boolean canStart() {
return true;
}
@Override
public void execute() {
terminalConnectionService.closeIdleConnections();
}
@Override
public void cancel() throws Exception {
}
}
|
package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.File;
import java.io.Reader;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.FormattedTextParser;
import org.intermine.xml.full.Item;
/**
*
* @author
*/
public class RnaseqExperimentInfoConverter extends BioFileConverter
{
//
private static final String DATASET_TITLE = "RNAseq Experiment Info";
private static final String DATA_SOURCE_NAME = "RNAseq Experiment";
private static final Logger LOG = Logger.getLogger(RnaseqExperimentInfoConverter.class);
private Integer proteomeId = null;
/**
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public RnaseqExperimentInfoConverter(ItemWriter writer, Model model) {
super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
*
*
* {@inheritDoc}
*/
public void process(Reader reader) throws Exception {
File theFile = getCurrentFile();
//TODO if we want to process multiple organisms, makes sure we set
// the organism variable at this point.
if( !theFile.getName().endsWith(".info") ) {
LOG.info("Ignoring file " + theFile.getName() + ". Not a vcf sample info file.");
} else {
// one organism (at most) per file
String organismIdentifier = null;
if (proteomeId != null) {
Item org = createItem("Organism");
org.setAttribute("proteomeId",proteomeId.toString());
try {
store(org);
} catch (ObjectStoreException e) {
throw new BuildException("Cannot store organism: "+e.getMessage());
}
organismIdentifier = org.getIdentifier();
} else {
throw new BuildException("Proteome Id must be set for rna-seq experiment.");
}
Iterator<?> tsvIter;
try {
tsvIter = FormattedTextParser.parseTabDelimitedReader(reader);
} catch (Exception e) {
throw new BuildException("Cannot parse file: " + getCurrentFile(),e);
}
int ctr = 0;
while (tsvIter.hasNext() ) {
ctr++;
String[] fields = (String[]) tsvIter.next();
if (fields.length == 1 && fields[0].startsWith("#") ) {
// header field. Is there anything we want to do?
} else {
if (fields.length > 1) {
Item sample = createItem("RNAseqExperiment");
sample.setAttribute("name",fields[0]);
setIfNotNull(sample,"experimentGroup",fields[1]);
if (fields.length > 2) setIfNotNull(sample,"description",fields[2]);
if (fields.length > 3) setIfNotNull(sample,"url",fields[3]);
sample.setReference("organism",organismIdentifier);
try{
store(sample);
} catch (ObjectStoreException e) {
throw new BuildException("Cannot store rnaseq-experiment: "+e.getMessage());
}
}
}
if ((ctr%100000) == 0) {
LOG.info("Processed " + ctr + " lines...");
}
}
LOG.info("Processed " + ctr + " lines.");
}
}
void setIfNotNull(Item s,String field,String value) {
if (value != null && value.trim().length() > 0) {
s.setAttribute(field,value);
}
}
public void setProteomeId(String organism) {
try {
proteomeId = Integer.valueOf(organism);
} catch (NumberFormatException e) {
throw new RuntimeException("can't find integer value for: " + organism);
}
}
}
|
/**
* Copyright 2008 - 2015 The Loon Game Engine Authors
*
* 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.5
*/
package loon;
public interface Save {
interface Batch {
void setItem(String key, String data);
void removeItem(String key);
void commit();
}
public void setItem(String key, String data);
public void removeItem(String key);
public String getItem(String key);
public Batch startBatch();
public Iterable<String> keys();
public boolean isPersisted();
}
|
package com.hero.webview.webchromeclient;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import com.hero.webview.utils.WebConstants;
import com.hero.webview.widget.BaseWebView;
import com.hero.webview.widget.ProgressWebView;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
public class ProgressWebChromeClient extends WebChromeClient {
private ValueCallback<Uri[]> mFilePathCallback;
private Handler progressHandler;
private String mCameraPhotoPath;
public ProgressWebChromeClient(Handler progressHandler) {
this.progressHandler = progressHandler;
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (view instanceof ProgressWebView) {
if (!TextUtils.isEmpty(title)) {
HashMap<String, String> params = new HashMap<String, String>();
params.put(WebConstants.COMMAND_UPDATE_TITLE_PARAMS_TITLE, title);
((BaseWebView) view).post(WebConstants.COMMAND_UPDATE_TITLE, new Gson().toJson(params));
}
}
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
Message message = new Message();
if (newProgress == 100) {
message.obj = newProgress;
progressHandler.sendMessageDelayed(message, 200);
} else {
if (newProgress < 10) {
newProgress = 10;
}
message.obj = newProgress;
progressHandler.sendMessage(message);
}
super.onProgressChanged(view, newProgress);
}
@Override
public boolean onJsAlert(final WebView view, String url, String message, JsResult result) {
new AlertDialog.Builder(view.getContext())
.setTitle(android.R.string.dialog_alert_title)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
//按钮事件
Toast.makeText(view.getContext(), view.getContext().getString(android.R.string.ok) + " clicked.", Toast.LENGTH_LONG).show();
}
}).show();
//result.confirm();// 不加这行代码,会造成Alert劫持:Alert只会弹出一次,并且WebView会卡死
return true;
}
//For Android5.0+
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(webView.getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
((BaseWebView) webView).getWebViewCallBack().onShowFileChooser(takePictureIntent, mFilePathCallback);
return true;
}
/**
* More info this method can be found at
* http://developer.android.com/training/camera/photobasics.html
*
* @return
* @throws IOException
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
return imageFile;
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.i("consolemessage","consoleMessage="+consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
}
|
/**
* Copyright 2008 Jordi Hernández Sellés
*
* 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 net.jawr.web.resource.bundle.renderer;
import org.directwebremoting.impl.DefaultSecureIdGenerator;
/**
* This class adds a small script to pages, which is needed when integrating
* JAWR with DWR.
*
* @author Jordi Hernández Sellés
*/
public class DWRParamWriter {
private static final DefaultSecureIdGenerator ID_GENERATOR = new DefaultSecureIdGenerator();
private static boolean USE_DYNAMIC_SESSION_ID; // Should this evolve to an
// interceptor chain for the
// AbstractBundleLinkRenderer?
/**
* Adds a script with DWR needed params, including a generated ID that DWR
* needs.
*
* @param contextPath
* @param dwrPath
* @return
*/
public static StringBuffer buildRequestSpecificParams(String contextPath,
String dwrPath) {
StringBuffer sb = new StringBuffer(
"<script type=\"text/javascript\">if(!JAWR){var JAWR = {};};");
sb.append(buildDWRJSParams(contextPath, dwrPath));
sb.append("</script>").append("\n");
return sb;
}
public static StringBuffer buildDWRJSParams(String contextPath,
String dwrPath) {
StringBuffer sb = new StringBuffer(";");
sb.append("JAWR.jawr_dwr_path='");
sb.append(dwrPath).append("';");
if (USE_DYNAMIC_SESSION_ID)
sb.append("JAWR.dwr_scriptSessionId='")
.append(ID_GENERATOR.generate()).append("';");
sb.append("JAWR.app_context_path='").append(contextPath).append("';");
return sb;
}
/**
* Sets the flag indicating that we must yse the dynamic session ID
*
* @param useDynamicSessionId
* the flag to set
*/
public static void setUseDynamicSessionId(boolean useDynamicSessionId) {
DWRParamWriter.USE_DYNAMIC_SESSION_ID = useDynamicSessionId;
}
}
|
package com.ceiba.controlador;
import com.ceiba.usuario.consulta.ManejadorListarUsuariosEnvios;
import com.ceiba.usuario.modelo.dto.DtoUsuarioEnvio;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/envios")
@Api(tags={"Controlador consulta usuarios registrados"})
public class ConsultaControladorEnvio {
private final ManejadorListarUsuariosEnvios manejadorListarUsuariosEnvios;
public ConsultaControladorEnvio(ManejadorListarUsuariosEnvios manejadorListarUsuariosEnvios) {
this.manejadorListarUsuariosEnvios = manejadorListarUsuariosEnvios;
}
@GetMapping
@ApiOperation("Listar Usuarios")
public List<DtoUsuarioEnvio> listar() {
return this.manejadorListarUsuariosEnvios.ejecutar();
}
}
|
package org.nesc.ec.bigdata.job;
import com.alibaba.fastjson.JSONObject;
import org.nesc.ec.bigdata.common.util.KafkaAdmins;
import org.nesc.ec.bigdata.constant.Constants;
import org.nesc.ec.bigdata.constant.TopicConfig;
import org.nesc.ec.bigdata.model.ClusterInfo;
import org.nesc.ec.bigdata.model.TopicInfo;
import org.nesc.ec.bigdata.service.ClusterService;
import org.nesc.ec.bigdata.service.KafkaAdminService;
import org.nesc.ec.bigdata.service.TopicInfoService;
import org.nesc.ec.bigdata.service.ZKService;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.common.TopicPartitionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ExecutionException;
@Component
public class CollectTopicJob {
private static final Logger LOG = LoggerFactory.getLogger(CollectTopicJob.class);
@Autowired
ClusterService clusterService;
@Autowired
KafkaAdminService kafkaAdminService;
@Autowired
TopicInfoService topicInfoService;
@Autowired
ZKService zkService;
private Map<String, TopicInfo> dbTopicMap = new HashMap<>();
private Map<String,Map<String, TopicDescription>> descTopicMap = new HashMap<>();
private Map<String,Map<String, Config>> descConfigsMap = new HashMap<>();
/*
* 1.获取集群的topic信息,和topic表信息进行对比,集群中被删除的topic在topic表中删除
* 2.获取第一部分的数据,将topic表中没有的数据集群中有的数据写入表中
* **/
void collectionTopicData() {
Map<String,Set<String>> clusterTopicMap = topicDescripe();
Set<Long> delete = this.dbTopic(clusterTopicMap);
Map<String,Set<TopicInfo>> map = topicOpertion();
Set<TopicInfo> needInsert = map.getOrDefault(Constants.Operation.INSERT,new HashSet<>());
Set<TopicInfo> needUpdate = map.getOrDefault(Constants.Operation.UPDATE,new HashSet<>());
if(!delete.isEmpty()) {
topicInfoService.deleteByIds(delete);
}
if(!needInsert.isEmpty()) {
if(!topicInfoService.batchInsert(needInsert)) {
LOG.error("batch insert topic table faild,please check");
}
}
if(!needUpdate.isEmpty()) {
if(!topicInfoService.batchUpdate(needUpdate)) {
LOG.error("batch update topic table faild,please check");
}
}
}
private Map<String,Set<String>> topicDescripe(){
Map<String,Set<String>> clusterTopicMap = new HashMap<>();
List<ClusterInfo> clusters = clusterService.getTotalData();
clusters.forEach(cluster->{
KafkaAdmins kafkaAdmins = kafkaAdminService.getKafkaAdmins(cluster.getId().toString());
Map<String, TopicDescription> descTopics = null;
Map<String, Config> descConfigs = null;
try {
Set<String> topics = kafkaAdmins.listTopics();
clusterTopicMap.put(cluster.getId().toString(),topics);
descTopics = kafkaAdmins.descTopics(topics);
descConfigs = kafkaAdmins.descConfigs(topics);
}catch (InterruptedException | ExecutionException ignored) {
}finally {
descTopicMap.put(cluster.getId().toString(), descTopics);
descConfigsMap.put(cluster.getId().toString(), descConfigs);
}
});
return clusterTopicMap;
}
private Map<String, Set<TopicInfo>> topicOpertion(){
Map<String, Set<TopicInfo>> map = new HashMap<>();
Set<TopicInfo> needInsert = new HashSet<>();
Set<TopicInfo> needUpdate = new HashSet<>();
descTopicMap.forEach((clusterId,topicInfo)-> topicInfo.forEach((key, value)->{
List<TopicPartitionInfo> topicPartitionInfos = value.partitions();
int partion = !topicPartitionInfos.isEmpty()?topicPartitionInfos.size():0;
int nodeSize = !topicPartitionInfos.isEmpty()?(!topicPartitionInfos.get(0).replicas().isEmpty()?topicPartitionInfos.get(0).replicas().size():0):0;
String newKey = calacKey(clusterId,key);
Map<String, Config> topicDescrip = descConfigsMap.get(clusterId);
if(!dbTopicMap.containsKey(newKey)) {
TopicInfo tInfo = this.updateTTL(topicDescrip, clusterId, new TopicInfo(), key);
tInfo.setPartition(partion);
tInfo.setReplication((short)nodeSize);
tInfo.setTopicName(key);
tInfo.setClusterId(clusterId);
needInsert.add(tInfo);
}else {
//需要更新的topic
TopicInfo tInfo = this.updateTTL(topicDescrip,clusterId, dbTopicMap.get(newKey), key);
tInfo.setPartition(partion);
tInfo.setReplication((short)nodeSize);
needUpdate.add(tInfo);
}
}));
map.put(Constants.Operation.INSERT,needInsert);
map.put(Constants.Operation.UPDATE,needUpdate);
return map;
}
private Set<Long> dbTopic( Map<String,Set<String>> clusterTopicMap){
List<TopicInfo> topicInfos = topicInfoService.getTotalData();
Set<Long> result = new HashSet<>();
topicInfos.forEach(topic->{
String key = calacKey(topic.getCluster().getId().toString(),topic.getTopicName());
dbTopicMap.put(key, topic);
Set<String> topics = clusterTopicMap.get(topic.getCluster().getId().toString());
if( topics!=null && !topics.contains(topic.getTopicName())) {
result.add(topic.getId());
}
});
return result;
}
private TopicInfo updateTTL(Map<String, Config> topicDescrip,String clusterId,TopicInfo tInfo,String topicName) {
try {
if(topicDescrip!=null) {
Config con = topicDescrip.get(topicName);
con.entries().forEach(entry->{
if(TopicConfig.DELETE_RETENTION_MS.equalsIgnoreCase(entry.name())) {
long ttl = Long.parseLong(entry.value());
tInfo.setTtl(ttl>0?ttl:0);
}
});
}else {
JSONObject res = zkService.getZK(clusterId).descConfig(topicName);
if(res.containsKey(TopicConfig.DELETE_RETENTION_MS)) {
String ttlStr= res.getString(TopicConfig.DELETE_RETENTION_MS).trim();
long ttl = Long.parseLong(ttlStr);
tInfo.setTtl(ttl>0?ttl:0);
}else if(res.containsKey(TopicConfig.RETENTION_MS)){
String ttlStr= res.getString(TopicConfig.RETENTION_MS).trim();
long ttl = Long.parseLong(ttlStr);
tInfo.setTtl(ttl>0?ttl:0);
}else {
tInfo.setTtl(0L);
}
}
} catch (Exception e) {
LOG.error("topic collect update has error: "+clusterId+Constants.Symbol.Vertical_STR+topicName,e);
}
return tInfo;
}
private String calacKey(String clusterId,String topicName) {
return clusterId+"|"+topicName;
}
}
|
// Released under the MIT License.
package net.groboclown.retval.impl;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.groboclown.retval.Problem;
import net.groboclown.retval.RetNullable;
import net.groboclown.retval.RetVal;
import net.groboclown.retval.RetVoid;
import net.groboclown.retval.env.ReturnTypeFactoryDetection;
import static net.groboclown.retval.impl.CollectionUtil.copyNonNullValues;
/**
* Central handler for creating Ret* instances.
*/
public class RetGenerator {
private static ReturnTypeFactory INSTANCE;
static {
INSTANCE = ReturnTypeFactoryDetection.discoverReturnTypeFactory();
}
private RetGenerator() {
// No state, so no constructor.
}
/**
* Create a {@link RetNullable} instance with a value.
*
* @param value value to store in the return object.
* @param <T> type of the value.
* @return the return object.
*/
@Nonnull
public static <T> RetNullable<T> nullableOk(@Nullable final T value) {
return INSTANCE.createNullableOk(value);
}
/**
* Create a {@link RetNullable} instance with one or more problems.
*
* @param problems collection of problem values.
* @param <T> type of the value.
* @return the return object.
*/
@Nonnull
public static <T> RetNullable<T> nullableFromProblem(
@Nonnull final Collection<Problem> problems
) {
final List<Problem> clonedProblems = copyNonNullValues(problems);
if (clonedProblems.isEmpty()) {
throw new IllegalArgumentException(
"Problem return objects must have at least 1 problem");
}
return INSTANCE.createNullableFromProblems(clonedProblems);
}
/**
* Create a new RetVal instance that has a value and no problems.
*
* @param value non-null value.
* @param <T> type of the value.
* @return a RetVal containing the value.
* @throws NullPointerException if the value is null.
*/
@Nonnull
public static <T> RetVal<T> valOk(@Nonnull final T value) {
return INSTANCE.createValOk(Objects.requireNonNull(value, "ok value"));
}
/**
* Create a new RetVal instance that has errors.
*
* @param problems list of other problems to include in this value.
* @param <T> type of the value
* @return an error RetVal.
*/
@Nonnull
public static <T> RetVal<T> valFromProblem(@Nonnull final Collection<Problem> problems) {
final List<Problem> clonedProblems = copyNonNullValues(problems);
if (clonedProblems.isEmpty()) {
throw new IllegalArgumentException(
"Problem return objects must have at least 1 problem");
}
return INSTANCE.createValFromProblems(clonedProblems);
}
/**
* Return a void object with no problems.
*
* @return a no-problem void object.
*/
@Nonnull
public static RetVoid voidOk() {
return INSTANCE.createVoidOk();
}
/**
* Constructs a {@link RetVoid} instance with the collections of problems.
* This is optimized to reduce the memory load where easy. If the problem list is
* empty, then
*
* @param problems collection of problems
* @return a problem version of a void ret.
*/
@Nonnull
public static RetVoid voidFromProblem(@Nonnull final Collection<Problem> problems) {
final List<Problem> clonedProblems = copyNonNullValues(problems);
if (clonedProblems.isEmpty()) {
return voidOk();
}
return INSTANCE.createVoidFromProblems(clonedProblems);
}
/**
* Allows for querying the active return type factory. Primarily useful for unit tests or
* other systems that need runtime replacements of the type.
*
* @return the current return type factory instance.
*/
@Nonnull
public static ReturnTypeFactory getFactory() {
return INSTANCE;
}
/**
* Allows for replacing the active return type factory. Primarily useful for unit tests or
* other systems that need runtime replacements of the type.
*
* @param factory the new factory to use; must be non-null.
*/
public static void setFactory(@Nonnull final ReturnTypeFactory factory) {
INSTANCE = Objects.requireNonNull(factory, "factory");
}
}
|
package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Inject;
import controllers.authentication.AuthenticationAction;
import play.libs.Json;
import play.mvc.Result;
import play.mvc.With;
import services.crypto.CryptoManager;
import services.util.Util;
import static controllers.actionservices.LoginService.COOKIE_KEY_STRING_VALIDACAO;
import static controllers.actionservices.LoginService.JSON_KEY_ID;
import static controllers.actionservices.LoginService.USUARIO_SESSAO_KEY;
import static play.mvc.Controller.request;
import static play.mvc.Controller.session;
import static play.mvc.Results.ok;
public class Auth {
private final CryptoManager cm;
//injeta o CryptoManager singleton no controller via construtor
@Inject
public Auth(CryptoManager cm) {
this.cm = cm;
}
//Teste onde só pode obter musiquinhas se estiver logado
@With(AuthenticationAction.class)
public Result obterMusiquinhas() {
Util.log("obterMusiquinhas");
return ok("Pronto, obteve as musiquinhas pois estava logado");
}
//Vem a string de solicitacao de método via POST para. host/services. Essa string vem codificada com o CryptoManager
/*
{
metodo:login
params:{
login:gilianp@gmail.com
}
}
*/
//A Requisição de login possui uma validação diferente dos outros métodos pois a string de validação é gerada pelo próprio id, por isso precisa validar varias coisas.
public Result loginSecure() throws Exception {
//JsonNode jsonBody = request().body().asJson();
String requestCrypto = request().body().asText();
Util.log("loginSecure() requestCrypto: " + requestCrypto);
if (requestCrypto != null) {
String requestDescrypto = cm.decode(requestCrypto);
Util.log("requestDescrypto: " + requestDescrypto);
JsonNode js = Json.parse(requestDescrypto);
String idCrypto = js.get(JSON_KEY_ID).asText();
String idDescryptoSV = cm.decode(idCrypto);
Util.log("idCrypto: " + idCrypto);
Util.log("idDescryptoSV: " + idDescryptoSV);
//Como é a requisição de login, a string de validação é gerada pelo próprio id. Então separa a string de validação sem sequer valida-la para poder entao confrontar com uma correta que é gerada pelo id
String SVExtraida = cm.extrairStringValidacao(idDescryptoSV);
String idSemSV = cm.removerStringValidacao(idDescryptoSV);
Util.log("idDescryptoSV: "+ idDescryptoSV + ", idSemSV: " + idSemSV + ", SVExtraida: " + SVExtraida);
//Verifica se a string de validação extraida do id é válida
boolean SVExtraidaLoginValida = cm.validarSintaxeStringValidacao(SVExtraida);
Util.log("SVExtraidaLoginValida: " + SVExtraidaLoginValida);
//Agora aplica o algoritmo de geração de string de validação a partir de um id para ver se a string de validação enviada é a mesma.
String SVGeradaLogin = cm.gerarStringValidacaoFromString(idSemSV);
Util.log("SVGeradaLogin: " + SVGeradaLogin);
//Verifica se as strings de validação são iguais. Note que somente compara o char idx 0 e 1, pois o idx 2 é gerado aleatoriamente e já foi validado na sintaxe
boolean SVIguais = (SVGeradaLogin.charAt(0) == SVExtraida.charAt(0)) && (SVGeradaLogin.charAt(1) == SVExtraida.charAt(1));
Util.log("SVIguais: " + SVIguais);
//Pronto, a partir desse ponto, a string de validação enviada no id está correta e o id foi extraido, então faz os procedimentos normais de um login
//Verifica se o usuário existe no banco
boolean existeNoBanco = true;
//boolean existeNoBanco = false;
if (existeNoBanco){
/*//Teste lê cookies fora session
Cookie cookieSV = request().cookie(COOKIE_KEY_STRING_VALIDACAO);
Util.log("cookieSV: " + cookieSV);
if (cookieSV !=null) {
String SV = cookieSV.value();
String SVSign = Crypto.cookieSigner().asJava().sign(SV);
Util.log("SV: " + SV + ", SVSign: "+ SVSign);
}*/
//Teste lê a string de validação do SESSION cookie
String cookieSV = session(COOKIE_KEY_STRING_VALIDACAO);
Util.log("cookieSV: " + cookieSV);
if (cookieSV !=null) {
String cookieSVDecrypt = cm.decode(cookieSV);
Util.log("cookieSVDecrypt: " + cookieSVDecrypt);
}
//Cria uma nova string de validação para colocar nos cookies da session pois é assimetrico. Coloca ela com CryptoManager também!
String SVRetorno = cm.gerarStringValidacaoAleatoria();
String SVRetornoCrypto = cm.enconde(SVRetorno);
Util.log("SVRetorno: " + SVRetorno + ", SVRetornoCrypto: "+ SVRetornoCrypto);
session(USUARIO_SESSAO_KEY, idSemSV);
session(COOKIE_KEY_STRING_VALIDACAO, SVRetornoCrypto);
/*String cookieSign = Crypto.cookieSigner().asJava().sign("Oisouvalorsignet123aB");
//TODO Coloca SVRetorno nos cookies
Http.Cookie cookie = Http.Cookie.builder(COOKIE_KEY_STRING_VALIDACAO, cookieSign)
.withSecure(false).build();*/
// return ok("USUARIO EXISTE NO BANCO, LOGADO, SVRetorno: " + SVRetorno).withCookies(cookie);
return ok("USUARIO EXISTE NO BANCO, LOGADO, SVRetorno: " + SVRetorno);
}
else{
return ok("USUARIO NÃO EXISTE NO BANCO!");
}
} else {
return ok("ERRO, BODY ESTA NULL");
}
}
void novoLogin(){
//1 lê o login e senha da requisicao a services
//2 verifica no banco se existe esse login. Se nao existir retorna login invalido
//3 coloca o usuario (login) na session
//4 gera a string de 2 caracteres para validação de login, e coloca ela nos cookies
//5 retorna a resposta Ok para o usuario com o s cookies preenchidos (session e string de validacao)
}
//Basicamente toda requisição que modifica moedas, score e etc, é através de um POST para www.host/services.
//No body do POST é que vai um json indicando o método (login, changeMoedas, saveScore, etc) e parametros usados. Esse body vem codificado com o CryptoManager
//Nas outras requisições para adicionar ou remover moedas, o login é enviado através do sistema de session/cookie
//A quantidade de moedas é criptografada usando o CryptoManager
//host/services
void securedService(){
}
public Result login() {
/*String usuarioLogado = session(USUARIO_SESSAO_KEY);
Util.log("usuarioLogado: " + usuarioLogado);*/
JsonNode jsonBody = request().body().asJson();
Util.log("jsonBody: " + jsonBody);
if (jsonBody != null) {
String login = jsonBody.get("login").asText();
String senha = jsonBody.get("senha").asText();
Util.log("login: " + login + ", senha: " + senha);
//Busca o usuario no banco
boolean usuarioExisteBanco = true;
String msg;
if (usuarioExisteBanco) {
msg = "login com sucesso, usuario colocado na sessao";
session(USUARIO_SESSAO_KEY, login);
} else {
msg = "Usuário: " + login + ", não encontrado no banco";
}
return ok(msg);
} else {
return ok("ERRO, BODY NULL");
}
}
public Result logout() {
String usuarioLogado = session(USUARIO_SESSAO_KEY);
Util.log("logout() usuarioLogado: " + usuarioLogado);
String msg;
if (usuarioLogado != null){
session().remove(USUARIO_SESSAO_KEY);
msg = "Usuario deslogado com sucesso";
} else {
msg = "NÃO TINHA USUARIO NA SESSION";
}
Util.log("msg: " + msg);
return ok(msg);
}
}
|
/**
* ApplicationEvents generated by the mqtt module.
*/
package org.springframework.integration.mqtt.event;
|
package com.kakyireinc.covid19.activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.kakyireinc.covid19.BuildConfig;
import com.kakyireinc.covid19.R;
import com.kakyireinc.covid19.fragments.NationsFragment;
import com.kakyireinc.covid19.fragments.WorldFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
TextView version;
TextView facebook;
TextView instagram;
TextView twitter;
BottomNavigationView bottomNavigationView;
BottomSheetBehavior sheetBehavior;
View linearLayout;
InterstitialAd interstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
uninstallApp();
//initializing views
initializingViews();
changeFragment(new NationsFragment());
String versionNumber = "Version: " + BuildConfig.VERSION_NAME;
version.setText(versionNumber);
facebook.setOnClickListener(v -> loadSocialMedia(getString(R.string.facebook)));
instagram.setOnClickListener(v -> loadSocialMedia(getString(R.string.instagram)));
twitter.setOnClickListener(v -> loadSocialMedia(getString(R.string.twitter)));
}
private void initializingViews() {
linearLayout = findViewById(R.id.bottom_sheet);
sheetBehavior = BottomSheetBehavior.from(linearLayout);
sheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
twitter = findViewById(R.id.twitter_follow);
instagram = findViewById(R.id.instagram_follow);
facebook = findViewById(R.id.facebook_follow);
version = findViewById(R.id.app_version);
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.bottom_nations) {
changeFragment(new NationsFragment());
return true;
} else if (id == R.id.bottom_world) {
changeFragment(new WorldFragment());
return true;
}
return false;
}
private void changeFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_info) {
showHideBottomSheet();
}
return true;
}
//checking bottom sheet behavior
private void showHideBottomSheet() {
if (sheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED) {
sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else {
sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
//method for loading social media
private void loadSocialMedia(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
Intent uninstallIntent;
//check if old version is installed
private void uninstallApp() {
uninstallIntent = getPackageManager().getLaunchIntentForPackage("com.kakyireinc.covid_19");
if (uninstallIntent != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Uninstalled Old Version")
.setMessage(Html.fromHtml("Old version of <b>COVID-19</b> detected.<br> Please <b>Uninstall</b> "))
.setPositiveButton("Uninstall", (dialog, which) -> {
Uri packageToRemove = Uri.parse("package:com.kakyireinc.covid_19");
uninstallIntent = new Intent(Intent.ACTION_DELETE, packageToRemove);
startActivity(uninstallIntent);
})
.setNegativeButton("Cancel", (dialog, which) -> finish());
builder.create()
.show();
}
}
}
|
package com.huaweicloud.sdk.roma.v2.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** UpdateTopicAccessPolicyReq */
public class UpdateTopicAccessPolicyReq {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "topics")
private List<UpdateTopicAccessPolicyTopicsObject> topics = null;
public UpdateTopicAccessPolicyReq withTopics(List<UpdateTopicAccessPolicyTopicsObject> topics) {
this.topics = topics;
return this;
}
public UpdateTopicAccessPolicyReq addTopicsItem(UpdateTopicAccessPolicyTopicsObject topicsItem) {
if (this.topics == null) {
this.topics = new ArrayList<>();
}
this.topics.add(topicsItem);
return this;
}
public UpdateTopicAccessPolicyReq withTopics(Consumer<List<UpdateTopicAccessPolicyTopicsObject>> topicsSetter) {
if (this.topics == null) {
this.topics = new ArrayList<>();
}
topicsSetter.accept(this.topics);
return this;
}
/** 策略列表。
*
* @return topics */
public List<UpdateTopicAccessPolicyTopicsObject> getTopics() {
return topics;
}
public void setTopics(List<UpdateTopicAccessPolicyTopicsObject> topics) {
this.topics = topics;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UpdateTopicAccessPolicyReq updateTopicAccessPolicyReq = (UpdateTopicAccessPolicyReq) o;
return Objects.equals(this.topics, updateTopicAccessPolicyReq.topics);
}
@Override
public int hashCode() {
return Objects.hash(topics);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UpdateTopicAccessPolicyReq {\n");
sb.append(" topics: ").append(toIndentedString(topics)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package ca.mohawk.lab7;
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);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.bytecode;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* ClassGenerator
*/
public final class ClassGenerator {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0);
private static final String SIMPLE_NAME_TAG = "<init>";
private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<ClassLoader, ClassPool>(); //ClassLoader - ClassPool
private ClassPool mPool;
private CtClass mCtc;
private String mClassName;
private String mSuperClass;
private Set<String> mInterfaces;
private List<String> mFields;
private List<String> mConstructors;
private List<String> mMethods;
private Map<String, Method> mCopyMethods; // <method desc,method instance>
private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance>
private boolean mDefaultConstructor = false;
private ClassGenerator() {
}
private ClassGenerator(ClassPool pool) {
mPool = pool;
}
public static ClassGenerator newInstance() {
return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader()));
}
public static ClassGenerator newInstance(ClassLoader loader) {
return new ClassGenerator(getClassPool(loader));
}
public static boolean isDynamicClass(Class<?> cl) {
return ClassGenerator.DC.class.isAssignableFrom(cl);
}
public static ClassPool getClassPool(ClassLoader loader) {
if (loader == null) {
return ClassPool.getDefault();
}
ClassPool pool = POOL_MAP.get(loader);
if (pool == null) {
pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
POOL_MAP.put(loader, pool);
}
return pool;
}
private static String modifier(int mod) {
StringBuilder modifier = new StringBuilder();
if (Modifier.isPublic(mod)) {
modifier.append("public");
}
if (Modifier.isProtected(mod)) {
modifier.append("protected");
}
if (Modifier.isPrivate(mod)) {
modifier.append("private");
}
if (Modifier.isStatic(mod)) {
modifier.append(" static");
}
if (Modifier.isVolatile(mod)) {
modifier.append(" volatile");
}
return modifier.toString();
}
public String getClassName() {
return mClassName;
}
public ClassGenerator setClassName(String name) {
mClassName = name;
return this;
}
public ClassGenerator addInterface(String cn) {
if (mInterfaces == null) {
mInterfaces = new HashSet<String>();
}
mInterfaces.add(cn);
return this;
}
public ClassGenerator addInterface(Class<?> cl) {
return addInterface(cl.getName());
}
public ClassGenerator setSuperClass(String cn) {
mSuperClass = cn;
return this;
}
public ClassGenerator setSuperClass(Class<?> cl) {
mSuperClass = cl.getName();
return this;
}
public ClassGenerator addField(String code) {
if (mFields == null) {
mFields = new ArrayList<String>();
}
mFields.add(code);
return this;
}
public ClassGenerator addField(String name, int mod, Class<?> type) {
return addField(name, mod, type, null);
}
public ClassGenerator addField(String name, int mod, Class<?> type, String def) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' ');
sb.append(name);
if (def != null && def.length() > 0) {
sb.append('=');
sb.append(def);
}
sb.append(';');
return addField(sb.toString());
}
public ClassGenerator addMethod(String code) {
if (mMethods == null) {
mMethods = new ArrayList<String>();
}
mMethods.add(code);
return this;
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) {
return addMethod(name, mod, rt, pts, null, body);
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets,
String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addMethod(sb.toString());
}
public ClassGenerator addMethod(Method m) {
addMethod(m.getName(), m);
return this;
}
public ClassGenerator addMethod(String name, Method m) {
String desc = name + ReflectUtils.getDescWithoutMethodName(m);
addMethod(':' + desc);
if (mCopyMethods == null) {
mCopyMethods = new ConcurrentHashMap<String, Method>(8);
}
mCopyMethods.put(desc, m);
return this;
}
public ClassGenerator addConstructor(String code) {
if (mConstructors == null) {
mConstructors = new LinkedList<String>();
}
mConstructors.add(code);
return this;
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) {
return addConstructor(mod, pts, null, body);
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addConstructor(sb.toString());
}
public ClassGenerator addConstructor(Constructor<?> c) {
String desc = ReflectUtils.getDesc(c);
addConstructor(":" + desc);
if (mCopyConstructors == null) {
mCopyConstructors = new ConcurrentHashMap<String, Constructor<?>>(4);
}
mCopyConstructors.put(desc, c);
return this;
}
public ClassGenerator addDefaultConstructor() {
mDefaultConstructor = true;
return this;
}
public ClassPool getClassPool() {
return mPool;
}
public Class<?> toClass() {
return toClass(ClassHelper.getClassLoader(ClassGenerator.class),
getClass().getProtectionDomain());
}
public Class<?> toClass(ClassLoader loader, ProtectionDomain pd) {
if (mCtc != null) {
mCtc.detach();
}
long id = CLASS_NAME_COUNTER.getAndIncrement();
try {
CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass);
if (mClassName == null) {
mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers())
? ClassGenerator.class.getName() : mSuperClass + "$sc") + id;
}
mCtc = mPool.makeClass(mClassName);
if (mSuperClass != null) {
mCtc.setSuperclass(ctcs);
}
mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag.
if (mInterfaces != null) {
for (String cl : mInterfaces) {
mCtc.addInterface(mPool.get(cl));
}
}
if (mFields != null) {
for (String code : mFields) {
mCtc.addField(CtField.make(code, mCtc));
}
}
if (mMethods != null) {
for (String code : mMethods) {
if (code.charAt(0) == ':') {
mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))),
code.substring(1, code.indexOf('(')), mCtc, null));
} else {
mCtc.addMethod(CtNewMethod.make(code, mCtc));
}
}
}
if (mDefaultConstructor) {
mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));
}
if (mConstructors != null) {
for (String code : mConstructors) {
if (code.charAt(0) == ':') {
mCtc.addConstructor(CtNewConstructor
.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null));
} else {
String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $.
mCtc.addConstructor(
CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc));
}
}
}
saveClassToFile(mCtc, mClassName);
return mCtc.toClass(loader, pd);
} catch (RuntimeException e) {
throw e;
} catch (NotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (CannotCompileException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private void saveClassToFile(CtClass ctClass,String mClassName){
try {
byte[] bytes = ctClass.toBytecode();
FileOutputStream fileOutputStream = new FileOutputStream(
new File("/Users/yzf/IdeaProjects/amateur/incubator-dubbo/dubbo-common/src/main/resources/javassist/"+mClassName+".class"));
fileOutputStream.write(bytes);
fileOutputStream.close();
} catch (IOException e) {
log.error("error_ClassGenerator class保存至文件错误");
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
}
}
public void release() {
if (mCtc != null) {
mCtc.detach();
}
if (mInterfaces != null) {
mInterfaces.clear();
}
if (mFields != null) {
mFields.clear();
}
if (mMethods != null) {
mMethods.clear();
}
if (mConstructors != null) {
mConstructors.clear();
}
if (mCopyMethods != null) {
mCopyMethods.clear();
}
if (mCopyConstructors != null) {
mCopyConstructors.clear();
}
}
private CtClass getCtClass(Class<?> c) throws NotFoundException {
return mPool.get(c.getName());
}
private CtMethod getCtMethod(Method m) throws NotFoundException {
return getCtClass(m.getDeclaringClass())
.getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m));
}
private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException {
return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c));
}
public static interface DC {
} // dynamic class tag interface.
}
|
package org.lenteja.jdbc.txproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.lenteja.jdbc.DataAccesFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TransactionalServiceProxyfier implements InvocationHandler {
static final Logger LOG = LoggerFactory.getLogger(TransactionalServiceProxyfier.class);
final Object target;
final DataAccesFacade facade;
protected TransactionalServiceProxyfier(Object target, DataAccesFacade facade) {
this.target = target;
this.facade = facade;
}
@SuppressWarnings("unchecked")
public static <T> T proxyfy(DataAccesFacade facade, T target, Class<? super T> serviceInterface) {
return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[] { serviceInterface },
new TransactionalServiceProxyfier(target, facade));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Method m;
TransactionalMethod anno = method.getAnnotation(TransactionalMethod.class);
if (anno == null) {
m = target.getClass().getMethod(method.getName(), method.getParameterTypes());
anno = m.getAnnotation(TransactionalMethod.class);
}
if (anno == null) {
return method.invoke(target, args);
} else if (anno.propagation() == EPropagation.NONE) {
return method.invoke(target, args);
} else if (anno.propagation() == EPropagation.CREATE_OR_REUSE) {
if (facade.isValidTransaction()) {
return method.invoke(target, args);
} else {
return executeInTransaction(method, args, anno.readOnly());
}
} else if (anno.propagation() == EPropagation.NEW) {
return executeInTransaction(method, args, anno.readOnly());
} else {
throw new RuntimeException(anno.propagation().name());
}
}
public Object executeInTransaction(Method method, Object[] args, boolean readOnly)
throws IllegalAccessException, InvocationTargetException, Exception {
if (readOnly) {
facade.begin();
try {
return method.invoke(target, args);
} finally {
facade.rollback();
}
} else {
facade.begin();
try {
Object r = method.invoke(target, args);
facade.commit();
return r;
} catch (Exception e) {
facade.rollback();
throw e;
}
}
}
}
|
/**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client;
public class ApiextensionsAPIGroupExtensionAdapter extends APIGroupExtensionAdapter<ApiextensionsAPIGroupClient> {
@Override
protected String getAPIGroupName() {
return "apiextension";
}
@Override
public Class<ApiextensionsAPIGroupClient> getExtensionType() {
return ApiextensionsAPIGroupClient.class;
}
@Override
protected ApiextensionsAPIGroupClient newInstance(Client client) {
return new ApiextensionsAPIGroupClient(client);
}
}
|
/*
* This file is part of WebScarab, an Open Web Application Security
* Project utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2004 Rogan Dawes
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package ch.csnc.extension.httpclient;
import java.security.cert.Certificate;
public class AliasCertificate {
private Certificate certificate;
private String alias;
AliasCertificate(Certificate certificate, String alias){
this.setCertificate(certificate);
this.setAlias(alias);
}
public void setCertificate(Certificate certificate) {
this.certificate = certificate;
}
public Certificate getCertificate() {
return certificate;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getAlias() {
return alias;
}
public String getName(){
String cn = getCN();
if(cn.length() == 0){
return getAlias();
}else{
return cn + " ["+getAlias()+"]";
}
}
public String getCN() {
String dn = getCertificate().toString();
int i = 0;
i = dn.indexOf("CN=");
if (i == -1) {
return null;
}
//get the remaining DN without CN=
dn = dn.substring(i + 3);
char[] dncs = dn.toCharArray();
for (i = 0; i < dncs.length; i++) {
if (dncs[i] == ',' && i > 0 && dncs[i - 1] != '\\') {
break;
}
}
return dn.substring(0, i);
}
}
|
/*-
* <<
* DBus
* ==
* Copyright (C) 2016 - 2019 Bridata
* ==
* 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.creditease.dbus.heartbeat.event.impl;
import com.alibaba.fastjson.JSON;
import com.creditease.dbus.heartbeat.container.AlarmResultContainer;
import com.creditease.dbus.heartbeat.container.HeartBeatConfigContainer;
import com.creditease.dbus.heartbeat.event.AbstractEvent;
import com.creditease.dbus.heartbeat.sinker.SinkerKafkaSource;
import com.creditease.dbus.heartbeat.sinker.SinkerMonitorNode;
import com.creditease.dbus.heartbeat.sinker.SinkerMonitorNodeManager;
import com.creditease.dbus.heartbeat.util.Constants;
import com.creditease.dbus.heartbeat.util.DateUtil;
import com.creditease.dbus.heartbeat.util.MsgUtil;
import com.creditease.dbus.heartbeat.vo.CommonConfigVo;
import com.creditease.dbus.heartbeat.vo.HeartBeatVo;
import com.creditease.dbus.heartbeat.vo.MonitorNodeVo;
import com.creditease.dbus.mail.DBusMailFactory;
import com.creditease.dbus.mail.IMail;
import com.creditease.dbus.mail.Message;
import org.apache.commons.lang.StringUtils;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class CheckSinkerHeartBeatEvent extends AbstractEvent {
private SinkerKafkaSource source = null;
private SinkerMonitorNodeManager monitorNodeManager = null;
private int checkAlarmInterval;
private long lastCheckAlarmTime;
private HashMap<String, SinkerMonitorNode> alarmNodes;
private HeartBeatVo hbConf = null;
private CommonConfigVo commonConfig = null;
private Map<String, Map<String, String>> heartBeatTimeoutConf = null;
// 最大报警次数
private int maxAlarmCnt = 0;
// 报警间隔, 超过alarm Ttl 可以再报
private long alarmTtl = 0;
private Map<String, Map<String, String>> additionalConf = null;
public CheckSinkerHeartBeatEvent(long interval) {
super(interval);
}
@Override
public void run() {
try {
init();
source = new SinkerKafkaSource();
List<String> list;
while (isRun.get()) {
try {
checkAlarmTime();
list = source.poll();
if (list == null) {
continue;
}
//yxorcl.YX_USER.T_CONNECTION_CHECK|1572508713387|1573456732417|948019030
list.forEach(s -> {
String key = s.substring(0, s.indexOf("|"));
int latencyMS = Integer.parseInt(s.substring(s.lastIndexOf("|") + 1));
monitorNodeManager.update(key, latencyMS);
});
} catch (Exception e) {
LOG.error("[sinker] {}", e.getMessage(), e);
}
}
} catch (Exception e) {
LOG.error("[sinker]", e);
} finally {
if (source != null) {
source.cleanUp();
source = null;
}
LOG.info("[sinker] exit.");
}
}
private void init() {
Set<MonitorNodeVo> nodes = HeartBeatConfigContainer.getInstance().getMonitorNodes();
this.monitorNodeManager = new SinkerMonitorNodeManager();
this.hbConf = HeartBeatConfigContainer.getInstance().getHbConf();
this.commonConfig = HeartBeatConfigContainer.getInstance().getConmmonConfig();
this.checkAlarmInterval = Integer.parseInt(commonConfig.getSinkerCheckAlarmInterval());
this.alarmNodes = new HashMap<>();
nodes.forEach(monitorNodeVo -> monitorNodeManager.add(String.format("%s.%s.%s", monitorNodeVo.getDsName(), monitorNodeVo.getSchema(), monitorNodeVo.getTableName())));
// 心跳超时补充配置
this.heartBeatTimeoutConf = new HashMap<>();
additionalConf = hbConf.getHeartBeatTimeoutAdditional();
if (additionalConf != null) {
for (Map.Entry<String, Map<String, String>> entry : additionalConf.entrySet()) {
HashMap<String, String> map = new HashMap<>();
map.put("startTime", entry.getValue().get("startTime"));
map.put("endTime", entry.getValue().get("endTime"));
map.put("heartBeatTimeout", entry.getValue().get("heartBeatTimeout"));
heartBeatTimeoutConf.put(StringUtils.replace(entry.getKey(), "/", "."), map);
}
} else {
additionalConf = new HashMap<>();
}
// 最大报警次数
maxAlarmCnt = hbConf.getMaxAlarmCnt();
// 报警间隔, 超过alarm Ttl 可以再报
alarmTtl = hbConf.getAlarmTtl();
}
private void checkAlarmTime() {
if ((System.currentTimeMillis() - lastCheckAlarmTime) > checkAlarmInterval) {
long heartBeatTimeout = hbConf.getHeartBeatTimeout();
Map<String, SinkerMonitorNode> sinkerMonitorMap = monitorNodeManager.getSinkerMonitorMap();
sinkerMonitorMap.forEach((key, sinkerMonitorNode) -> {
if (sinkerMonitorNode.isRunning()) {
boolean canFire = false;
//延迟时间 = 上一次sinker心跳延时时间 + 上次更新距离现在的时间差
long latencyMS = sinkerMonitorNode.getLatencyMS() + System.currentTimeMillis() - sinkerMonitorNode.getUpdateTime();
sinkerMonitorNode.setRealLatencyMS(latencyMS);
//报警成立条件,1.超时了,报警次数少于最大允许次数;2.超时了,报警次数大于等于最大允许次数,上次报警时间距离现在超过了报警间隔
if (latencyMS > heartBeatTimeout && (maxAlarmCnt < sinkerMonitorNode.getAlarmCount()
|| (maxAlarmCnt >= sinkerMonitorNode.getAlarmCount() && alarmTtl < System.currentTimeMillis() - sinkerMonitorNode.getLastAlarmTime()))) {
if (key.lastIndexOf(".") == -1) {
LOG.error("[sinker] error key {}", key);
return;
}
// 修正超时时间
Map<String, String> map = additionalConf.get(key.substring(0, key.lastIndexOf(".")));
if (map != null && DateUtil.isCurrentTimeInInterval(map.get("startTime"), map.get("endTime"))) {
if (latencyMS > Long.parseLong(map.get("heartBeatTimeout"))) {
alarmNodes.put(key, sinkerMonitorNode);
canFire = true;
}
} else {
alarmNodes.put(key, sinkerMonitorNode);
canFire = true;
}
//处理报警节点计数
if (canFire) {
LOG.info("[sinker] 表[{}]发生超时 ,超时时间:{},{}", key, DateUtil.diffDate(sinkerMonitorNode.getRealLatencyMS()), JSON.toJSONString(sinkerMonitorNode));
if (maxAlarmCnt < sinkerMonitorNode.getAlarmCount()) {
sinkerMonitorNode.setAlarmCount(sinkerMonitorNode.getTimeoutCnt() + 1);
} else {
sinkerMonitorNode.setAlarmCount(1);
}
sinkerMonitorNode.setTimeoutCnt(sinkerMonitorNode.getTimeoutCnt() + 1);
sinkerMonitorNode.setLastAlarmTime(System.currentTimeMillis());
}
} else {
sinkerMonitorNode.setTimeoutCnt(0);
}
}
});
LOG.info("[sinker] checkAlarmTime complete.");
this.lastCheckAlarmTime = System.currentTimeMillis();
}
if (!alarmNodes.isEmpty()) {
// 根据schema进行分组发邮件,防止一封邮件行数太多
ConcurrentMap<String, List<String>> schemas = alarmNodes.keySet().stream().collect(
Collectors.groupingByConcurrent(key -> key.substring(0, key.lastIndexOf("."))));
schemas.values().forEach(value -> sendEmail(value));
alarmNodes.clear();
}
}
private void sendEmail(List<String> value) {
String html = toHtml(value);
String adminEmail = hbConf.getAdminEmail();
String subject = "DBus Sinker超时报警 ";
String contents = MsgUtil.format(Constants.MAIL_SINKER_HEART_BEAT_NEW,
"超时报警",
DateUtil.convertLongToStr4Date(System.currentTimeMillis()),
IMail.ENV,
MsgUtil.format(AlarmResultContainer.getInstance().html(), html));
Message msg = new Message();
msg.setAddress(adminEmail);
msg.setContents(contents);
msg.setSubject(subject);
msg.setHost(hbConf.getAlarmMailSMTPAddress());
if (StringUtils.isNotBlank(hbConf.getAlarmMailSMTPPort()))
msg.setPort(Integer.valueOf(hbConf.getAlarmMailSMTPPort()));
msg.setUserName(hbConf.getAlarmMailUser());
msg.setPassword(hbConf.getAlarmMailPass());
msg.setFromAddress(hbConf.getAlarmSendEmail());
IMail mail = DBusMailFactory.build();
mail.send(msg);
}
public String toHtml(List<String> tables) {
Collections.sort(tables);
StringBuilder html = new StringBuilder();
tables.forEach(key -> {
SinkerMonitorNode sinkerMonitorNode = alarmNodes.get(key);
html.append("<tr bgcolor=\"#ffffff\">");
html.append(" <th align=\"left\">" + key + "</th>");
html.append(" <th align=\"right\">" + sinkerMonitorNode.getAlarmCount() + "</th>");
html.append(" <th align=\"right\">" + DateUtil.diffDate(sinkerMonitorNode.getRealLatencyMS()) + "</th>");
html.append(" <th align=\"right\">" + sinkerMonitorNode.getTimeoutCnt() + "</th>");
html.append("</tr>");
});
return html.toString();
}
private void sendEmail() {
String html = toHtml();
String adminEmail = hbConf.getAdminEmail();
String subject = "DBus Sinker超时报警 ";
String contents = MsgUtil.format(Constants.MAIL_SINKER_HEART_BEAT_NEW,
"超时报警",
DateUtil.convertLongToStr4Date(System.currentTimeMillis()),
IMail.ENV,
MsgUtil.format(AlarmResultContainer.getInstance().html(), html));
Message msg = new Message();
msg.setAddress(adminEmail);
msg.setContents(contents);
msg.setSubject(subject);
msg.setHost(hbConf.getAlarmMailSMTPAddress());
if (StringUtils.isNotBlank(hbConf.getAlarmMailSMTPPort()))
msg.setPort(Integer.valueOf(hbConf.getAlarmMailSMTPPort()));
msg.setUserName(hbConf.getAlarmMailUser());
msg.setPassword(hbConf.getAlarmMailPass());
msg.setFromAddress(hbConf.getAlarmSendEmail());
IMail mail = DBusMailFactory.build();
mail.send(msg);
}
public String toHtml() {
ArrayList<String> keys = new ArrayList<>(alarmNodes.keySet());
Collections.sort(keys);
StringBuilder html = new StringBuilder();
keys.forEach(key -> {
SinkerMonitorNode sinkerMonitorNode = alarmNodes.get(key);
html.append("<tr bgcolor=\"#ffffff\">");
html.append(" <th align=\"left\">" + key + "</th>");
html.append(" <th align=\"right\">" + sinkerMonitorNode.getAlarmCount() + "</th>");
html.append(" <th align=\"right\">" + DateUtil.diffDate(sinkerMonitorNode.getRealLatencyMS()) + "</th>");
html.append(" <th align=\"right\">" + sinkerMonitorNode.getTimeoutCnt() + "</th>");
html.append("</tr>");
});
return html.toString();
}
}
|
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.egeria.connectors.ibm.igc.repositoryconnector.mapping.entities;
import org.odpi.egeria.connectors.ibm.igc.clientlibrary.IGCVersionEnum;
import org.odpi.egeria.connectors.ibm.igc.repositoryconnector.mapping.classifications.TypeEmbeddedAttributeMapper_TabularColumn;
import org.odpi.egeria.connectors.ibm.igc.repositoryconnector.mapping.relationships.AttributeForSchemaMapper_RecordField;
/**
* Defines the mapping to the OMRS "TabularColumn" entity.
*/
public class TabularColumnMapper extends SchemaAttribute_Mapper {
private static class Singleton {
private static final TabularColumnMapper INSTANCE = new TabularColumnMapper();
}
public static TabularColumnMapper getInstance(IGCVersionEnum version) {
return Singleton.INSTANCE;
}
private TabularColumnMapper() {
// Start by calling the superclass's constructor to initialise the Mapper
super(
"data_file_field",
"Data File Field",
"TabularColumn"
);
// The list of properties that should be mapped
addSimplePropertyMapping("name", "displayName");
addSimplePropertyMapping("position", "position");
addSimplePropertyMapping("default_value", "defaultValueOverride");
// The list of relationships that should be mapped
addRelationshipMapper(AttributeForSchemaMapper_RecordField.getInstance(null));
// The list of classifications that should be mapped
addClassificationMapper(TypeEmbeddedAttributeMapper_TabularColumn.getInstance(null));
}
}
|
/*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.ui.swt.wizard.format.popup.chart;
import java.util.List;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.FontDefinition;
import org.eclipse.birt.chart.model.attribute.Text;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.composites.ExternalizedTextEditorComposite;
import org.eclipse.birt.chart.ui.swt.composites.FontDefinitionComposite;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext;
import org.eclipse.birt.chart.ui.swt.wizard.format.popup.AbstractPopupSheet;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
/**
* VisibilitySheet
*/
public class VisibilitySheet extends AbstractPopupSheet implements Listener
{
protected ExternalizedTextEditorComposite txtEmptyMsg;
protected Label lbTxtEmptyMsg;
protected Label lbFdcEmptyMsg;
protected FontDefinitionComposite fdcEmptyMsg;
protected Button btnAutoHide;
protected Button btnShowEmptyMsg;
public VisibilitySheet( String title, ChartWizardContext context )
{
super( title, context, false );
}
@Override
protected Composite getComponent( Composite parent )
{
Composite emptyMsgComp = new Composite( parent, SWT.NONE );
{
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
emptyMsgComp.setLayoutData( gd );
emptyMsgComp.setLayout( new GridLayout( 1, false ) );
}
org.eclipse.birt.chart.model.component.Label laEmptyMsg = getChart( ).getEmptyMessage( );
btnAutoHide = new Button( emptyMsgComp, SWT.RADIO );
{
btnAutoHide.setText( Messages.getString( "ChartSheetImpl.Button.AutoHide" ) ); //$NON-NLS-1$
GridData gd = new GridData( );
btnAutoHide.setLayoutData( gd );
btnAutoHide.setSelection( laEmptyMsg.isSetVisible( )
&& !laEmptyMsg.isVisible( ) );
btnAutoHide.addListener( SWT.Selection, this );
}
btnShowEmptyMsg = new Button( emptyMsgComp, SWT.RADIO );
{
btnShowEmptyMsg.setText( Messages.getString( "ChartSheetImpl.Button.ShowEmptyMsg" ) ); //$NON-NLS-1$
GridData gd = new GridData( );
btnShowEmptyMsg.setLayoutData( gd );
btnShowEmptyMsg.setSelection( laEmptyMsg.isSetVisible( )
&& laEmptyMsg.isVisible( ) );
btnShowEmptyMsg.addListener( SWT.Selection, this );
}
Composite cmpEmptyText = new Composite( emptyMsgComp, SWT.NONE );
{
GridData gd = new GridData( GridData.FILL_BOTH );
gd.horizontalIndent = 12;
cmpEmptyText.setLayoutData( gd );
cmpEmptyText.setLayout( new GridLayout( 2, false ) );
}
lbTxtEmptyMsg = new Label( cmpEmptyText, SWT.NONE );
lbTxtEmptyMsg.setText( Messages.getString( "ChartSheetImpl.Label.Text" ) ); //$NON-NLS-1$
List<String> keys = null;
if ( getContext( ).getUIServiceProvider( ) != null )
{
keys = getContext( ).getUIServiceProvider( )
.getRegisteredKeys( );
}
txtEmptyMsg = new ExternalizedTextEditorComposite( cmpEmptyText,
SWT.BORDER,
-1,
-1,
keys,
getContext( ).getUIServiceProvider( ),
laEmptyMsg.getCaption( ).getValue( ) );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = 200;
txtEmptyMsg.setLayoutData( gd );
txtEmptyMsg.addListener( this );
}
lbFdcEmptyMsg = new Label( cmpEmptyText, SWT.NONE );
lbFdcEmptyMsg.setText( Messages.getString( "ChartSheetImpl.Label.Font" ) ); //$NON-NLS-1$
fdcEmptyMsg = new FontDefinitionComposite( cmpEmptyText,
SWT.NONE,
getContext( ),
laEmptyMsg.getCaption( ).getFont( ),
laEmptyMsg.getCaption( ).getColor( ),
true );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = 200;
gd.grabExcessVerticalSpace = false;
fdcEmptyMsg.setLayoutData( gd );
fdcEmptyMsg.addListener( this );
}
updateEmptyMessageUIStates( );
}
return emptyMsgComp;
}
protected void updateEmptyMessageUIStates( )
{
boolean bEnabled = getChart( ).getEmptyMessage( ).isVisible( );
txtEmptyMsg.setEnabled( bEnabled );
fdcEmptyMsg.setEnabled( bEnabled );
lbTxtEmptyMsg.setEnabled( bEnabled );
lbFdcEmptyMsg.setEnabled( bEnabled );
}
public void handleEvent( Event event )
{
if ( event.widget == txtEmptyMsg )
{
getChart( ).getEmptyMessage( )
.getCaption( )
.setValue( txtEmptyMsg.getText( ) );
}
else if ( event.widget == btnAutoHide
|| event.widget == btnShowEmptyMsg )
{
getChart( ).getEmptyMessage( )
.setVisible( !btnAutoHide.getSelection( ) );
updateEmptyMessageUIStates( );
}
else if ( event.widget == fdcEmptyMsg )
{
Text caption = getChart( ).getEmptyMessage( ).getCaption( );
caption.setFont( (FontDefinition) ( (Object[]) event.data )[0] );
caption.setColor( (ColorDefinition) ( (Object[]) event.data )[1] );
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.weex.uitest.TC_AG;
import org.apache.weex.WXPageActivity;
import org.apache.weex.util.TestFlow;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;
public class AG_Margin_A_Margin_Top extends TestFlow {
public AG_Margin_A_Margin_Top() {
super(WXPageActivity.class);
}
@Before
public void setUp() throws InterruptedException {
super.setUp();
TreeMap testMap = new <String, Object> TreeMap();
testMap.put("testComponet", "AG_Margin");
testMap.put("testChildCaseInit", "AG_Margin_A_Margin_Top");
testMap.put("step1",new TreeMap(){
{
put("click", "10");
put("screenshot", "AG_Margin_A_Margin_Top_01_10");
}
});
testMap.put("step2",new TreeMap(){
{
put("click", "20");
put("screenshot", "AG_Margin_A_Margin_Top_02_20");
}
});
super.setTestMap(testMap);
}
@Test
public void doTest(){
super.testByTestMap();
}
}
|
// Copyright 2007 The Apache Software Foundation
//
// 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 org.apache.tapestry5.upload.integration;
import org.apache.tapestry5.test.AbstractIntegrationTestSuite;
import org.example.upload.pages.Start;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
/**
* . TODO: These tests wont work because Selenium cannot enter values for input type="file'
*/
public class UploadIntegrationTest extends AbstractIntegrationTestSuite
{
@BeforeTest
public void setupTargetFolder() throws IOException
{
File target = new File(Start.TARGET_DIR);
if (!target.exists())
{
target.mkdirs();
}
else
{
for (File file : target.listFiles())
{
file.delete();
}
}
}
@Test(enabled = false)
public void integration_test() throws Exception
{
open(BASE_URL);
File source = new File("test/data/upload.txt");
type("file", source.getCanonicalPath());
clickAndWait("//input[@value='Upload']");
}
}
|
package io.github.joaoh1.okzoomer.client.mixin;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import io.github.joaoh1.okzoomer.client.OkZoomerClientMod;
import io.github.joaoh1.okzoomer.client.config.OkZoomerConfigPojo;
import io.github.joaoh1.okzoomer.client.config.OkZoomerConfigPojo.FeaturesGroup.CinematicCameraOptions;
import io.github.joaoh1.okzoomer.client.config.OkZoomerConfigPojo.FeaturesGroup.ZoomModes;
import io.github.joaoh1.okzoomer.client.utils.ZoomUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.Mouse;
import net.minecraft.client.util.SmoothUtil;
//TODO - Comment this code better
//This mixin is responsible for the mouse-behavior-changing part of the zoom.
@Mixin(Mouse.class)
public class MouseMixin {
@Final
@Shadow
private MinecraftClient client;
@Shadow
private final SmoothUtil cursorXSmoother = new SmoothUtil();
@Shadow
private final SmoothUtil cursorYSmoother = new SmoothUtil();
@Shadow
private double cursorDeltaX;
@Shadow
private double cursorDeltaY;
@Shadow
private double eventDeltaWheel;
private final SmoothUtil cursorXZoomSmoother = new SmoothUtil();
private final SmoothUtil cursorYZoomSmoother = new SmoothUtil();
private double extractedE;
private double adjustedG;
//This mixin handles the "Reduce Sensitivity" option.
@ModifyVariable(at = @At(value = "FIELD", target = "Lnet/minecraft/client/Mouse;client:Lnet/minecraft/client/MinecraftClient;", ordinal = 2), method = "updateMouse()V", ordinal = 2)
private double applyReduceSensitivity(double g) {
double modifiedMouseSensitivity = this.client.options.mouseSensitivity;
if (OkZoomerConfigPojo.features.reduceSensitivity) {
if (ZoomUtils.zoomState) {
modifiedMouseSensitivity /= ZoomUtils.zoomDivisor;
}
}
double appliedMouseSensitivity = modifiedMouseSensitivity * 0.6 + 0.2;
g = appliedMouseSensitivity * appliedMouseSensitivity * appliedMouseSensitivity * 8.0;
this.adjustedG = g;
return g;
}
@Inject(at = @At(value = "INVOKE", target = "net/minecraft/client/Mouse.isCursorLocked()Z"), method = "updateMouse()V", locals = LocalCapture.CAPTURE_FAILHARD)
private void obtainCinematicCameraValues(CallbackInfo info, double d, double e) {
this.extractedE = e;
}
@ModifyVariable(at = @At(value = "FIELD", target = "Lnet/minecraft/client/Mouse;cursorDeltaX:D", ordinal = 3, shift = At.Shift.BEFORE), method = "updateMouse()V", ordinal = 1)
private double applyCinematicModeX(double l) {
if (!OkZoomerConfigPojo.features.cinematicCamera.equals(CinematicCameraOptions.OFF)) {
if (ZoomUtils.zoomState) {
if (this.client.options.smoothCameraEnabled) {
l = this.cursorXSmoother.smooth(this.cursorDeltaX * this.adjustedG, (this.extractedE * this.adjustedG));
this.cursorXZoomSmoother.clear();
} else {
l = this.cursorXZoomSmoother.smooth(this.cursorDeltaX * this.adjustedG, (this.extractedE * this.adjustedG));
}
if (OkZoomerConfigPojo.features.cinematicCamera.equals(CinematicCameraOptions.MULTIPLIED)) {
l *= OkZoomerConfigPojo.values.cinematicMultiplier;
}
} else {
this.cursorXZoomSmoother.clear();
}
}
return l;
}
@ModifyVariable(at = @At(value = "FIELD", target = "Lnet/minecraft/client/Mouse;cursorDeltaY:D", ordinal = 3, shift = At.Shift.BEFORE), method = "updateMouse()V", ordinal = 2)
private double applyCinematicModeY(double m) {
if (!OkZoomerConfigPojo.features.cinematicCamera.equals(CinematicCameraOptions.OFF)) {
if (ZoomUtils.zoomState) {
if (this.client.options.smoothCameraEnabled) {
m = this.cursorYSmoother.smooth(this.cursorDeltaY * this.adjustedG, (this.extractedE * this.adjustedG));
this.cursorYZoomSmoother.clear();
} else {
m = this.cursorYZoomSmoother.smooth(this.cursorDeltaY * this.adjustedG, (this.extractedE * this.adjustedG));
}
if (OkZoomerConfigPojo.features.cinematicCamera.equals(CinematicCameraOptions.MULTIPLIED)) {
m *= OkZoomerConfigPojo.values.cinematicMultiplier;
}
} else {
this.cursorYZoomSmoother.clear();
}
}
return m;
}
@Inject(at = @At(value = "FIELD", target = "Lnet/minecraft/client/Mouse;eventDeltaWheel:D", ordinal = 7), method = "onMouseScroll(JDD)V", cancellable = true)
private void zoomerOnMouseScroll(CallbackInfo info) {
if (OkZoomerConfigPojo.features.zoomScrolling && !ZoomUtils.disableZoomScrolling) {
if (OkZoomerConfigPojo.features.zoomMode.equals(ZoomModes.PERSISTENT)) {
if (!OkZoomerClientMod.zoomKeyBinding.isPressed()) {
return;
}
}
if (ZoomUtils.zoomState) {
if (this.eventDeltaWheel != 0.0) {
if (this.eventDeltaWheel > 0.0) {
ZoomUtils.changeZoomDivisor(true);
} else if (this.eventDeltaWheel < 0.0) {
ZoomUtils.changeZoomDivisor(false);
}
info.cancel();
}
}
}
}
}
|
/**
* Copyright 2010-2016 the original author or authors.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yunmel.db.dialect;
public interface Dialect {
/**
* is support offset feature
*
* @return
*/
public boolean supportsOffset();
/**
* Given a limit and an offset, apply the limit clause to the query.
*
* @param query The query to which to apply the limit.
* @param offset The offset of the limit
* @param limit The limit of the limit ;)
* @return The modified query statement with the limit applied.
*/
public String getLimitString(String query, int offset, int limit);
/**
* get count sql
* @param query
* @return
*/
public String getCountSql(String query);
/**
* get GUID sql
* @return
*/
public String getSelectGUIDString();
/**
* get Sequence Next Value sql
* @param tablename
* @return
*/
public String getSequenceNextValString(String tablename);
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.storage.to;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import com.cloud.agent.api.to.DataObjectType;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DataTO;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.offering.DiskOffering.DiskCacheMode;
import com.cloud.storage.Storage;
import com.cloud.storage.Volume;
public class VolumeObjectTO implements DataTO {
private String uuid;
private Volume.Type volumeType;
private DataStoreTO dataStore;
private String name;
private Long size;
private String path;
private Long volumeId;
private String vmName;
private long accountId;
private String chainInfo;
private Storage.ImageFormat format;
private Storage.ProvisioningType provisioningType;
private long id;
private Long deviceId;
private Long bytesReadRate;
private Long bytesWriteRate;
private Long iopsReadRate;
private Long iopsWriteRate;
private DiskCacheMode cacheMode;
private Hypervisor.HypervisorType hypervisorType;
public VolumeObjectTO() {
}
public VolumeObjectTO(VolumeInfo volume) {
uuid = volume.getUuid();
path = volume.getPath();
accountId = volume.getAccountId();
if (volume.getDataStore() != null) {
dataStore = volume.getDataStore().getTO();
} else {
dataStore = null;
}
vmName = volume.getAttachedVmName();
size = volume.getSize();
setVolumeId(volume.getId());
chainInfo = volume.getChainInfo();
volumeType = volume.getVolumeType();
name = volume.getName();
setId(volume.getId());
format = volume.getFormat();
provisioningType = volume.getProvisioningType();
bytesReadRate = volume.getBytesReadRate();
bytesWriteRate = volume.getBytesWriteRate();
iopsReadRate = volume.getIopsReadRate();
iopsWriteRate = volume.getIopsWriteRate();
cacheMode = volume.getCacheMode();
hypervisorType = volume.getHypervisorType();
setDeviceId(volume.getDeviceId());
}
public String getUuid() {
return uuid;
}
@Override
public String getPath() {
return path;
}
public Volume.Type getVolumeType() {
return volumeType;
}
@Override
public DataStoreTO getDataStore() {
return dataStore;
}
@Override
public Hypervisor.HypervisorType getHypervisorType() {
return hypervisorType;
}
public void setDataStore(DataStoreTO store) {
dataStore = store;
}
public void setDataStore(PrimaryDataStoreTO dataStore) {
this.dataStore = dataStore;
}
public String getName() {
return name;
}
public Long getSize() {
return size;
}
@Override
public DataObjectType getObjectType() {
return DataObjectType.VOLUME;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setName(String name) {
this.name = name;
}
public void setSize(long size) {
this.size = size;
}
public void setPath(String path) {
this.path = path;
}
public Long getVolumeId() {
return volumeId;
}
public void setVolumeId(Long volumeId) {
this.volumeId = volumeId;
}
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
public String getVmName() {
return vmName;
}
public void setVmName(String vmName) {
this.vmName = vmName;
}
public String getChainInfo() {
return chainInfo;
}
public void setChainInfo(String chainInfo) {
this.chainInfo = chainInfo;
}
@Override
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Storage.ImageFormat getFormat() {
return format;
}
public void setFormat(Storage.ImageFormat format) {
this.format = format;
}
public Storage.ProvisioningType getProvisioningType(){
return provisioningType;
}
public void setProvisioningType(Storage.ProvisioningType provisioningType){
this.provisioningType = provisioningType;
}
@Override
public String toString() {
return new StringBuilder("volumeTO[uuid=").append(uuid).append("|path=").append(path).append("|datastore=").append(dataStore).append("]").toString();
}
public void setBytesReadRate(Long bytesReadRate) {
this.bytesReadRate = bytesReadRate;
}
public Long getBytesReadRate() {
return bytesReadRate;
}
public void setBytesWriteRate(Long bytesWriteRate) {
this.bytesWriteRate = bytesWriteRate;
}
public Long getBytesWriteRate() {
return bytesWriteRate;
}
public void setIopsReadRate(Long iopsReadRate) {
this.iopsReadRate = iopsReadRate;
}
public Long getIopsReadRate() {
return iopsReadRate;
}
public void setIopsWriteRate(Long iopsWriteRate) {
this.iopsWriteRate = iopsWriteRate;
}
public Long getIopsWriteRate() {
return iopsWriteRate;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public void setCacheMode(DiskCacheMode cacheMode) {
this.cacheMode = cacheMode;
}
public DiskCacheMode getCacheMode() {
return cacheMode;
}
}
|
package com.vvt.crypto;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import com.vvt.async.AsyncCallback;
import com.vvt.async.NullListenerException;
import com.vvt.logger.FxLog;
/**
* @author Tanakharn
* @version 1.0
* @created 10-May-2010 5:29:44 PM
*
* 1st Refactoring: December 2011
* : adjust coding style,
* improve Threading by using AsyncCallback
*/
public class AESCipher extends AsyncCallback<AESCipherListener> {
//Debug Information
private static final String TAG = "AESCipher";
//Fileds
private static final int BUFFER_SIZE = 1024;
private static final IvParameterSpec CBC_SALT = new IvParameterSpec(
new byte[] { 7, 34, 56, 78, 90, 87, 65, 43, 12, 34, 56, 78, 123, 87, 65, 43 } );
/*
* Constants
*/
private static final int MODE_ENCRYPT = 1;
private static final int MODE_DECRYPT = 2;
private static final int CALL_BACK_ENCRYPT_ERROR = 1;
private static final int CALL_BACK_ENCRYPT_SUCCESS = 2;
private static final int CALL_BACK_DECRYPT_ERROR = 3;
private static final int CALL_BACK_DECRYPT_SUCCESS = 4;
private boolean mWorkInProgress;
private int mWorkingMode;
private SecretKey mKey;
private String mInputFilePath;
private String mOutputFilePath;
private AESCipherListener mListener;
/**
* Encrypt input file and store output cipher into output file.
* This operation accept only one request at a time.
* Call this method while doing previous request will return FALSE
*
* @param key secret key for encrypt - cannot be null.
* @param inputFilePath absolute path to input file - cannot be null.
* @param outputFilePath absolute path to output file - cannot be null.
* @param listener AESEncryptListener - null is allowed.
* @return TRUE if request is accepted, FALSE if previous request is pending.
*/
public synchronized boolean encrypt(SecretKey key, String inputFilePath, String outputFilePath, AESEncryptListener listener){
if(!mWorkInProgress){
mWorkInProgress = true;
FxLog.d(TAG, "!encrypt");
//validate input
if(key == null){
FxLog.e(TAG, "> encrypt # Secret Key cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Secret Key cannot be NULL");
}
if(inputFilePath == null){
FxLog.e(TAG, "> encrypt # Input file path cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Input file path cannot be NULL");
}
if(outputFilePath == null){
FxLog.e(TAG, "> encrypt # Output file path cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Output file path cannot be NULL");
}
// set parameters
mKey = key;
mInputFilePath = inputFilePath;
mOutputFilePath = outputFilePath;
mListener = listener;
mWorkingMode = MODE_ENCRYPT;
//grab caller Thread
if(listener != null){
try {
addAsyncCallback(listener);
} catch (NullListenerException e) {
// unchecked
FxLog.w(TAG, "> compress # NullListenerException");
}
}
// start executor
Executor executor = new Executor();
executor.setPriority(Thread.MIN_PRIORITY);
executor.start();
return true;
}else{
FxLog.e(TAG, "> encrypt # Previous request is in progress, skip incoming request");
return false;
}
}
/**
* Decipher input file and store output plain text into output file.
* This operation accept only one request at a time.
* Call this method while doing previous request will return FALSE.
*
* @param key secret key for decrypt - cannot be null.
* @param inputFilePath absolute path to input cipher file - cannot be null.
* @param outputFilePath absolute path to output plain text file - cannot be null.
* @param listener AESDecryptListener - null is allowed.
* @return TRUE if request is accepted, FALSE if previous request is pending.
*/
public synchronized boolean decrypt(SecretKey key, String inputFilePath, String outputFilePath, AESDecryptListener listener){
if(!mWorkInProgress){
mWorkInProgress = true;
FxLog.d(TAG, "!decrypt");
//validate input
if(key == null){
FxLog.e(TAG, "> decrypt # Secret Key cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Secret Key cannot be NULL");
}
if(inputFilePath == null){
FxLog.e(TAG, "> decrypt # Input file path cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Input file path cannot be NULL");
}
if(outputFilePath == null){
FxLog.e(TAG, "> decrypt # Output file path cannot be NULL");
mWorkInProgress = false;
throw new IllegalArgumentException("Output file path cannot be NULL");
}
// set parameters
mKey = key;
mInputFilePath = inputFilePath;
mOutputFilePath = outputFilePath;
mListener = listener;
mWorkingMode = MODE_DECRYPT;
//grab caller Thread
if(listener != null){
try {
addAsyncCallback(listener);
} catch (NullListenerException e) {
// unchecked
FxLog.w(TAG, "> compress # NullListenerException");
}
}
// start executor
Executor executor = new Executor();
executor.setPriority(Thread.MIN_PRIORITY);
executor.start();
return true;
}else{
FxLog.e(TAG, "> decrypt # Previous request is in progress, skip incoming request");
return false;
}
}
private class Executor extends Thread{
@Override
public void run(){
FxLog.d(TAG, String.format("Executor > run # Executor is running with Thread ID: %d", Thread.currentThread().getId()));
//choose operation mode
if(mWorkingMode == MODE_ENCRYPT){
doEncrypt();
}else{
doDecrypt();
}
}
private void doEncrypt(){
AESEncryptListener listener = null;
try {
//1 prepare Listener
if(mListener != null){
listener = (AESEncryptListener) mListener;
}
//2 open files
FileInputStream fInStream = new FileInputStream(mInputFilePath); // input plain text file
FileOutputStream fOutStream = new FileOutputStream(mOutputFilePath); // output cipher file
//3 prepare Cipher instance
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//4 initialize Cipher
cipher.init(Cipher.ENCRYPT_MODE, mKey, CBC_SALT);
//5 initiate CipherInputStream and buffer
CipherInputStream cis = new CipherInputStream(fInStream, cipher);
byte[] buffer = new byte[BUFFER_SIZE];
//6 encrypt data and write output to file
int readCount = cis.read(buffer);
while(readCount != -1){
fOutStream.write(buffer, 0, readCount);
readCount = cis.read(buffer);
}
//7 do final encryption block and close input stream (IOException might be occurred)
cis.close();
/*
* 8 close output stream
* We need to close output stream before notify result to caller.
* Since caller might use this file.
*/
fOutStream.close();
//9 clear working flag
mWorkInProgress = false;
//10 notify caller and clear working flag
if(listener != null){
mListener = null;
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_SUCCESS, mOutputFilePath);
listener = null;
}
}catch (FileNotFoundException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # File not found\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
}catch (NoSuchAlgorithmException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # Cannot initiate Cipher using the given algorithm\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (NoSuchPaddingException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # Cannot initiate Cipher using the given padding method\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (InvalidKeyException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # Secret Key is invalid\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (InvalidAlgorithmParameterException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # IV is invalid\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (IOException e) {
FxLog.e(TAG, String.format("Executor > doEncrypt # Exception while encryting file\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_ENCRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
}
}
private void doDecrypt(){
AESDecryptListener listener = null;
try{
//1 prepare listener
if(mListener != null){
listener = (AESDecryptListener) mListener;
}
//2 open files
FileInputStream fInStream = new FileInputStream(mInputFilePath); // input cipher file
FileOutputStream fOutStream = new FileOutputStream(mOutputFilePath); // output plain text file
//3 prepare Cipher instance
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//4 initialize Cipher
cipher.init(Cipher.DECRYPT_MODE, mKey, CBC_SALT);
//5 initiate CipherInputStream and buffer
CipherInputStream cis = new CipherInputStream(fInStream, cipher);
byte[] buffer = new byte[BUFFER_SIZE];
//6 decrypt data and write output to file
int readCount = cis.read(buffer);
while(readCount != -1){
fOutStream.write(buffer, 0, readCount);
readCount = cis.read(buffer);
}
//7 do final decryption block and close input stream (IOException might be occurred)
cis.close();
/*
* 8 close output stream
* We need to close output stream before notify result to caller.
* Since caller might use this file.
*/
fOutStream.close();
//9 clear working flag
mWorkInProgress = false;
//10 notify caller and clear working flag
if(listener != null){
mListener = null;
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_SUCCESS, mOutputFilePath);
listener = null;
}
}catch (FileNotFoundException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # File not found\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
}catch (NoSuchAlgorithmException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # Cannot initiate Cipher using the given algorithm\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (NoSuchPaddingException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # Cannot initiate Cipher using the given padding method\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (InvalidKeyException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # Secret Key is invalid\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (InvalidAlgorithmParameterException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # IV is invalid\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
} catch (IOException e) {
FxLog.e(TAG, String.format("Executor > doDecrypt # Exception while decryting file\n%s", e.getMessage()));
if(listener != null){
invokeAsyncCallback(listener, CALL_BACK_DECRYPT_ERROR, e);
listener = null;
mListener = null;
}
mWorkInProgress = false;
}
}
}
@Override
protected void onAsyncCallbackInvoked(AESCipherListener listener, int what, Object... results) {
FxLog.d(TAG, String.format("> onAsyncCallbackInvoked # Thread ID: %d", Thread.currentThread().getId()));
/*
* CRITICAL - Concurrent Problem!
* The reason that we remove async callback here (using caller Thread)
* because of the concurrent problem.
* If caller thread request for another operation immediately in callback method - for example, call decrypt() in onAESEncryptSuccess(),
* and also supply the same listener instance with the past request - normally, the listener instance is the caller's instance
* The listener object might be null if we remove async callback in Executor Thread after call invokeAsyncCallback()
* since Caller Thread might be faster than Executor and set new request before Executor remove previous listener.
*/
removeAsyncCallback(listener);
switch(what){
case CALL_BACK_ENCRYPT_ERROR :
AESEncryptListener encryptErrListener = (AESEncryptListener) listener;
encryptErrListener.onAESEncryptError((Exception) results[0]);
break;
case CALL_BACK_ENCRYPT_SUCCESS :
AESEncryptListener encryptSucListener = (AESEncryptListener) listener;
encryptSucListener.onAESEncryptSuccess((String) results[0]);
break;
case CALL_BACK_DECRYPT_ERROR :
AESDecryptListener decryptErrListener = (AESDecryptListener) listener;
decryptErrListener.onAESDecryptError((Exception) results[0]);
break;
case CALL_BACK_DECRYPT_SUCCESS :
AESDecryptListener decryptSucListener = (AESDecryptListener) listener;
decryptSucListener.onAESDecryptSuccess((String) results[0]);
break;
}
}
// =================================================== static methods ========================================== //
/**
* Encrypt input byte data using AES algorithm.
*
* @param key
* @param data
* @return cipher or null if error.
* @throws InvalidKeyException if input secret key is invalid.
*/
public static byte[] encrypt(SecretKey key, byte[] data) throws InvalidKeyException{
if(key == null || data == null){
FxLog.e(TAG, "> encrypt # Input data is null");
throw new IllegalArgumentException("input is null");
}
byte[] cipherText = null;
try {
//1 get Cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//2 initialize Cipher
cipher.init(Cipher.ENCRYPT_MODE, key, CBC_SALT);
//3 do encryption
cipherText = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
FxLog.e(TAG, String.format("> encrypt # cipher connot initialize using specific algorithm\n%s", e.getMessage()));
} catch (NoSuchPaddingException e) {
FxLog.e(TAG, String.format("> encrypt # cipher cannot initialize specific padding\n%s", e.getMessage()));
} catch (InvalidKeyException e) {
FxLog.e(TAG, String.format("> encrypt # Secret key is invalid\n%s", e.getMessage()));
throw e;
} catch (InvalidAlgorithmParameterException e) {
FxLog.e(TAG, String.format("> encrypt # Initial Vector is invalid\n%s", e.getMessage()));
} catch (IllegalBlockSizeException e) {
FxLog.e(TAG, String.format("> encrypt # Illegal block size\n%s", e.getMessage()));
} catch (BadPaddingException e) {
FxLog.e(TAG, String.format("> encrypt # Bad padding\n%s", e.getMessage()));
}
return cipherText;
}
/**
* Decipher input cipher using AES algorithm.
* @param key
* @param data
* @return plain text or null if error.
* @throws InvalidKeyException if secret key is invalid.
*/
public static byte[] decrypt(SecretKey key, byte[] data)throws InvalidKeyException{
if(key == null || data == null){
FxLog.e(TAG, "> decrypt # Input data is null");
throw new IllegalArgumentException("input is null");
}
byte[] plainText = null;
try {
//1 get Cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//2 initialize Cipher
cipher.init(Cipher.DECRYPT_MODE, key, CBC_SALT);
//3 do decryption
plainText = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
FxLog.e(TAG, String.format("> decrypt # cipher cannot initialize using specific algorithm\n%s", e.getMessage()));
} catch (NoSuchPaddingException e) {
FxLog.e(TAG, String.format("> decrypt # cipher cannot initialize using specific padding\n%s", e.getMessage()));
} catch (InvalidKeyException e) {
FxLog.e(TAG, String.format("> decrypt # Secret key is invalid\n%s", e.getMessage()));
throw e;
} catch (InvalidAlgorithmParameterException e) {
FxLog.e(TAG, String.format("> decrypt # Initial Vector is invalid\n%s", e.getMessage()));
} catch (IllegalBlockSizeException e) {
FxLog.e(TAG, String.format("> decrypt # Illegal block size\n%s", e.getMessage()));
} catch (BadPaddingException e) {
FxLog.e(TAG, String.format("> decrypt # Bad padding\n%s", e.getMessage()));
}
return plainText;
}
}
|
package com.esp.library.exceedersesp.controllers.fieldstype.viewholders;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.esp.library.R;
import com.esp.library.utilities.customcontrols.ESP_LIB_BodyText;
import com.google.android.material.textfield.TextInputLayout;
public class ESP_LIB_EditTextTypeViewHolder extends RecyclerView.ViewHolder {
public TextInputLayout tilFieldLabel;
public TextInputLayout tilFieldDisableLabel;
public com.esp.library.utilities.customcontrols.ESP_LIB_BodyEditText etValue;
public com.esp.library.utilities.customcontrols.ESP_LIB_BodyEditText etvalueDisable;
public ESP_LIB_BodyText tValue;
public ESP_LIB_BodyText tValueLabel;
public ImageView ivicon;
public View onlyviewlayout;
public LinearLayout llparent;
public ESP_LIB_EditTextTypeViewHolder(View itemView) {
super(itemView);
llparent = itemView.findViewById(R.id.llparent);
tilFieldLabel = itemView.findViewById(R.id.tilFieldLabel);
tilFieldDisableLabel = itemView.findViewById(R.id.tilFieldDisableLabel);
etValue = itemView.findViewById(R.id.etValue);
tValue = itemView.findViewById(R.id.tValue);
tValueLabel = itemView.findViewById(R.id.tValueLabel);
etvalueDisable = itemView.findViewById(R.id.etvalueDisable);
ivicon = itemView.findViewById(R.id.ivicon);
onlyviewlayout = itemView.findViewById(R.id.onlyviewlayout);
}
}
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.workspaces.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/DescribeIpGroups" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeIpGroupsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Information about the IP access control groups.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup> result;
/**
* <p>
* The token to use to retrieve the next page of results. This value is null when there are no more results to
* return.
* </p>
*/
private String nextToken;
/**
* <p>
* Information about the IP access control groups.
* </p>
*
* @return Information about the IP access control groups.
*/
public java.util.List<WorkspacesIpGroup> getResult() {
if (result == null) {
result = new com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup>();
}
return result;
}
/**
* <p>
* Information about the IP access control groups.
* </p>
*
* @param result
* Information about the IP access control groups.
*/
public void setResult(java.util.Collection<WorkspacesIpGroup> result) {
if (result == null) {
this.result = null;
return;
}
this.result = new com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup>(result);
}
/**
* <p>
* Information about the IP access control groups.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResult(java.util.Collection)} or {@link #withResult(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param result
* Information about the IP access control groups.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeIpGroupsResult withResult(WorkspacesIpGroup... result) {
if (this.result == null) {
setResult(new com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup>(result.length));
}
for (WorkspacesIpGroup ele : result) {
this.result.add(ele);
}
return this;
}
/**
* <p>
* Information about the IP access control groups.
* </p>
*
* @param result
* Information about the IP access control groups.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeIpGroupsResult withResult(java.util.Collection<WorkspacesIpGroup> result) {
setResult(result);
return this;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is null when there are no more results to
* return.
* </p>
*
* @param nextToken
* The token to use to retrieve the next page of results. This value is null when there are no more results
* to return.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is null when there are no more results to
* return.
* </p>
*
* @return The token to use to retrieve the next page of results. This value is null when there are no more results
* to return.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token to use to retrieve the next page of results. This value is null when there are no more results to
* return.
* </p>
*
* @param nextToken
* The token to use to retrieve the next page of results. This value is null when there are no more results
* to return.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeIpGroupsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResult() != null)
sb.append("Result: ").append(getResult()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeIpGroupsResult == false)
return false;
DescribeIpGroupsResult other = (DescribeIpGroupsResult) obj;
if (other.getResult() == null ^ this.getResult() == null)
return false;
if (other.getResult() != null && other.getResult().equals(this.getResult()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResult() == null) ? 0 : getResult().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public DescribeIpGroupsResult clone() {
try {
return (DescribeIpGroupsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.audit.service.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.rest.webmvc.support.ExceptionMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LogManager.getLogger();
@ExceptionHandler({ Exception.class })
@ResponseBody
public ResponseEntity<?> handleAnyException(Exception e) {
if (e instanceof IllegalArgumentException) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} else if (e instanceof IllegalStateException) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
protected ResponseEntity<ExceptionMessage> errorResponse(Throwable throwable,
HttpStatus status) {
if (null != throwable) {
LOGGER.error("error caught: " + throwable.getMessage(), throwable);
return response(new ExceptionMessage(throwable), status);
} else {
LOGGER.error("unknown error caught in RESTController, {}", status);
return response(null, status);
}
}
protected <T> ResponseEntity<T> response(T body, HttpStatus status) {
LOGGER.debug("Responding with a status of {}", status);
return new ResponseEntity<>(body, new HttpHeaders(), status);
}
}
|
package com.zeral.bean;
import java.util.List;
/**
* ngx-treeview 组件返回tree数据
*
* @author Zeral
* @date 2018-03-06
*/
public class NgxTree {
private String text;
private Long value;
private boolean checked;
private List<NgxTree> children;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public List<NgxTree> getChildren() {
return children;
}
public void setChildren(List<NgxTree> children) {
this.children = children;
}
}
|
/*******************************************************************************
* Copyright 2002-2016 the original author or authors.
*
* 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.github.lothar.security.acl.elasticsearch.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import com.github.lothar.security.acl.Acl;
@Document(indexName = "deniedToAll")
@Acl("denyAllStrategy")
public class DeniedToAllObject {
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
package com.aftertoday.redisdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RedisDemoApplication.class,args);
}
}
|
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.transport.http.netty.sender.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.HttpConversionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.transport.http.netty.common.Constants;
import org.wso2.transport.http.netty.contractimpl.DefaultHttpClientConnector;
import org.wso2.transport.http.netty.message.HTTPCarbonMessage;
import org.wso2.transport.http.netty.sender.RedirectUtil;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
/**
* {@code RedirectHandler} is responsible for HTTP/2 redirection.
*/
public class RedirectHandler implements Http2DataEventListener {
private static final Logger log = LoggerFactory.getLogger(RedirectHandler.class);
private Http2ClientChannel http2ClientChannel;
private int maxRedirectCount;
public RedirectHandler(Http2ClientChannel http2ClientChannel, int maxRedirectCount) {
this.http2ClientChannel = http2ClientChannel;
this.maxRedirectCount = maxRedirectCount;
}
@Override
public boolean onStreamInit(ChannelHandlerContext ctx, int streamId) {
return true;
}
@Override
public boolean onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, boolean endOfStream) {
OutboundMsgHolder outboundMsgHolder = http2ClientChannel.getInFlightMessage(streamId);
int statusCode = fetchStatusCode(headers);
if (!isRedirectionResponse(statusCode)) {
return true;
}
String location = fetchLocationHeaderVal(headers);
if (location == null) {
return true;
}
if (outboundMsgHolder.incrementRedirectCount() > maxRedirectCount) {
return true;
}
if (endOfStream) {
doRedirection(ctx, streamId, statusCode, outboundMsgHolder, location, fetchUserAgentHeaderVal(headers));
} else {
outboundMsgHolder.markForRedirection();
outboundMsgHolder.setRedirectResponseHeaders(headers);
}
return false;
}
@Override
public boolean onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, boolean endOfStream) {
OutboundMsgHolder outboundMsgHolder = http2ClientChannel.getInFlightMessage(streamId);
if (outboundMsgHolder.isMarkedForRedirection()) {
if (endOfStream) {
Http2Headers headers = outboundMsgHolder.getRedirectResponseHeaders();
doRedirection(ctx, streamId, fetchStatusCode(headers), outboundMsgHolder,
fetchLocationHeaderVal(headers), fetchUserAgentHeaderVal(headers));
}
return false;
}
return true;
}
@Override
public boolean onPushPromiseRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
boolean endOfStream) {
return true;
}
@Override
public boolean onHeadersWrite(ChannelHandlerContext ctx, int streamId, Http2Headers headers, boolean endOfStream) {
return true;
}
@Override
public boolean onDataWrite(ChannelHandlerContext ctx, int streamId, ByteBuf data, boolean endOfStream) {
return true;
}
@Override
public boolean onStreamReset(int streamId) {
return true;
}
@Override
public boolean onStreamClose(int streamId) {
return true;
}
@Override
public void destroy() {
}
private void doRedirection(ChannelHandlerContext ctx, int streamId, int statusCode,
OutboundMsgHolder outboundMsgHolder, String location, String userAgent) {
try {
HTTPCarbonMessage originalRequest = outboundMsgHolder.getRequest();
String redirectionMethod = getRedirectionRequestMethod(statusCode, originalRequest);
String redirectionURL = RedirectUtil.getResolvedRedirectURI(location, originalRequest);
List<Map.Entry<String, String>> headers = originalRequest.getHeaders().entries();
HTTPCarbonMessage request = RedirectUtil
.createRedirectCarbonRequest(redirectionURL, redirectionMethod, statusCode, ctx, headers);
outboundMsgHolder.clearRedirectionState();
http2ClientChannel.removeInFlightMessage(streamId);
outboundMsgHolder.updateRequest(request);
DefaultHttpClientConnector connector = ctx.channel().attr(Constants.CLIENT_CONNECTOR).get();
connector.send(outboundMsgHolder, request);
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException occurred when constructing direction request",
e);
} catch (MalformedURLException e) {
log.error("MalformedURLException occurred when constructing direction request", e);
} catch (URISyntaxException e) {
log.error("URISyntaxException occurred when constructing direction request", e);
}
}
private int fetchStatusCode(Http2Headers headers) {
HttpResponseStatus responseStatus;
try {
responseStatus = HttpConversionUtil.parseStatus(headers.status());
} catch (Http2Exception e) {
responseStatus = HttpResponseStatus.BAD_GATEWAY;
}
return responseStatus.code();
}
private String fetchLocationHeaderVal(Http2Headers headers) {
return headers.get(HttpHeaderNames.LOCATION) != null ? headers.get(HttpHeaderNames.LOCATION).toString() : null;
}
private String fetchUserAgentHeaderVal(Http2Headers headers) {
return headers.
get(HttpHeaderNames.USER_AGENT) != null ? headers.get(HttpHeaderNames.USER_AGENT).toString() : null;
}
private boolean isRedirectionResponse(int statusCode) {
return statusCode >= 300 && statusCode < 400;
}
private String getRedirectionRequestMethod(int statusCode, HTTPCarbonMessage originalRequest) {
String originalRequestMethod =
originalRequest != null ? (String) originalRequest.getProperty(Constants.HTTP_METHOD) : null;
switch (statusCode) {
case 300:
case 305:
case 307:
case 308:
if (Constants.HTTP_GET_METHOD.equals(originalRequestMethod) || Constants.HTTP_HEAD_METHOD
.equals(originalRequestMethod)) {
return originalRequestMethod;
}
break;
case 301:
case 302:
if (Constants.HTTP_GET_METHOD.equals(originalRequestMethod) || Constants.HTTP_HEAD_METHOD
.equals(originalRequestMethod)) {
return Constants.HTTP_GET_METHOD;
}
break;
case 303:
return Constants.HTTP_GET_METHOD;
}
return null;
}
}
|
package com.abings.baby.ui.login.create;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import com.abings.baby.R;
import com.abings.baby.ZSApp;
import com.abings.baby.ui.base.BaseTitleActivity;
import com.abings.baby.ui.login.needbaby.NeedBabyActivity;
import com.abings.baby.util.SharedPreferencesUtils;
import com.hellobaby.library.Const;
import com.hellobaby.library.data.model.BabyModel;
import com.hellobaby.library.ui.LoginUtils;
import com.hellobaby.library.ui.crop.SinglePhotoActivity;
import com.hellobaby.library.widget.BottomDialogUtils;
import com.hellobaby.library.widget.BottomPickerDateDialog;
import com.hellobaby.library.widget.crop.FileUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
/**
* Created by zwj on 2016/11/15.
* description : 创建一个宝宝
*/
public class CreateBabyActivity extends BaseTitleActivity implements CreateBabyMvpView {
@Inject
CreateBabyPresenter presenter;
@BindView(R.id.createBaby_iv_head)
ImageView ivHead;
@BindView(R.id.createBaby_et_name)
EditText etName;
@BindView(R.id.createBaby_et_gender)
EditText etGender;
@BindView(R.id.createBaby_et_birthday)
EditText etBirthday;
@BindView(R.id.createBaby_et_native)
EditText etNative;
@BindView(R.id.createBaby_et_school)
EditText etSchool;
@BindView(R.id.createBaby_btn_complete)
Button btnComplete;
String birthday = null;
private String mHeadImgPath;
@Override
protected int getContentViewLayoutID() {
return R.layout.activity_createbaby;
}
@Override
protected void initDaggerInject() {
getActivityComponent().inject(this);
}
@Override
protected void initViewsAndEvents(@Nullable Bundle savedInstanceState) {
setBtnLeftClickFinish();
presenter.attachView(this);
}
@Override
public void showData(Object o) {
}
//姓名
@OnTextChanged(value = R.id.createBaby_et_name, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void otcName(CharSequence charSequence) {
LoginUtils.setBtnVisibility(charSequence, btnComplete, etGender, etBirthday, etNative);
}
//性别
@OnTextChanged(value = R.id.createBaby_et_gender, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void otcGender(CharSequence charSequence) {
LoginUtils.setBtnVisibility(charSequence, btnComplete, etName, etBirthday, etNative);
}
//生日
@OnTextChanged(value = R.id.createBaby_et_birthday, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void otcBirthday(CharSequence charSequence) {
LoginUtils.setBtnVisibility(charSequence, btnComplete, etName, etGender, etNative);
}
//出生地
@OnTextChanged(value = R.id.createBaby_et_native, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void otcNative(CharSequence charSequence) {
LoginUtils.setBtnVisibility(charSequence, btnComplete, etName, etGender, etBirthday);
}
@OnClick({R.id.createBaby_iv_head, R.id.createBaby_et_gender, R.id.createBaby_et_birthday, R.id.createBaby_btn_complete})
public void onClick(View view) {
switch (view.getId()) {
case R.id.createBaby_iv_head:
//已经选中的用户
//切换头像
Intent intent = new Intent(bContext, SinglePhotoActivity.class);
intent.putExtra("isCreate", true);
intent.putExtra("bitmap", ivHead.getDrawingCache());
startActivityForResult(intent, 200);
break;
case R.id.createBaby_et_gender:
//性别
BottomDialogUtils.getBottomGenderDialog(bContext, new BottomDialogUtils.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, String item, long id) {
etGender.setText(item);
}
});
break;
case R.id.createBaby_et_birthday:
//生日
// String birthday = null;
String[] bs = etBirthday.getText().toString().split(" ");
if (bs.length >= 2) {
birthday = etBirthday.getText().toString().split(" ")[1];
} else
birthday = null;
BottomDialogUtils.getBottomDatePickerDialog(bContext, birthday, true, new BottomPickerDateDialog.BottomOnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth, String showDate) {
etBirthday.setText("出生 " + showDate);
}
});
break;
case R.id.createBaby_btn_complete:
BabyModel baby = new BabyModel();
baby.setBabyName(etName.getText().toString());
baby.setBabyGender(etGender.getText().toString().contains("男孩") ? "1" : "0");
SimpleDateFormat sdf = new SimpleDateFormat("出生 yyyy年MM月dd日");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(etBirthday.getText().toString());
baby.setBirthday(sdf2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
baby.setAddress(etNative.getText().toString());
baby.setKindergarten(etSchool.getText().toString());
String phoneNum = (String) SharedPreferencesUtils.getParam(bContext, Const.keyPhoneNum, "");
List<BabyModel> list = ZSApp.getInstance().getListBaby();
boolean isSameName = false;
if (list != null && list.size() > 0) {
for (BabyModel babyModel : list) {
if (baby.getBabyName().equals(babyModel.getBabyName())) {
isSameName = true;
break;
}
}
}
if (isSameName) {
showError("该宝宝已存在");
return;
}
presenter.createBaby(baby, mHeadImgPath, phoneNum);
break;
}
}
@Override
public void createBabyFinish(int babyId) {
// presenter.insertInitAlert(babyId);
}
@Override
public void createFinish(String msg) {
showToast("创建宝宝完成");
setResult(NeedBabyActivity.kCreateBabySuccess);
finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == -1) {
//用户的登录头像更换
mHeadImgPath = FileUtils.getFilePathFromUri(bContext, data.getData());
ivHead.setImageURI(data.getData());
}
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.disruptor.trace;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventTranslatorThreeArg;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.internal.DaemonThreadFactory;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SpanProcessor;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A low-latency event queue for background updating of (possibly contended) objects. This is
* intended for use by instrumentation methods to ensure that they do not block foreground
* activities.
*/
final class DisruptorEventQueue {
private static final Logger logger = Logger.getLogger(DisruptorEventQueue.class.getName());
private static final String WORKER_THREAD_NAME = "DisruptorEventQueue_WorkerThread";
private static final EventTranslatorThreeArg<
DisruptorEvent, EventType, Object, CompletableResultCode>
TRANSLATOR_THREE_ARG =
(event, sequence, eventType, span, result) -> event.setEntry(eventType, span, result);
private static final EventFactory<DisruptorEvent> EVENT_FACTORY = DisruptorEvent::new;
private final RingBuffer<DisruptorEvent> ringBuffer;
private final AtomicBoolean loggedShutdownMessage = new AtomicBoolean(false);
private volatile boolean isShutdown = false;
private final boolean blocking;
private enum EventType {
ON_START,
ON_END,
ON_SHUTDOWN,
ON_FORCE_FLUSH
}
DisruptorEventQueue(
int bufferSize, WaitStrategy waitStrategy, SpanProcessor spanProcessor, boolean blocking) {
// Create new Disruptor for processing. Note that Disruptor creates a single thread per
// consumer (see https://github.com/LMAX-Exchange/disruptor/issues/121 for details);
// this ensures that the event handler can take unsynchronized actions whenever possible.
Disruptor<DisruptorEvent> disruptor =
new Disruptor<>(
EVENT_FACTORY,
bufferSize,
new DaemonThreadFactory(WORKER_THREAD_NAME),
ProducerType.MULTI,
waitStrategy);
disruptor.handleEventsWith(new DisruptorEventHandler(spanProcessor));
this.ringBuffer = disruptor.start();
this.blocking = blocking;
}
void enqueueStartEvent(ReadWriteSpan span, Context parentContext) {
if (isShutdown) {
if (!loggedShutdownMessage.getAndSet(true)) {
logger.info("Attempted to enqueue start event after Disruptor shutdown.");
}
return;
}
enqueue(EventType.ON_START, new AbstractMap.SimpleImmutableEntry<>(span, parentContext), null);
}
void enqueueEndEvent(ReadableSpan span) {
if (isShutdown) {
if (!loggedShutdownMessage.getAndSet(true)) {
logger.info("Attempted to enqueue end event after Disruptor shutdown.");
}
return;
}
enqueue(EventType.ON_END, span, null);
}
// Shuts down the underlying disruptor. Ensures that when this method returns the disruptor is
// shutdown.
CompletableResultCode shutdown() {
synchronized (this) {
if (isShutdown) {
// Race condition between two calls to shutdown. The other call already finished.
return CompletableResultCode.ofSuccess();
}
isShutdown = true;
return enqueueWithResult(EventType.ON_SHUTDOWN);
}
}
// Force to publish the ended spans to the SpanProcessor
CompletableResultCode forceFlush() {
if (isShutdown) {
if (!loggedShutdownMessage.getAndSet(true)) {
logger.info("Attempted to flush after Disruptor shutdown.");
}
return CompletableResultCode.ofFailure();
}
return enqueueWithResult(EventType.ON_FORCE_FLUSH);
}
private CompletableResultCode enqueueWithResult(EventType event) {
CompletableResultCode result = new CompletableResultCode();
enqueue(event, null, result);
return result;
}
// Enqueues an event on the {@link DisruptorEventQueue}.
private void enqueue(
EventType eventType, @Nullable Object span, @Nullable CompletableResultCode result) {
if (blocking) {
ringBuffer.publishEvent(TRANSLATOR_THREE_ARG, eventType, span, result);
} else {
// TODO: Record metrics if element not added.
ringBuffer.tryPublishEvent(TRANSLATOR_THREE_ARG, eventType, span, result);
}
}
// An event in the {@link EventQueue}. Just holds a reference to an EventQueue.Entry.
private static final class DisruptorEvent {
@Nullable private Object eventArgs = null;
@Nullable private EventType eventType = null;
@Nullable private CompletableResultCode result = null;
void setEntry(
@Nullable EventType eventType,
@Nullable Object span,
@Nullable CompletableResultCode result) {
this.eventArgs = span;
this.eventType = eventType;
this.result = result;
}
@Nullable Object getEventArgs() {
return eventArgs;
}
@Nullable EventType getEventType() {
return eventType;
}
void succeed() {
if (result != null) {
result.succeed();
}
}
void fail() {
if (result != null) {
result.fail();
}
}
}
private static final class DisruptorEventHandler implements EventHandler<DisruptorEvent> {
private final SpanProcessor spanProcessor;
private DisruptorEventHandler(SpanProcessor spanProcessor) {
this.spanProcessor = spanProcessor;
}
@Override
public void onEvent(final DisruptorEvent event, long sequence, boolean endOfBatch) {
final Object readableSpan = event.getEventArgs();
final EventType eventType = event.getEventType();
if (eventType == null) {
logger.warning("Disruptor enqueued null element type.");
return;
}
try {
switch (eventType) {
case ON_START:
// In practice never null
if (readableSpan != null) {
@SuppressWarnings("unchecked")
final SimpleImmutableEntry<ReadWriteSpan, Context> eventArgs =
(SimpleImmutableEntry<ReadWriteSpan, Context>) readableSpan;
spanProcessor.onStart(eventArgs.getValue(), eventArgs.getKey());
}
break;
case ON_END:
// In practice never null
if (readableSpan != null) {
spanProcessor.onEnd((ReadableSpan) readableSpan);
}
break;
case ON_SHUTDOWN:
propagateResult(spanProcessor.shutdown(), event);
break;
case ON_FORCE_FLUSH:
propagateResult(spanProcessor.forceFlush(), event);
break;
}
} finally {
// Remove the reference to the previous entry to allow the memory to be gc'ed.
event.setEntry(null, null, null);
}
}
}
private static void propagateResult(
final CompletableResultCode result, final DisruptorEvent event) {
result.whenComplete(
() -> {
if (result.isSuccess()) {
event.succeed();
} else {
event.fail();
}
});
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.client.impl.LeaseRenewer;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class TestLease {
static boolean hasLease(MiniDFSCluster cluster, Path src) {
return NameNodeAdapter.getLeaseForPath(cluster.getNameNode(),
src.toString()) != null;
}
static int leaseCount(MiniDFSCluster cluster) {
return NameNodeAdapter.getLeaseManager(cluster.getNamesystem()).countLease();
}
static final String dirString = "/test/lease";
final Path dir = new Path(dirString);
static final Log LOG = LogFactory.getLog(TestLease.class);
final Configuration conf = new HdfsConfiguration();
@Test
public void testLeaseAbort() throws Exception {
MiniDFSCluster cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
cluster.waitActive();
NamenodeProtocols preSpyNN = cluster.getNameNodeRpc();
NamenodeProtocols spyNN = spy(preSpyNN);
DFSClient dfs = new DFSClient(null, spyNN, conf, null);
byte[] buf = new byte[1024];
FSDataOutputStream c_out = createFsOut(dfs, dirString + "c");
c_out.write(buf, 0, 1024);
c_out.close();
DFSInputStream c_in = dfs.open(dirString + "c");
FSDataOutputStream d_out = createFsOut(dfs, dirString + "d");
// stub the renew method.
doThrow(new RemoteException(InvalidToken.class.getName(),
"Your token is worthless")).when(spyNN).renewLease(anyString());
// We don't need to wait the lease renewer thread to act.
// call renewLease() manually.
// make it look like the soft limit has been exceeded.
LeaseRenewer originalRenewer = dfs.getLeaseRenewer();
dfs.lastLeaseRenewal = Time.monotonicNow() -
HdfsConstants.LEASE_SOFTLIMIT_PERIOD - 1000;
try {
dfs.renewLease();
} catch (IOException e) {}
// Things should continue to work it passes hard limit without
// renewing.
try {
d_out.write(buf, 0, 1024);
LOG.info("Write worked beyond the soft limit as expected.");
} catch (IOException e) {
Assert.fail("Write failed.");
}
long hardlimit = conf.getLong(DFSConfigKeys.DFS_LEASE_HARDLIMIT_KEY,
DFSConfigKeys.DFS_LEASE_HARDLIMIT_DEFAULT) * 1000;
// make it look like the hard limit has been exceeded.
dfs.lastLeaseRenewal = Time.monotonicNow() - hardlimit - 1000;
dfs.renewLease();
// this should not work.
try {
d_out.write(buf, 0, 1024);
d_out.close();
Assert.fail("Write did not fail even after the fatal lease renewal failure");
} catch (IOException e) {
LOG.info("Write failed as expected. ", e);
}
// If aborted, the renewer should be empty. (no reference to clients)
Thread.sleep(1000);
Assert.assertTrue(originalRenewer.isEmpty());
// unstub
doNothing().when(spyNN).renewLease(anyString());
// existing input streams should work
try {
int num = c_in.read(buf, 0, 1);
if (num != 1) {
Assert.fail("Failed to read 1 byte");
}
c_in.close();
} catch (IOException e) {
LOG.error("Read failed with ", e);
Assert.fail("Read after lease renewal failure failed");
}
// new file writes should work.
try {
c_out = createFsOut(dfs, dirString + "c");
c_out.write(buf, 0, 1024);
c_out.close();
} catch (IOException e) {
LOG.error("Write failed with ", e);
Assert.fail("Write failed");
}
} finally {
cluster.shutdown();
}
}
@Test
public void testLeaseAfterRename() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
Path p = new Path("/test-file");
Path d = new Path("/test-d");
Path d2 = new Path("/test-d-other");
// open a file to get a lease
FileSystem fs = cluster.getFileSystem();
FSDataOutputStream out = fs.create(p);
out.writeBytes("something");
//out.hsync();
Assert.assertTrue(hasLease(cluster, p));
Assert.assertEquals(1, leaseCount(cluster));
// just to ensure first fs doesn't have any logic to twiddle leases
DistributedFileSystem fs2 = (DistributedFileSystem) FileSystem.newInstance(fs.getUri(), fs.getConf());
// rename the file into an existing dir
LOG.info("DMS: rename file into dir");
Path pRenamed = new Path(d, p.getName());
fs2.mkdirs(d);
fs2.rename(p, pRenamed);
Assert.assertFalse(p+" exists", fs2.exists(p));
Assert.assertTrue(pRenamed+" not found", fs2.exists(pRenamed));
Assert.assertFalse("has lease for "+p, hasLease(cluster, p));
Assert.assertTrue("no lease for "+pRenamed, hasLease(cluster, pRenamed));
Assert.assertEquals(1, leaseCount(cluster));
// rename the parent dir to a new non-existent dir
LOG.info("DMS: rename parent dir");
Path pRenamedAgain = new Path(d2, pRenamed.getName());
fs2.rename(d, d2);
// src gone
Assert.assertFalse(d+" exists", fs2.exists(d));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d2+" not found", fs2.exists(d2));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename the parent dir to existing dir
// NOTE: rename w/o options moves paths into existing dir
LOG.info("DMS: rename parent again");
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(new Path(d, d2.getName()), p.getName());
fs2.mkdirs(d);
fs2.rename(d2, d);
// src gone
Assert.assertFalse(d2+" exists", fs2.exists(d2));
Assert.assertFalse("no lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d+" not found", fs2.exists(d));
Assert.assertTrue(pRenamedAgain +" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename with opts to non-existent dir
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(d2, p.getName());
fs2.rename(pRenamed.getParent(), d2, Options.Rename.OVERWRITE);
// src gone
Assert.assertFalse(pRenamed.getParent() +" not found", fs2.exists(pRenamed.getParent()));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d2+" not found", fs2.exists(d2));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename with opts to existing dir
// NOTE: rename with options will not move paths into the existing dir
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(d, p.getName());
fs2.rename(pRenamed.getParent(), d, Options.Rename.OVERWRITE);
// src gone
Assert.assertFalse(pRenamed.getParent() +" not found", fs2.exists(pRenamed.getParent()));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d+" not found", fs2.exists(d));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
out.close();
} finally {
cluster.shutdown();
}
}
/**
* Test that we can open up a file for write, move it to another location,
* and then create a new file in the previous location, without causing any
* lease conflicts. This is possible because we now use unique inode IDs
* to identify files to the NameNode.
*/
@Test
public void testLeaseAfterRenameAndRecreate() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
final Path path1 = new Path("/test-file");
final String contents1 = "contents1";
final Path path2 = new Path("/test-file-new-location");
final String contents2 = "contents2";
// open a file to get a lease
FileSystem fs = cluster.getFileSystem();
FSDataOutputStream out1 = fs.create(path1);
out1.writeBytes(contents1);
Assert.assertTrue(hasLease(cluster, path1));
Assert.assertEquals(1, leaseCount(cluster));
DistributedFileSystem fs2 = (DistributedFileSystem)
FileSystem.newInstance(fs.getUri(), fs.getConf());
fs2.rename(path1, path2);
FSDataOutputStream out2 = fs2.create(path1);
out2.writeBytes(contents2);
out2.close();
// The first file should still be open and valid
Assert.assertTrue(hasLease(cluster, path2));
out1.close();
// Contents should be as expected
DistributedFileSystem fs3 = (DistributedFileSystem)
FileSystem.newInstance(fs.getUri(), fs.getConf());
Assert.assertEquals(contents1, DFSTestUtil.readFile(fs3, path2));
Assert.assertEquals(contents2, DFSTestUtil.readFile(fs3, path1));
} finally {
cluster.shutdown();
}
}
@Test
public void testLease() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
FileSystem fs = cluster.getFileSystem();
Assert.assertTrue(fs.mkdirs(dir));
Path a = new Path(dir, "a");
Path b = new Path(dir, "b");
DataOutputStream a_out = fs.create(a);
a_out.writeBytes("something");
Assert.assertTrue(hasLease(cluster, a));
Assert.assertTrue(!hasLease(cluster, b));
DataOutputStream b_out = fs.create(b);
b_out.writeBytes("something");
Assert.assertTrue(hasLease(cluster, a));
Assert.assertTrue(hasLease(cluster, b));
a_out.close();
b_out.close();
Assert.assertTrue(!hasLease(cluster, a));
Assert.assertTrue(!hasLease(cluster, b));
Path fileA = new Path(dir, "fileA");
FSDataOutputStream fileA_out = fs.create(fileA);
fileA_out.writeBytes("something");
Assert.assertTrue("Failed to get the lease!", hasLease(cluster, fileA));
fs.delete(dir, true);
try {
fileA_out.hflush();
Assert.fail("Should validate file existence!");
} catch (FileNotFoundException e) {
// expected
GenericTestUtils.assertExceptionContains("File does not exist", e);
}
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
@SuppressWarnings("unchecked")
@Test
public void testFactory() throws Exception {
final String[] groups = new String[]{"supergroup"};
final UserGroupInformation[] ugi = new UserGroupInformation[3];
for(int i = 0; i < ugi.length; i++) {
ugi[i] = UserGroupInformation.createUserForTesting("user" + i, groups);
}
Mockito.doReturn(new HdfsFileStatus.Builder()
.replication(1)
.blocksize(1024)
.perm(new FsPermission((short) 777))
.owner("owner")
.group("group")
.symlink(new byte[0])
.path(new byte[0])
.fileId(1010)
.build())
.when(mcp)
.getFileInfo(anyString());
Mockito.doReturn(new HdfsFileStatus.Builder()
.replication(1)
.blocksize(1024)
.perm(new FsPermission((short) 777))
.owner("owner")
.group("group")
.symlink(new byte[0])
.path(new byte[0])
.fileId(1010)
.build())
.when(mcp)
.create(anyString(), (FsPermission) anyObject(), anyString(),
(EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject(),
anyObject());
final Configuration conf = new Configuration();
final DFSClient c1 = createDFSClientAs(ugi[0], conf);
FSDataOutputStream out1 = createFsOut(c1, "/out1");
final DFSClient c2 = createDFSClientAs(ugi[0], conf);
FSDataOutputStream out2 = createFsOut(c2, "/out2");
Assert.assertEquals(c1.getLeaseRenewer(), c2.getLeaseRenewer());
final DFSClient c3 = createDFSClientAs(ugi[1], conf);
FSDataOutputStream out3 = createFsOut(c3, "/out3");
Assert.assertTrue(c1.getLeaseRenewer() != c3.getLeaseRenewer());
final DFSClient c4 = createDFSClientAs(ugi[1], conf);
FSDataOutputStream out4 = createFsOut(c4, "/out4");
Assert.assertEquals(c3.getLeaseRenewer(), c4.getLeaseRenewer());
final DFSClient c5 = createDFSClientAs(ugi[2], conf);
FSDataOutputStream out5 = createFsOut(c5, "/out5");
Assert.assertTrue(c1.getLeaseRenewer() != c5.getLeaseRenewer());
Assert.assertTrue(c3.getLeaseRenewer() != c5.getLeaseRenewer());
}
private FSDataOutputStream createFsOut(DFSClient dfs, String path)
throws IOException {
return new FSDataOutputStream(dfs.create(path, true), null);
}
static final ClientProtocol mcp = Mockito.mock(ClientProtocol.class);
static public DFSClient createDFSClientAs(UserGroupInformation ugi,
final Configuration conf) throws Exception {
return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws Exception {
return new DFSClient(null, mcp, conf, null);
}
});
}
}
|
package org.adligo.tests4j_gen.console;
import org.adligo.tests4j.shared.asserts.reference.I_ClassAttributes;
import org.adligo.tests4j.shared.asserts.reference.I_FieldSignature;
import org.adligo.tests4j.shared.asserts.reference.I_MethodSignature;
import org.adligo.tests4j.shared.asserts.reference.MethodSignature;
import java.io.PrintStream;
import java.util.Set;
/**
* this class generates a sibling
* class for each class or interface
* with _MockUse in the name.
*
* @author scott
*
*/
public class ConstantClassAttributeMethodGen {
private ConstantLookup constantLookup;
/**
* this currently only prints
* out the method
* @param caa
* @param out
* @param ctx
*/
public void gen(ClassAndAttributes caa, PrintStream out, GenDepGroupContext ctx) {
constantLookup = ctx.getConstantLookup();
String packageName = ctx.getTrialPackageName();
Class<?> clazz = caa.getClazz();
out.println("\tpublic static ClassAttributes get" + clazz.getSimpleName() +"() {");
out.println("\t\tClassAttributesMutant toRet = new ClassAttributesMutant();");
out.println("\t\ttoRet.setName(" + constantLookup.get(clazz.getName()) + ");");
out.println("");
I_ClassAttributes ca = caa.getAttributes();
Set<I_MethodSignature> ms = ca.getMethods();
if (!clazz.isInterface()) {
out.println("\t\t//constructors");
if (!ms.contains(new MethodSignature("<init>"))) {
//everything has a hidden constructor with no arguments
//which shows up in ASM but not reflection,
//even if there isn't a public one
out.println("\t\ttoRet.addMethod(new MethodSignature(\"<init>\"));");
}
}
for (I_MethodSignature method: ms) {
if ("<init>".equals(method.getMethodName())) {
String nextLine = "\t\ttoRet.addMethod(new MethodSignature(\"" + method.getMethodName() + "\"";
if (method.getParameters() >= 1) {
nextLine = nextLine + ", " + System.lineSeparator() + "\t\t\t" + getMethodParamsDefaults(method);
}
if (method.getReturnClassName() != null) {
String type = constantLookup.get(method.getReturnClassName());
if (type != null) {
nextLine = nextLine + ", " + System.lineSeparator() + "\t\t\t" + type + "";
}
}
nextLine = nextLine + "));";
out.println(nextLine);
}
}
out.println("");
out.println("\t\tadd" + clazz.getSimpleName() + "Members(toRet);");
out.println("\t\treturn new ClassAttributes(toRet);");
out.println("\t}");
out.println("");
out.println("\tpublic static void add" + clazz.getSimpleName() + "Members(ClassAttributesMutant toRet) {");
Class<?> parentClass = clazz.getSuperclass();
if (parentClass != null) {
out.println("\t\tadd" + parentClass.getSimpleName() + "Members(toRet);");
}
Set<I_FieldSignature> fs = ca.getFields();
for (I_FieldSignature sig: fs) {
String nextLine = "\t\ttoRet.addField(new FieldSignature(\"" + sig.getName() + "\", " +
constantLookup.get(sig.getClassName()) + "));";
out.println(nextLine);
}
for (I_MethodSignature method: ms) {
if ( !"<init>".equals(method.getMethodName())) {
String nextLine = "\t\ttoRet.addMethod(new MethodSignature(\"" + method.getMethodName() + "\"";
if (method.getParameters() >= 1) {
nextLine = nextLine + ", " + System.lineSeparator() + "\t\t\t" + getMethodParamsDefaults(method);
}
if (method.getReturnClassName() != null) {
String type = constantLookup.get(method.getReturnClassName());
if (type != null) {
nextLine = nextLine + ", " + System.lineSeparator() + "\t\t\t" + type + "";
}
}
nextLine = nextLine + "));";
out.println(nextLine);
}
}
out.println("\t}");
}
private String getMethodParamsDefaults(I_MethodSignature ms) {
StringBuilder sb = new StringBuilder();
sb.append("new String[] {");
for (int i = 0; i < ms.getParameters(); i++) {
String param = ms.getParameterClassName(i);
if (i >= 1) {
sb.append(", ");
}
sb.append(constantLookup.get(param));
}
sb.append("}");
return sb.toString();
}
}
|
package br.com.caelum.tubaina.io;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.io.IOUtils;
import br.com.caelum.tubaina.TubainaException;
import br.com.caelum.tubaina.resources.Resource;
import br.com.caelum.tubaina.resources.ResourceManipulator;
public class TubainaHtmlDir implements TubainaDir{
private final File currentFolder;
private final File templateDir;
private final ResourceManipulatorFactory resourceManipulatorFactory;
public TubainaHtmlDir(File outputFolder, File templateDir, ResourceManipulatorFactory resourceManipulatorFactory) {
this.currentFolder = outputFolder;
this.templateDir = templateDir;
this.resourceManipulatorFactory = resourceManipulatorFactory;
}
public TubainaHtmlDir cd(String directoryName) {
File destination = new File(currentFolder, directoryName);
destination.mkdir();
return new TubainaHtmlDir(destination, templateDir, resourceManipulatorFactory);
}
public TubainaHtmlDir writeIndex(StringBuffer bookContent) {
File file = new File(currentFolder, "index.html");
try {
IOUtils.write(bookContent, new PrintStream(file, "UTF-8"));
return this;
} catch (IOException e) {
throw new TubainaException("Couldn't create index.html in " + currentFolder);
}
}
public TubainaHtmlDir writeResources(List<Resource> resources) {
Map<String, Integer> indexes = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
//TODO: remove this asap too
File logo = new File(templateDir, "logo.png");
ResourceManipulator manipulator = resourceManipulatorFactory.build(this.currentFolder, indexes, logo);
for (Resource r : resources) {
r.copyTo(manipulator);
}
return this;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package atter.jedis;
import atter.jedis.adapter.JedisAdapter;
import com.alibaba.fastjson.JSON;
/**
* Description: RedisQueue define
* Copyright: 2018 CSNT. All rights reserved.
* Company:CSNT
*
* @author wangling
* @version 1.0
*/
public class RedisQueue<E> implements JedisAdapterAware, KeyedData, Queue<E> {
private JedisAdapter jedisAdapter;
private String redisKey;
public RedisQueue(JedisAdapter jedisAdapter, String redisKey) {
this.jedisAdapter = jedisAdapter;
this.redisKey = redisKey;
}
@Override
public void setJedisAdapter(JedisAdapter jedisAdapter) {
this.jedisAdapter = jedisAdapter;
}
@Override
public void setRedisKey(String redisKey) {
this.redisKey = redisKey;
}
@Override
public String getRedisKey() {
return redisKey;
}
@Override
public boolean push(E o) {
long l;
if (o == null) {
l = jedisAdapter.rpush(redisKey, null);
}
if (o instanceof String) {
l = jedisAdapter.rpush(redisKey, String.valueOf(o));
} else {
l = jedisAdapter.rpush(redisKey, JSON.toJSONString(o));
}
return l > 0;
}
@Override
public E lpop() {
return (E) jedisAdapter.lpop(redisKey);
}
}
|
/*
* Copyright 2010 Brian S O'Neill
*
* 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 org.cojen.test;
import org.cojen.util.Cache;
import org.cojen.util.WeakValueCache;
/**
*
*
* @author Brian S O'Neill
*/
public class TestWeakValueCache {
public static void main(String[] arg) throws Exception {
Cache<Integer, Integer> cache = new WeakValueCache<Integer, Integer>(100);
for (int i = 0, j = 0; i < 100000; i++, j += 15) {
if (i % 100 == 0) {
System.out.println("Size = " + cache.size());
}
Integer key = new Integer(i);
Integer value = new Integer(j);
cache.put(key, value);
}
int originalSize = cache.size();
while (true) {
System.out.println(cache.size());
System.gc();
Thread.sleep(1000);
System.out.println(cache);
}
}
}
|
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/bigtable/admin/v2/bigtable_table_admin.proto
package com.google.bigtable.admin.v2;
public interface DeleteTableRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.bigtable.admin.v2.DeleteTableRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The unique name of the table to be deleted.
* Values are of the form
* `projects/{project}/instances/{instance}/tables/{table}`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Required. The unique name of the table to be deleted.
* Values are of the form
* `projects/{project}/instances/{instance}/tables/{table}`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
}
|
package UDM.api;
import UDM.models.SearchResult;
import UDM.models.SubscriptionData;
import UDM.models.NFProfile;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
public class NRFServiceRequest {
private String nrfAddress; //to store the adress of NRF in the network
private final MediaType mediaType; //the media tpye to be used in requests by default it is JSON
private Object mapper = new ObjectMapper(); // to map strings into given mediaType(Json,xml)
private OkHttpClient httpClient; //to send http2 requests
private ArrayList<NFProfile> nfProfiles = new ArrayList<>(); //to store discovered network functions profiles
NRFServiceRequest(OkHttpClient okHttpClient, MediaType mediaType, NFProfile NRFProfile) {
nfProfiles.add(NRFProfile);
this.nrfAddress = NRFProfile.getIpv4Address();
this.httpClient = okHttpClient;
this.mediaType = mediaType;
nfProfiles.add(NRFProfile);
}
//registers Network Function to NRF
void nrfRegistration(NFProfile nfProfile, long nfInstanceID){
try {
String requestUrl = nrfAddress+"/nf-instances/"+nfInstanceID;
String json = ((ObjectMapper) mapper).writeValueAsString(nfProfile);
RequestBody body = RequestBody.create(mediaType, json);
System.out.println("REQUEST SENT:\nInfo: Registration Request \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: PUT \nBody: \n" + json);
Request request = new Request.Builder()
.url(requestUrl)
.put(body)
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: Registration Response \nFrom:NRF");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string() + "\n");
}catch (ConnectException n){
System.out.println("ERROR:Couldnt Connect to NRF. Make sure the NRF is online.");
} catch (IOException e) {
e.printStackTrace();
}
}
//deregisters Network Function with given ID from NRF
void nrfDeregistration(long nfInstanceID){
try {
String requestUrl = nrfAddress+"/nf-instances/"+nfInstanceID;
System.out.println("REQUEST SENT: \nInfo: Deregistration Request \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: DELETE");
Request request = new Request.Builder()
.url(requestUrl)
.delete()
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: Deregistration Response \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
//receive Network Function's profile with given ID
void nrfGetNFProfile(long nfInstanceID){
try {
String requestUrl = nrfAddress+"/nf-instances/"+nfInstanceID;
System.out.println("REQUEST SENT: \nInfo: NF Profile Retrieval \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: GET ");
Request request = new Request.Builder()
.url(requestUrl)
.get()
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: NF Profile Retrieval Response \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
//returns all Network functions with specified type
void nrfGetNFProfileList(String nftype, int limit){
try {
String requestUrl = nrfAddress + "/nf-instances/?nf-type=" + nftype + "&limit=" + limit;
System.out.println("REQUEST SENT: \nInfo: NF Profile List Retrieval of specific type \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: GET ");
Request request = new Request.Builder()
.url(requestUrl)
.get()
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: NF Profile Retrieval Response \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
void nrfCreateSubscription(SubscriptionData subscriptionData){
try {
String json;
String requestUrl = nrfAddress + "/subscriptions";
json = ((ObjectMapper) mapper).writeValueAsString(subscriptionData);
RequestBody body = RequestBody.create(mediaType, json);
System.out.println("REQUEST SENT: \nInfo: Subscription Creation \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: POST \nBody:\n " + json);
Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: Subscription Creation \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
void nrfDeleteSubscription(long subscriptionID){
try {
String requestUrl = nrfAddress + "/subscriptions/"+subscriptionID;
System.out.println("REQUEST SENT: \nInfo: Subscription Deletion \nTo: NRF \nAddress: "+requestUrl);
System.out.println("Method: DELETE ");
Request request = new Request.Builder()
.url(requestUrl)
.delete()
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: Subscription Deletion \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
System.out.println("Body: \n" +response.body().string()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
void nrfDiscovery(ArrayList<String> serviceNames, String requesterNftype, String targetNftype, String requesterNfInstanceFQDN){
try {
String requestUrl = nrfAddress + "/nf-instances?target-nf-type="+targetNftype+
"&requester-nf-type="+requesterNftype+
"&requester-nf-instance-fqdn="+requesterNfInstanceFQDN;
Request request = new Request.Builder()
.url(requestUrl)
.get()
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
System.out.println("RESPONSE: \nInfo: NF Discovery \nFrom:NRF ");
System.out.println("Protocol: " + response.protocol().toString());
System.out.println("Code: " + response.code());
String jsonString = response.body().string();
System.out.println("Body: \n" +jsonString+"\n");
try{
SearchResult searchResult1 = ((ObjectMapper) mapper).readValue(jsonString, SearchResult.class);
nfProfiles.addAll(searchResult1.getNfInstances());
}catch (JsonParseException ignored){
}
}catch (IOException e) {
e.printStackTrace();
}
}
//checks if a Network function with given type discovered before and returns it
//if not discovered before it ask use to send discovery request to NRF
NFProfile getNfProfile(String nfType) {
for (NFProfile nf : nfProfiles) {
if(nf.getNfType().equals(nfType)){
return nf;
}
}
System.out.println("ERROR");
System.out.println("There is no "+nfType +" found. Please send NF discovery Message to NRF with nfType.");
return null;
}
}
|
/**
* Copyright (c) 2014, by the Authors: John E Lloyd (UBC)
*
* This software is freely available under a 2-clause BSD license. Please see
* the LICENSE file in the ArtiSynth distribution directory for details.
*/
package artisynth.core.femmodels;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import maspack.matrix.Point3d;
import maspack.matrix.Vector3d;
import maspack.util.ReaderTokenizer;
/**
* A class to read an FEM described in the Abaqus file format.
*/
public class AnsysReader implements FemReader {
/**
* Tells the reader to subdivide each hexahedral element into five
* tetrahedra.
*/
public static int TETRAHEDRALIZE_HEXES = 0x1;
/**
* Tells the reader to number the nodes and elements starting from one.
* This is the same convention as used by ANSYS.
*/
public static int ONE_BASED_NUMBERING = 0x2;
static boolean cwHexWarningGiven;
static boolean cwWedgeWarningGiven;
static boolean cwPyramidWarningGiven;
static boolean cwTetWarningGiven;
static boolean nodeIdWarningGiven;
private File myNodeFile;
private File myElemFile;
public AnsysReader(File nodes, File elems) {
myNodeFile = nodes;
myElemFile = elems;
}
public AnsysReader(String nodeFile, String elemFile) {
myNodeFile = new File(nodeFile);
myElemFile = new File(elemFile);
}
@Override
public FemModel3d readFem(FemModel3d fem) throws IOException {
return read(fem, myNodeFile.getAbsolutePath(), myElemFile.getAbsolutePath());
}
/**
* Creates an FemModel with uniform density based on ANSYS data contained in
* a specified file. The node coordinate data can be scaled non-uniformly
* using an optional parameter giving scale values about the x, y, and z
* axes.
*
* @param model
* FEM model to be populated by ANSYS data. If <code>null</code>, a
* new model is created
* @param nodeFileName
* path name of the ANSYS node file
* @param elemFileName
* path name of the ANSYS element file
* @return created model
* @throws IOException
* if this is a problem reading the file
*/
public static FemModel3d read (
FemModel3d model, String nodeFileName, String elemFileName)
throws IOException {
return read(model, nodeFileName, elemFileName, -1, null, 0);
}
/**
* Creates an FemModel with uniform density based on ANSYS data contained in
* a specified file. The node coordinate data can be scaled non-uniformly
* using an optional parameter giving scale values about the x, y, and z
* axes.
*
* @param model
* FEM model to be populated by ANSYS data. If <code>null</code>, a
* new model is created
* @param nodeFileName
* path name of the ANSYS node file
* @param elemFileName
* path name of the ANSYS element file
* @param density
* density of the model
* @param scale
* if non-null, gives scaling about the x, y, and z axes
* @param options
* option flags. Should be an or-ed combination of
* {@link #TETRAHEDRALIZE_HEXES} and {@link #ONE_BASED_NUMBERING}.
* @return created model
* @throws IOException
* if this is a problem reading the file
*/
public static FemModel3d read (
FemModel3d model, String nodeFileName, String elemFileName,
double density, Vector3d scale, int options)
throws IOException {
Reader nodeReader = null;
Reader elemReader = null;
try {
nodeReader = new FileReader (nodeFileName);
elemReader = new FileReader (elemFileName);
model = read (model, nodeReader, elemReader, density, scale, options);
}
catch (IOException e) {
throw e;
}
finally {
if (nodeReader != null) {
nodeReader.close ();
}
if (elemReader != null) {
elemReader.close ();
}
}
return model;
}
/**
* Creates an FemModel with uniform density based on ANSYS data contained in
* a specified file. The node coordinate data can be scaled non-uniformly
* using an optional parameter giving scale values about the x, y, and z
* axes.
*
* @param model
* FEM model to be populated by ANSYS data. If <code>null</code>, a
* new model is created
* @param nodeReader
* reader supplying node data in the ANSYS format
* @param elemReader
* reader supplying element data in the ANSYS format
* @param density
* density of the model
* @param scale
* if non-null, gives scaling about the x, y, and z axes
* @param options
* option flags. Should be an or-ed combination of
* {@link #TETRAHEDRALIZE_HEXES} and {@link #ONE_BASED_NUMBERING}.
* @return created model
* @throws IOException
* if this is a problem reading the file
*/
public static FemModel3d read (
FemModel3d model, Reader nodeReader, Reader elemReader,
double density, Vector3d scale, int options) throws IOException {
boolean tetrahedralize = (options & TETRAHEDRALIZE_HEXES) != 0;
boolean useAnsysNum = (options & ONE_BASED_NUMBERING) != 0;
if (model == null) {
model = new FemModel3d();
} else {
model.clear ();
}
if (density >= 0) {
model.setDensity (density);
}
if (useAnsysNum) {
model.useAnsysNumbering ();
}
LinkedHashMap<Integer, Point3d> nodeMap = readNodeFile (nodeReader, useAnsysNum);
LinkedHashMap<Integer, Integer> nodeIdMap =
new LinkedHashMap<Integer, Integer> ();
for (int nodeId : nodeMap.keySet ()) {
Point3d pos = nodeMap.get (nodeId);
if (scale != null) {
pos.x *= scale.x;
pos.y *= scale.y;
pos.z *= scale.z;
}
FemNode3d node = new FemNode3d (pos);
model.addNumberedNode (node, nodeId);
// Store new node ID to match with element node IDs
nodeIdMap.put (nodeId, node.getNumber ());
}
LinkedHashMap<Integer, ArrayList<Integer>> elemMap =
readElemFile (elemReader, useAnsysNum);
ArrayList<HexElement> hexElems = new ArrayList<HexElement> ();
boolean flip = false;
if (scale != null) {
double scaleProduct = scale.x*scale.y*scale.z;
flip = (scaleProduct < 0);
}
for (int elemId : elemMap.keySet ()) {
ArrayList<Integer> elemNumList = elemMap.get (elemId);
int[] attrList = new int[5];
for (int i = attrList.length - 1 ; i >= 0 ; i--) {
attrList[i] = elemNumList.remove (0);
}
ArrayList<Integer> nodeList =
getValidElemNodes (elemNumList, nodeIdMap, flip);
switch (nodeList.size ()) {
case 4:
createTet (model, nodeList, elemId, attrList);
break;
case 5:
createPyramid (model, nodeList, elemId, attrList);
break;
case 6:
createWedge (model, nodeList, elemId, attrList);
break;
case 8:
hexElems.add (createHex (model, nodeList, elemId, attrList));
break;
case 10:
createQuadTet (model, nodeList, elemId, attrList);
break;
case 20:
createQuadHex (model, nodeList, elemId, attrList);
break;
default:
System.out.println ("Element "+elemId+": unknown type with " +
nodeList.size() + " nodes; ignoring");
}
}
// TODO implement for quadhex elements
HexElement.setParities (hexElems);
if (tetrahedralize) { // replace all hex elements with tets
for (HexElement hex : hexElems) {
FemNode3d[] n = hex.getNodes ();
TetElement[] tets =
TetElement.createCubeTesselation (
n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], hex
.getParity () == 1);
model.removeElement (hex);
for (TetElement tet : tets) {
model.addElement (tet);
}
}
}
return model;
}
protected static int computeWidths (List<Integer> widths, String line)
throws IOException {
int max = line.length();
int off = 0;
int width = 0;
// skip leading white space
while (off < max) {
width = 0;
// leading white space
while (off < max && Character.isWhitespace((line.charAt(off)))) {
off++;
width++;
}
// digits
while (off < max && Character.isDigit((line.charAt(off)))) {
off++;
width++;
}
widths.add(width);
}
return widths.size();
}
protected static int parseNumber (
ArrayList<Integer> numbers, String line, int off, int maxWidth, int lineno)
throws IOException {
int max = line.length();
// limit maximum digits for the first 13 numbers
if (numbers.size() < 13 && maxWidth > 0) {
max = Math.min (max, off+maxWidth); // maximum number width
}
int c = 0;
// skip leading white space
while (off < max && Character.isWhitespace((c=line.charAt(off)))) {
off++;
}
if (off == max) {
return -1;
}
if (!Character.isDigit(c)) {
throw new IOException (
"Error: non-digit '"+c+"' in file at line "+lineno);
}
int num = 0;
while (off < max && Character.isDigit((c=line.charAt(off)))) {
num = 10*num + (c-'0');
off++;
}
numbers.add (num);
return off;
}
public static LinkedHashMap<Integer, ArrayList<Integer>> readElemFile (
Reader elemReader, boolean useAnsysNum) throws IOException {
LinkedHashMap<Integer, ArrayList<Integer>> elemPositions =
new LinkedHashMap<Integer, ArrayList<Integer>> ();
// ReaderTokenizer rtok =
// new ReaderTokenizer (new BufferedReader (elemReader));
//rtok.eolIsSignificant (true);
int offset = useAnsysNum ? 0 : -1;
int elemId = 0;
String line;
int lineno = 0;
BufferedReader reader = new BufferedReader (elemReader);
line = reader.readLine();
// compute widths
ArrayList<Integer> widths = new ArrayList<Integer>(14);
computeWidths(widths, line);
widths.add(0); // terminal width to prevent crashes if no space at end of line
while (line != null) {
ArrayList<Integer> numbers = new ArrayList<Integer> ();
ArrayList<Integer> elemNumList;
lineno++;
int off = 0;
int nidx = 0;
while ( (off = parseNumber (numbers, line, off, widths.get(nidx), lineno)) != -1) {
nidx++;
// break if at the end of the line
if(off >= line.length()) {
break;
}
}
if (numbers.size() == 14) {
elemNumList = new ArrayList<Integer> ();
for (int i = 0; i < 8; i++) {
elemNumList.add (numbers.get (i) + offset);
}
for (int i = 8; i < 13; i++) {
elemNumList.add (0, numbers.get (i));
}
elemId = numbers.get (13);
}
else {
elemNumList = elemPositions.get (elemId + offset);
for (int i = 0; i < numbers.size(); i++) {
elemNumList.add (numbers.get (i) + offset);
}
}
elemPositions.put (elemId + offset, elemNumList);
// queue-up next line
line = reader.readLine();
}
return elemPositions;
}
protected static LinkedHashMap<Integer, ArrayList<Integer>> readElemFileOld (
Reader elemReader, boolean useAnsysNum) throws IOException {
LinkedHashMap<Integer, ArrayList<Integer>> elemPositions =
new LinkedHashMap<Integer, ArrayList<Integer>> ();
ReaderTokenizer rtok =
new ReaderTokenizer (new BufferedReader (elemReader));
rtok.eolIsSignificant (true);
int offset = useAnsysNum ? 0 : -1;
int elemId = 0;
while (rtok.nextToken () != ReaderTokenizer.TT_EOF) {
rtok.pushBack ();
ArrayList<Integer> curLine = new ArrayList<Integer> ();
ArrayList<Integer> elemNumList;
int nextToken = rtok.nextToken ();
while (nextToken != ReaderTokenizer.TT_EOL &&
nextToken != ReaderTokenizer.TT_EOF) {
curLine.add ((int) rtok.nval);
nextToken = rtok.nextToken ();
}
if (curLine.size() == 14) {
elemNumList = new ArrayList<Integer> ();
for (int i = 0; i < 8; i++) {
elemNumList.add (curLine.get (i) + offset);
}
for (int i = 8; i < 13; i++) {
elemNumList.add (0, curLine.get (i));
}
elemId = curLine.get (13);
}
else {
elemNumList = elemPositions.get (elemId + offset);
for (int i = 0; i < curLine.size(); i++) {
elemNumList.add (curLine.get (i) + offset);
}
}
elemPositions.put (elemId + offset, elemNumList);
}
return elemPositions;
}
public static LinkedHashMap<Integer, Point3d> readNodeFile (
Reader nodeReader, boolean useAnsysNum) throws IOException {
LinkedHashMap<Integer, Point3d> nodePositions =
new LinkedHashMap<Integer, Point3d> ();
ReaderTokenizer rtok =
new ReaderTokenizer (new BufferedReader (nodeReader));
rtok.eolIsSignificant (true);
int offset = useAnsysNum ? 0 : -1;
while (rtok.nextToken () != ReaderTokenizer.TT_EOF) {
rtok.pushBack ();
int nodeId = rtok.scanInteger ();
Point3d pos = new Point3d ();
double[] posArray = new double[3];
for (int i = 0; i < posArray.length; i++) {
int nextToken = rtok.nextToken();
if (nextToken == ReaderTokenizer.TT_EOL) {
throw new IOException ("Unexpected EOL, " + rtok);
}
else if (nextToken == ReaderTokenizer.TT_NUMBER) {
posArray[i] = rtok.nval;
}
else {
i--;
}
}
pos.x = posArray[0];
pos.y = posArray[1];
pos.z = posArray[2];
nodePositions.put (nodeId + offset, pos);
int nextToken;
do {
nextToken = rtok.nextToken ();
} while (nextToken != ReaderTokenizer.TT_EOL &&
nextToken != ReaderTokenizer.TT_EOF);
}
return nodePositions;
}
private static ArrayList<Integer> getValidElemNodes (
ArrayList<Integer> nodeList, HashMap<Integer, Integer> nodeIdMap,
boolean reverse) {
int nNodes = nodeList.size();
ArrayList<Integer> validNodeIds = new ArrayList<Integer> (nNodes);
for (int i = 0; i < nNodes; i++) {
int nodeId;
nodeId = nodeList.get (i);
if (nodeId >= 0) {
Integer validId = nodeIdMap.get (nodeId);
if (validId != null && !validNodeIds.contains (validId)) {
validNodeIds.add (validId);
}
}
}
return validNodeIds;
}
private static void createTet (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
TetElement e;
if (TetElement.computeVolume (n0, n1, n2, n3) >= 0) {
e = new TetElement (n0, n1, n2, n3);
}
else {
e = new TetElement (n0, n2, n1, n3);
if (cwTetWarningGiven) {
System.out.println ("found cw tet");
cwTetWarningGiven = true;
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
}
private static void createQuadTet (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
FemNode3d n4 = model.getByNumber (nodeIds.get (4));
FemNode3d n5 = model.getByNumber (nodeIds.get (5));
FemNode3d n6 = model.getByNumber (nodeIds.get (6));
FemNode3d n7 = model.getByNumber (nodeIds.get (7));
FemNode3d n8 = model.getByNumber (nodeIds.get (8));
FemNode3d n9 = model.getByNumber (nodeIds.get (9));
QuadtetElement e;
if (TetElement.computeVolume (n0, n1, n2, n3) >= 0) {
e = new QuadtetElement (n0, n1, n2, n3, n4, n5, n6,
n7, n8, n9);
}
else {
e = new QuadtetElement (n0, n2, n1, n3, n6, n5, n4,
n7, n9, n8);
if (cwTetWarningGiven) {
System.out.println ("found ccw quadtet");
cwTetWarningGiven = true;
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
}
private static HexElement createHex (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
FemNode3d n4 = model.getByNumber (nodeIds.get (4));
FemNode3d n5 = model.getByNumber (nodeIds.get (5));
FemNode3d n6 = model.getByNumber (nodeIds.get (6));
FemNode3d n7 = model.getByNumber (nodeIds.get (7));
HexElement e;
if (HexElement.computeVolume (n3, n2, n1, n0, n7, n6, n5, n4) >= 0) {
e = new HexElement (n3, n2, n1, n0, n7, n6, n5, n4);
}
else {
e = new HexElement (n0, n1, n2, n3, n4, n5, n6, n7);
if (!cwHexWarningGiven) {
System.out.println ("found cw hex");
cwHexWarningGiven = true;
}
if (e.computeVolumes () < 0) {
System.out.println ("found neg volume hex, # " + e.getNumber ());
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
return e;
}
private static void createQuadHex (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
FemNode3d n4 = model.getByNumber (nodeIds.get (4));
FemNode3d n5 = model.getByNumber (nodeIds.get (5));
FemNode3d n6 = model.getByNumber (nodeIds.get (6));
FemNode3d n7 = model.getByNumber (nodeIds.get (7));
FemNode3d n8 = model.getByNumber (nodeIds.get (8));
FemNode3d n9 = model.getByNumber (nodeIds.get (9));
FemNode3d n10 = model.getByNumber (nodeIds.get (10));
FemNode3d n11 = model.getByNumber (nodeIds.get (11));
FemNode3d n12 = model.getByNumber (nodeIds.get (12));
FemNode3d n13 = model.getByNumber (nodeIds.get (13));
FemNode3d n14 = model.getByNumber (nodeIds.get (14));
FemNode3d n15 = model.getByNumber (nodeIds.get (15));
FemNode3d n16 = model.getByNumber (nodeIds.get (16));
FemNode3d n17 = model.getByNumber (nodeIds.get (17));
FemNode3d n18 = model.getByNumber (nodeIds.get (18));
FemNode3d n19 = model.getByNumber (nodeIds.get (19));
QuadhexElement e;
if (HexElement.computeVolume (n3, n2, n1, n0, n7, n6, n5, n4) >= 0) {
e = new QuadhexElement (
new FemNode3d[] {n3, n2, n1, n0, n7, n6, n5, n4, n10, n9, n8, n11,
n14, n13, n12, n15, n19, n18, n17, n16});
}
else {
e = new QuadhexElement (
new FemNode3d[] {n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11,
n12, n13, n14, n15, n16, n17, n18, n19});
if (!cwHexWarningGiven) {
System.out.println ("found cw quadhex");
cwHexWarningGiven = true;
}
if (e.computeVolumes () < 0) {
System.out.println ("found neg volume quadhex, # " + e.getNumber ());
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
}
private static void createPyramid (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
FemNode3d n4 = model.getByNumber (nodeIds.get (4));
PyramidElement e = new PyramidElement (n0, n1, n2, n3, n4);
if (e.computeVolumes () < 0) {
e = new PyramidElement (n0, n3, n2, n1, n4);
if (!cwPyramidWarningGiven) {
System.out.println ("found ccw pyramid");
cwPyramidWarningGiven = true;
}
if (e.computeVolumes () < 0) {
System.out.println ("found inverted pyramid, # " + e.getNumber ());
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
}
private static void createWedge (FemModel3d model,
ArrayList<Integer> nodeIds, int elemId, int[] attrList) {
FemNode3d n0 = model.getByNumber (nodeIds.get (0));
FemNode3d n1 = model.getByNumber (nodeIds.get (1));
FemNode3d n2 = model.getByNumber (nodeIds.get (2));
FemNode3d n3 = model.getByNumber (nodeIds.get (3));
FemNode3d n4 = model.getByNumber (nodeIds.get (4));
FemNode3d n5 = model.getByNumber (nodeIds.get (5));
WedgeElement e = new WedgeElement (n0, n1, n2, n3, n4, n5);
if (e.computeVolumes () < 0) {
e = new WedgeElement (n2, n1, n0, n5, n4, n3);
if (!cwWedgeWarningGiven) {
System.out.println ("found ccw wedge");
cwWedgeWarningGiven = true;
}
if (e.computeVolumes () < 0) {
System.out.println ("found inverted wedge, # " + e.getNumber ());
}
}
model.addNumberedElement (e, elemId);
model.ansysElemProps.put (e, attrList);
}
// private static void createTetsFromHex (FemModel3d model, int[] idxs) {
// TetElement[] elems =
// TetElement.createCubeTesselation (model.getNode (idxs[0]), model
// .getNode (idxs[1]), model.getNode (idxs[2]), model
// .getNode (idxs[3]), model.getNode (idxs[4]), model
// .getNode (idxs[5]), model.getNode (idxs[6]), model
// .getNode (idxs[7]), true);
// for (TetElement tet : elems)
// model.addElement (tet);
// }
// private static void createTetsFromWedge (FemModel3d model, int[] idxs) {
// TetElement[] elems =
// TetElement.createWedgeTesselation (model.getNode (idxs[0]), model
// .getNode (idxs[2]), model.getNode (idxs[1]), model
// .getNode (idxs[3]), model.getNode (idxs[5]), model
// .getNode (idxs[4]), true);
// for (TetElement tet : elems)
// model.addElement (tet);
// }
public static Integer[] readNodeIdxs (Reader nodeReader) throws IOException {
ReaderTokenizer rtok =
new ReaderTokenizer (new BufferedReader (nodeReader));
Point3d coords = new Point3d ();
ArrayList<Integer> nodeIds = new ArrayList<Integer> ();
while (rtok.nextToken () != ReaderTokenizer.TT_EOF) {
rtok.pushBack ();
int nodeId = rtok.scanInteger ();
nodeIds.add (nodeId);
coords.x = rtok.scanNumber ();
coords.y = rtok.scanNumber ();
coords.z = rtok.scanNumber ();
}
return nodeIds.toArray (new Integer[0]);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
/**
* An Iterator over the lines in a <code>Reader</code>.
* <p>
* <code>LineIterator</code> holds a reference to an open <code>Reader</code>.
* When you have finished with the iterator you should close the reader
* to free internal resources. This can be done by closing the reader directly,
* or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)}
* method on the iterator.
* <p>
* The recommended usage pattern is:
* <pre>
* LineIterator it = FileUtils.lineIterator(file, "UTF-8");
* try {
* while (it.hasNext()) {
* String line = it.nextLine();
* // do something with line
* }
* } finally {
* it.close();
* }
* </pre>
*
* @since 1.2
*/
public class LineIterator implements Iterator<String>, Closeable {
// N.B. This class deliberately does not implement Iterable, see https://issues.apache.org/jira/browse/IO-181
/** The reader that is being read. */
private final BufferedReader bufferedReader;
/** The current line. */
private @Nullable String cachedLine;
/** A flag indicating if the iterator has been fully read. */
private boolean finished = false;
/**
* Constructs an iterator of the lines for a <code>Reader</code>.
*
* @param reader the <code>Reader</code> to read from, not null
* @throws IllegalArgumentException if the reader is null
*/
public LineIterator(final Reader reader) throws IllegalArgumentException {
if (reader == null) {
throw new IllegalArgumentException("Reader must not be null");
}
if (reader instanceof BufferedReader) {
bufferedReader = (BufferedReader) reader;
} else {
bufferedReader = new BufferedReader(reader);
}
}
//-----------------------------------------------------------------------
/**
* Indicates whether the <code>Reader</code> has more lines.
* If there is an <code>IOException</code> then {@link #close()} will
* be called on this instance.
*
* @return {@code true} if the Reader has more lines
* @throws IllegalStateException if an IO exception occurs
*/
@Override
@EnsuresNonNullIf(expression = "cachedLine", result = true)
public boolean hasNext() {
if (cachedLine != null) {
return true;
} else if (finished) {
return false;
} else {
try {
while (true) {
final String line = bufferedReader.readLine();
if (line == null) {
finished = true;
return false;
} else if (isValidLine(line)) {
cachedLine = line;
return true;
}
}
} catch(final IOException ioe) {
IOUtils.closeQuietly(this, e -> ioe.addSuppressed(e));
throw new IllegalStateException(ioe);
}
}
}
/**
* Overridable method to validate each line that is returned.
* This implementation always returns true.
* @param line the line that is to be validated
* @return true if valid, false to remove from the iterator
*/
protected boolean isValidLine(final String line) {
return true;
}
/**
* Returns the next line in the wrapped <code>Reader</code>.
*
* @return the next line from the input
* @throws NoSuchElementException if there is no line to return
*/
@Override
public String next() {
return nextLine();
}
/**
* Returns the next line in the wrapped <code>Reader</code>.
*
* @return the next line from the input
* @throws NoSuchElementException if there is no line to return
*/
public String nextLine() {
if (!hasNext()) {
throw new NoSuchElementException("No more lines");
}
final String currentLine = cachedLine;
cachedLine = null;
return currentLine;
}
/**
* Closes the underlying {@code Reader}.
* This method is useful if you only want to process the first few
* lines of a larger file. If you do not close the iterator
* then the {@code Reader} remains open.
* This method can safely be called multiple times.
*
* @throws IOException if closing the underlying {@code Reader} fails.
*/
@Override
public void close() throws IOException {
finished = true;
cachedLine = null;
IOUtils.close(bufferedReader);
}
/**
* Unsupported.
*
* @throws UnsupportedOperationException always
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Remove unsupported on LineIterator");
}
//-----------------------------------------------------------------------
/**
* Closes a {@code LineIterator} quietly.
*
* @param iterator The iterator to close, or {@code null}.
* @deprecated As of 2.6 deprecated without replacement. Please use the try-with-resources statement or handle
* suppressed exceptions manually.
* @see Throwable#addSuppressed(java.lang.Throwable)
*/
@Deprecated
public static void closeQuietly(final @Nullable LineIterator iterator) {
IOUtils.closeQuietly(iterator);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.janquadflieg.mrracer.classification;
import de.janquadflieg.mrracer.telemetry.SensorData;
import java.awt.geom.Point2D;
import javax.vecmath.Vector2d;
/**
*
* @author Jan Quadflieg
*/
public class AngleBasedClassifier {
private boolean advanced = false;
private float[] angles = new float[19];
public final static double STRAIGHT_FULL = 3.0;
public final static double FULL_MEDIUM = 20.0;
public final static double MEDIUM_SLOW = 35.0;
public final static double SLOW_HAIRPIN = 60.0;
private int maxNum = Integer.MIN_VALUE;
public AngleBasedClassifier(int n){
advanced = true;
// init angles
for (int i = 0; i < 19; ++i) {
angles[i] = -90 + i * 10;
}
maxNum = n;
}
public AngleBasedClassifier(boolean b) {
advanced = b;
// init angles
for (int i = 0; i < 19; ++i) {
angles[i] = -90 + i * 10;
}
}
public AngleBasedClassifier(float[] f) {
advanced = true;
System.arraycopy(f, 0, angles, 0, f.length);
}
public Situation classify(SensorData data) {
if (data.getTrackPosition() > 1.0 || data.getTrackPosition() < -1.0) {
int side = Situations.DIRECTION_LEFT;
if (data.getTrackPosition() < -1.0) {
side = Situations.DIRECTION_RIGHT;
}
return new Situation(Situations.ERROR_NONE | Situations.TYPE_OUTSIDE | side, 0, 0);
}
if (Math.toDegrees(data.getAngleToTrackAxis()) < -80
|| Math.toDegrees(data.getAngleToTrackAxis()) > 80) {
return new Situation(Situations.ERROR_UNABLE_TO_CLASSIFY, 0, 0);
}
double value;
if (advanced) {
value = measure2(data);
} else {
value = measure(data);
}
double absv = Math.abs(value);
double sign = Math.signum(value);
int direction = Situations.DIRECTION_FORWARD;
int type = Situations.TYPE_FULL;
if (value >= -3.0 && value <= 3.0) {
double dtc = biggestSensorValue(data);
if (dtc < 90) {
return new Situation(Situations.STRAIGHT_AC, value, dtc);
} else {
return new Situation(Situations.STRAIGHT, value, 0);
}
} else {
// some kind of type
if (sign == -1) {
direction = Situations.DIRECTION_RIGHT;
} else {
direction = Situations.DIRECTION_LEFT;
}
if (absv > STRAIGHT_FULL && absv <= FULL_MEDIUM) {
type = Situations.TYPE_FULL;
} else if (absv > FULL_MEDIUM && absv <= MEDIUM_SLOW) {
type = Situations.TYPE_MEDIUM;
} else if (absv > MEDIUM_SLOW && absv <= SLOW_HAIRPIN) {
type = Situations.TYPE_SLOW;
} else {
type = Situations.TYPE_HAIRPIN;
}
return new Situation(Situations.ERROR_NONE | direction | type, value, 0);
}
}
public double measure(SensorData data) {
// Calculate coordinates
Point2D[] points = SensorData.calculateTrackPoints(data, angles);
// Find the index of the biggest sensor value
int index = SensorData.maxTrackIndexLeft(data);
return calculateAngle(points, index, index);
}
public double measure2(SensorData data) {
// Calculate coordinates
Point2D[] points = SensorData.calculateTrackPoints(data);
// Find the indeces of the biggest sensor value
int leftIndex = SensorData.maxTrackIndexLeft(data);
int rightIndex = SensorData.maxTrackIndexRight(data);
if(this.maxNum != Integer.MIN_VALUE){
leftIndex = Math.min(leftIndex, maxNum+2);
rightIndex = Math.max(rightIndex, 18-(maxNum+2));
}
return calculateAngle(points, leftIndex, rightIndex);
}
private static double calculateAngle(Point2D[] points, int leftIndex, int rightIndex) {
double angleLeft = 0;
if (leftIndex > 2) {
Vector2d[] vectors = new Vector2d[leftIndex - 1];
for (int i = 0; i < vectors.length; ++i) {
Point2D first = points[i];
Point2D second = points[i + 1];
vectors[i] = new Vector2d(second.getX() - first.getX(),
second.getY() - first.getY());
vectors[i].normalize();
}
//System.out.print("Left: ");
angleLeft = AngleBasedClassifier.sumAngles(vectors);
//System.out.println("");
}
double angleRight = 0;
if (rightIndex < points.length - 3) {
Vector2d[] vectors = new Vector2d[points.length - (rightIndex + 2)];
for (int i = 0; i < vectors.length; ++i) {
Point2D first = points[points.length - (1 + i)];
Point2D second = points[points.length - (2 + i)];
vectors[i] = new Vector2d(second.getX() - first.getX(),
second.getY() - first.getY());
vectors[i].normalize();
}
//System.out.print("Right: ");
angleRight = AngleBasedClassifier.sumAngles(vectors);
//System.out.println("");
}
return angleLeft + angleRight;
}
private double biggestSensorValue(SensorData data) {
double max = Double.NEGATIVE_INFINITY;
double[] trackSensors = data.getTrackEdgeSensors();
for (int i = 0; i < trackSensors.length; ++i) {
max = Math.max(max, trackSensors[i]);
}
return max;
}
public static double sumAngles(Vector2d[] vectors) {
double result = 0;
for (int i = 0; i < vectors.length - 1; ++i) {
Vector2d first = vectors[i];
Vector2d second = vectors[i + 1];
double angleD = Math.toDegrees(first.angle(second));
double crossZ = (first.getX() * second.getY())
- (first.getY() * second.getX());
double sign = Math.signum(crossZ);
angleD *= sign;
//System.out.println("Angle[i]: "+angleD);
//System.out.print(Utils.doubleToString(angleD)+", ");
result += angleD;
}
return result;
}
}
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class TestGZip {
@Test
public void testBasic() throws Exception {
final String s = "some kind of text";
final StringEntity e = new StringEntity(s, ContentType.TEXT_PLAIN);
e.setChunked(false);
final GzipCompressingEntity gzipe = new GzipCompressingEntity(e);
Assert.assertTrue(gzipe.isChunked());
Assert.assertEquals(-1, gzipe.getContentLength());
Assert.assertNotNull(gzipe.getContentEncoding());
Assert.assertEquals("gzip", gzipe.getContentEncoding().getValue());
}
@Test
public void testCompressionDecompression() throws Exception {
final StringEntity in = new StringEntity("some kind of text", ContentType.TEXT_PLAIN);
final GzipCompressingEntity gzipe = new GzipCompressingEntity(in);
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
gzipe.writeTo(buf);
final ByteArrayEntity out = new ByteArrayEntity(buf.toByteArray());
final GzipDecompressingEntity gunzipe = new GzipDecompressingEntity(out);
Assert.assertEquals("some kind of text", EntityUtils.toString(gunzipe, Consts.ASCII));
}
@Test
public void testCompressionIOExceptionLeavesOutputStreamOpen() throws Exception {
final HttpEntity in = Mockito.mock(HttpEntity.class);
Mockito.doThrow(new IOException("Ooopsie")).when(in).writeTo(Mockito.<OutputStream>any());
final GzipCompressingEntity gzipe = new GzipCompressingEntity(in);
final OutputStream out = Mockito.mock(OutputStream.class);
try {
gzipe.writeTo(out);
} catch (final IOException ex) {
Mockito.verify(out, Mockito.never()).close();
}
}
}
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.systemtest;
import java.time.Duration;
/**
* Interface for keep global constants used across system tests.
*/
public interface Constants {
long TIMEOUT_FOR_DEPLOYMENT_CONFIG_READINESS = Duration.ofMinutes(7).toMillis();
long TIMEOUT_FOR_RESOURCE_CREATION = Duration.ofMinutes(5).toMillis();
long TIMEOUT_FOR_SECRET_CREATION = Duration.ofMinutes(2).toMillis();
long TIMEOUT_FOR_RESOURCE_READINESS = Duration.ofMinutes(14).toMillis();
long TIMEOUT_FOR_RESOURCE_DELETION = Duration.ofMinutes(1).toMillis();
long TIMEOUT_FOR_POD_DELETION = Duration.ofMinutes(5).toMillis();
long TIMEOUT_FOR_CR_CREATION = Duration.ofMinutes(3).toMillis();
long TIMEOUT_FOR_MIRROR_MAKER_COPY_MESSAGES_BETWEEN_BROKERS = Duration.ofMinutes(7).toMillis();
long TIMEOUT_FOR_MIRROR_JOIN_TO_GROUP = Duration.ofMinutes(2).toMillis();
long TIMEOUT_FOR_TOPIC_CREATION = Duration.ofMinutes(1).toMillis();
long TIMEOUT_FOR_LOG = Duration.ofMinutes(2).toMillis();
long POLL_INTERVAL_FOR_RESOURCE_CREATION = Duration.ofSeconds(3).toMillis();
long POLL_INTERVAL_FOR_RESOURCE_READINESS = Duration.ofSeconds(1).toMillis();
long POLL_INTERVAL_FOR_RESOURCE_DELETION = Duration.ofSeconds(5).toMillis();
long WAIT_FOR_ROLLING_UPDATE_INTERVAL = Duration.ofSeconds(5).toMillis();
long WAIT_FOR_ROLLING_UPDATE_TIMEOUT = Duration.ofMinutes(7).toMillis();
long TIMEOUT_FOR_SEND_RECEIVE_MSG = Duration.ofSeconds(60).toMillis();
long TIMEOUT_AVAILABILITY_TEST = Duration.ofMinutes(1).toMillis();
long TIMEOUT_FOR_CLUSTER_STABLE = Duration.ofMinutes(20).toMillis();
long TIMEOUT_FOR_ZK_CLUSTER_STABILIZATION = Duration.ofMinutes(7).toMillis();
long GET_BROKER_API_TIMEOUT = Duration.ofMinutes(1).toMillis();
long GET_BROKER_API_INTERVAL = Duration.ofSeconds(5).toMillis();
long TIMEOUT_FOR_GET_SECRETS = Duration.ofMinutes(1).toMillis();
long TIMEOUT_TEARDOWN = Duration.ofSeconds(10).toMillis();
long GLOBAL_TIMEOUT = Duration.ofMinutes(5).toMillis();
long GLOBAL_STATUS_TIMEOUT = Duration.ofMinutes(3).toMillis();
long CONNECT_STATUS_TIMEOUT = Duration.ofMinutes(5).toMillis();
long GLOBAL_POLL_INTERVAL = Duration.ofSeconds(1).toMillis();
long PRODUCER_POLL_INTERVAL = Duration.ofSeconds(30).toMillis();
long PRODUCER_TIMEOUT = Duration.ofSeconds(25).toMillis();
long GLOBAL_TRACING_POLL = Duration.ofSeconds(30).toMillis();
long GLOBAL_TRACING_TIMEOUT = Duration.ofMinutes(7).toMillis();
long GLOBAL_CLIENTS_POLL = Duration.ofSeconds(15).toMillis();
long GLOBAL_CLIENTS_TIMEOUT = Duration.ofMinutes(2).toMillis();
long GLOBAL_CLIENTS_EXCEPT_ERROR_TIMEOUT = Duration.ofSeconds(10).toMillis();
long CO_OPERATION_TIMEOUT_DEFAULT = Duration.ofMinutes(5).toMillis();
long CO_OPERATION_TIMEOUT_SHORT = Duration.ofSeconds(30).toMillis();
long CO_OPERATION_TIMEOUT_MEDIUM = Duration.ofMinutes(2).toMillis();
long CO_OPERATION_TIMEOUT_WAIT = CO_OPERATION_TIMEOUT_SHORT + Duration.ofSeconds(80).toMillis();
long CO_OPERATION_TIMEOUT_POLL = Duration.ofSeconds(2).toMillis();
long RECONCILIATION_INTERVAL = Duration.ofSeconds(30).toMillis();
// stability count ensures that after some reconciliation we have some additional time
int GLOBAL_STABILITY_OFFSET_COUNT = 20;
// it is replacement instead of checking logs for reconciliation using dynamic waiting on some change for some period of time
int GLOBAL_RECONCILIATION_COUNT = (int) ((RECONCILIATION_INTERVAL / GLOBAL_POLL_INTERVAL) + GLOBAL_STABILITY_OFFSET_COUNT);
/**
* Constants for Kafka clients labels
*/
String KAFKA_CLIENTS_LABEL_KEY = "user-test-app";
String KAFKA_CLIENTS_LABEL_VALUE = "kafka-clients";
String KAFKA_CLIENTS = "kafka-clients";
String STRIMZI_DEPLOYMENT_NAME = "strimzi-cluster-operator";
String ALWAYS_IMAGE_PULL_POLICY = "Always";
String IF_NOT_PRESENT_IMAGE_PULL_POLICY = "IfNotPresent";
/**
* Constants for specific ports
*/
int HTTP_KEYCLOAK_DEFAULT_PORT = 8080;
int HTTPS_KEYCLOAK_DEFAULT_PORT = 8443;
int COMPONENTS_METRICS_PORT = 9404;
int CLUSTER_OPERATOR_METRICS_PORT = 8080;
int USER_OPERATOR_METRICS_PORT = 8081;
int TOPIC_OPERATOR_METRICS_PORT = 8080;
String DEPLOYMENT = "Deployment";
String SERVICE = "Service";
String INGRESS = "Ingress";
String CLUSTER_ROLE_BINDING = "ClusterRoleBinding";
String ROLE_BINDING = "RoleBinding";
/**
* Kafka Bridge JSON encoding with JSON embedded format
*/
String KAFKA_BRIDGE_JSON_JSON = "application/vnd.kafka.json.v2+json";
/**
* Kafka Bridge JSON encoding
*/
String KAFKA_BRIDGE_JSON = "application/vnd.kafka.v2+json";
String DEFAULT_SINK_FILE_PATH = "/tmp/test-file-sink.txt";
int HTTP_BRIDGE_DEFAULT_PORT = 8080;
int HTTP_JAEGER_DEFAULT_TCP_PORT = 5778;
int HTTP_JAEGER_DEFAULT_NODE_PORT = 32480;
int HTTPS_KEYCLOAK_DEFAULT_NODE_PORT = 32481;
int HTTP_KEYCLOAK_DEFAULT_NODE_PORT = 32482;
/**
* Default value which allows execution of tests with any tags
*/
String DEFAULT_TAG = "all";
/**
* Tag for acceptance tests, which are triggered for each push/pr/merge on travis-ci
*/
String ACCEPTANCE = "acceptance";
/**
* Tag for regression tests which are stable.
*/
String REGRESSION = "regression";
/**
* Tag for upgrade tests.
*/
String UPGRADE = "upgrade";
/**
* Tag for acceptance tests executed during Travis builds.
*/
String TRAVIS = "travis";
/**
* Tag for tests, which results are not 100% reliable on all testing environments.
*/
String FLAKY = "flaky";
/**
* Tag for scalability tests
*/
String SCALABILITY = "scalability";
/**
* Tag for tests, which are working only on specific environment and we usually don't want to execute them on all environments.
*/
String SPECIFIC = "specific";
/**
* Tag for tests, which are using NodePort.
*/
String NODEPORT_SUPPORTED = "nodeport";
/**
* Tag for tests, which are using LoadBalancer.
*/
String LOADBALANCER_SUPPORTED = "loadbalancer";
/**
* Tag for tests, which are using NetworkPolicies.
*/
String NETWORKPOLICIES_SUPPORTED = "networkpolicies";
/**
* Tag for Prometheus tests
*/
String PROMETHEUS = "prometheus";
/**
* Tag for Tracing tests
*/
String TRACING = "tracing";
/**
* Tag for Helm tests
*/
String HELM = "helm";
/**
* Tag for oauth tests
*/
String OAUTH = "oauth";
/**
* Tag for recovery tests
*/
String RECOVERY = "recovery";
/**
* Tag for tests which deploys KafkaConnector resource
*/
String CONNECTOR_OPERATOR = "connectoroperator";
/**
* Tag for tests which deploys KafkaConnect resource
*/
String CONNECT = "connect";
/**
* Tag for tests which deploys KafkaConnectS2I resource
*/
String CONNECT_S2I = "connects2i";
/**
* Tag for tests which deploys KafkaMirrorMaker resource
*/
String MIRROR_MAKER = "mirrormaker";
/**
* Tag for tests which deploys KafkaMirrorMaker2 resource
*/
String MIRROR_MAKER2 = "mirrormaker2";
/**
* Tag for tests which deploys any of KafkaConnect, KafkaConnects2i, KafkaConnector, KafkaMirrorMaker2
*/
String CONNECT_COMPONENTS = "connectcomponents";
/**
* Tag for tests which deploys KafkaBridge resource
*/
String BRIDGE = "bridge";
/**
* Tag for tests which use internal Kafka clients (used clients in cluster)
*/
String INTERNAL_CLIENTS_USED = "internalclients";
/**
* Tag for tests which use external Kafka clients (called from test code)
*/
String EXTERNAL_CLIENTS_USED = "externalclients";
/**
* Tag for tests where metrics are used
*/
String METRICS = "metrics";
}
|
package com.walmartlabs.concord.sdk;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2019 Walmart 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.
* =====
*/
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
/**
* Provides a way for the runtime and plugins to retrieve and cache
* various external artifacts.
* Supports all dependency types as the regular "dependencies" configuration.
*/
public interface DependencyManager {
/**
* Downloads the URL or returns a previously cached copy.
*/
Path resolve(URI uri) throws IOException;
}
|
package de.metas.ui.web.pickingslotsClearing.process;
import de.metas.handlingunits.HuId;
import de.metas.handlingunits.model.I_M_HU;
import de.metas.handlingunits.picking.IHUPickingSlotBL;
import de.metas.handlingunits.picking.PickingCandidateService;
import de.metas.process.IProcessPrecondition;
import de.metas.process.ProcessPreconditionsResolution;
import de.metas.ui.web.picking.pickingslot.PickingSlotRow;
import de.metas.ui.web.pickingslotsClearing.PickingSlotsClearingView;
import de.metas.ui.web.window.datatypes.DocumentIdsSelection;
import de.metas.util.Check;
import de.metas.util.Services;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.SpringContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
/*
* #%L
* metasfresh-webui-api
* %%
* Copyright (C) 2017 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public class WEBUI_PickingSlotsClearingView_TakeOutHU extends PickingSlotsClearingViewBasedProcess implements IProcessPrecondition
{
private final transient IHUPickingSlotBL huPickingSlotBL = Services.get(IHUPickingSlotBL.class);
private final PickingCandidateService pickingCandidateService = SpringContextHolder.instance.getBean(PickingCandidateService.class);
private final List<HUExtractedFromPickingSlotEvent> husExtractedEvents = new ArrayList<>();
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final PickingSlotRow row = getSingleSelectedPickingSlotRow();
if (!row.isTopLevelHU())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select a top level HU");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
//
// Get the HU
final PickingSlotRow huRow = getSingleSelectedPickingSlotRow();
Check.assume(huRow.isTopLevelHU(), "row {} shall be a top level HU", huRow);
final I_M_HU hu = InterfaceWrapperHelper.load(huRow.getHuId(), I_M_HU.class);
//
// Remove the HU from it's picking slot
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(hu);
//
// Make sure the HU has the BPartner/Location of the picking slot
final PickingSlotRow pickingSlotRow = getRootRowForSelectedPickingSlotRows();
if (pickingSlotRow.getBPartnerId() > 0)
{
hu.setC_BPartner_ID(pickingSlotRow.getBPartnerId());
hu.setC_BPartner_Location_ID(pickingSlotRow.getBPartnerLocationId());
InterfaceWrapperHelper.save(hu);
}
//
// Move the HU to an after picking locator
moveToAfterPickingLocator(hu);
//
// Inactive all those picking candidates
pickingCandidateService.inactivateForHUId(HuId.ofRepoId(hu.getM_HU_ID()));
husExtractedEvents.add(HUExtractedFromPickingSlotEvent.builder()
.huId(hu.getM_HU_ID())
.bpartnerId(hu.getC_BPartner_ID())
.bpartnerLocationId(hu.getC_BPartner_Location_ID())
.build());
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Invalidate the views
// Expectation: the HU shall disappear from picking slots view (left side) and shall appear on after picking HUs view (right side).
final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView();
invalidateView(pickingSlotsClearingView.getViewId());
//
husExtractedEvents.forEach(pickingSlotsClearingView::handleEvent);
}
}
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.server.model;
public interface ExternalFileBasedAuthenticationManager<X extends ExternalFileBasedAuthenticationManager<X>> extends PasswordCredentialManagingAuthenticationProvider<X>
{
String PATH = "path";
@ManagedAttribute( mandatory = true, description = "File location", immutable = true)
public String getPath();
}
|
package fr.axel.simpleinventoryspring.controller;
import fr.axel.simpleinventoryspring.entity.Warranty;
import fr.axel.simpleinventoryspring.service.WarrantyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "/api/v1/warranties")
public class WarrantyController {
private final WarrantyService warrantyService;
@Autowired
public WarrantyController(WarrantyService warrantyService) {
this.warrantyService = warrantyService;
}
@GetMapping
public List<Warranty> getWarranty() {
return warrantyService.getWarranty();
}
@GetMapping(path = "{warrantyId}")
public Warranty getWarrantyById(@PathVariable("warrantyId") Long warrantyId) {
return warrantyService.getWarrantyById(warrantyId);
}
@DeleteMapping(path = "{warrantyId}")
public void deleteWarranty(@PathVariable("warrantyId") Long warrantyId) {
warrantyService.deleteWarrantyById(warrantyId);
}
@PatchMapping(path = "{warrantyId}")
public Warranty updateWarranty(@PathVariable("warrantyId") Long warrantyId, @RequestBody Warranty updates) {
return warrantyService.updateWarranty(warrantyId, updates);
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.commands;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.Drivetrain;
/**
* Creates a new DriveDistance.
*/
public class DriveDistance extends CommandBase {
private Drivetrain mdrivetrain;
private double requestedDistance;
public DriveDistance(final Drivetrain drivetrain, final double distance) {
// Use addRequirements() here to declare subsystem dependencies.
mdrivetrain = drivetrain;
requestedDistance = distance;
addRequirements(mdrivetrain);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
mdrivetrain.resetDistanceTravelled();
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if(requestedDistance >= 0) {
mdrivetrain.tankDrive(0.4, 0.4, false);
} else {
mdrivetrain.tankDrive(-0.4, -0.4, false);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(final boolean interrupted) {
mdrivetrain.tankDrive(0,0);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
if(requestedDistance >= 0) {
if(mdrivetrain.getDistanceTravelled() >= requestedDistance) {
return true;
} else {
return false;
}
} else {
if(mdrivetrain.getDistanceTravelled() <= requestedDistance) {
return true;
} else {
return false;
}
}
//return false;
}
}
|
package com.example.android.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* {@link ForecastAdapter} exposes a list of weather forecasts
* from a {@link Cursor} to a {@link android.widget.ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
private static final int VIEW_TYPE_COUNT = 2;
private static final int VIEW_TYPE_TODAY = 0;
private static final int VIEW_TYPE_FUTURE_DAY = 1;
// Flag to determine if we want to use a separate view for "today".
private boolean mUseTodayLayout = true;
/**
* Cache of the children views for a forecast list item.
*/
public static class ViewHolder {
public final ImageView iconView;
public final TextView dateView;
public final TextView descriptionView;
public final TextView highTempView;
public final TextView lowTempView;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
dateView = (TextView) view.findViewById(R.id.list_item_date_textview);
descriptionView = (TextView) view.findViewById(R.id.list_item_forecast_textview);
highTempView = (TextView) view.findViewById(R.id.list_item_high_textview);
lowTempView = (TextView) view.findViewById(R.id.list_item_low_textview);
}
}
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Choose the layout type
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
switch (viewType) {
case VIEW_TYPE_TODAY: {
layoutId = R.layout.list_item_forecast_today;
break;
}
case VIEW_TYPE_FUTURE_DAY: {
layoutId = R.layout.list_item_forecast;
break;
}
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
int viewType = getItemViewType(cursor.getPosition());
switch (viewType) {
case VIEW_TYPE_TODAY: {
// Get weather icon
viewHolder.iconView.setImageResource(Utility.getArtResourceForWeatherCondition(
cursor.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID)));
break;
}
case VIEW_TYPE_FUTURE_DAY: {
// Get weather icon
viewHolder.iconView.setImageResource(Utility.getIconResourceForWeatherCondition(
cursor.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID)));
break;
}
}
// Read date from cursor
long dateInMillis = cursor.getLong(ForecastFragment.COL_WEATHER_DATE);
// Find TextView and set formatted date on it
viewHolder.dateView.setText(Utility.getFriendlyDayString(context, dateInMillis));
// Read weather forecast from cursor
String description = cursor.getString(ForecastFragment.COL_WEATHER_DESC);
// Find TextView and set weather forecast on it
viewHolder.descriptionView.setText(description);
// For accessibility, add a content description to the icon field
viewHolder.iconView.setContentDescription(description);
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
double high = cursor.getDouble(ForecastFragment.COL_WEATHER_MAX_TEMP);
viewHolder.highTempView.setText(Utility.formatTemperature(context, high, isMetric));
// Read low temperature from cursor
double low = cursor.getDouble(ForecastFragment.COL_WEATHER_MIN_TEMP);
viewHolder.lowTempView.setText(Utility.formatTemperature(context, low, isMetric));
}
public void setUseTodayLayout(boolean useTodayLayout) {
mUseTodayLayout = useTodayLayout;
}
@Override
public int getItemViewType(int position) {
return (position == 0 && mUseTodayLayout) ? VIEW_TYPE_TODAY : VIEW_TYPE_FUTURE_DAY;
}
@Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
}
|
package com.wtwoo.autoresource;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
/*#######################################################
*
* Maintained by Gregor Santner, 2017-
* https://gsantner.net/
*
* License of this file: Apache 2.0 (Commercial upon request)
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.markor.ui.hleditor;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import net.gsantner.markor.activity.MainActivity;
import net.gsantner.markor.model.Document;
import net.gsantner.markor.util.AppSettings;
import net.gsantner.opoc.util.StringUtils;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings("UnusedReturnValue")
public class HighlightingEditor extends AppCompatEditText {
public boolean isCurrentLineEmpty() {
final int posOrig = getSelectionStart();
final int posLineBegin = moveCursorToBeginOfLine(0);
final int posEndBegin = moveCursorToEndOfLine(0);
setSelection(posOrig);
return posLineBegin == posEndBegin;
}
private boolean _modified = true;
private boolean _hlEnabled = false;
private boolean _accessibilityEnabled = true;
private final boolean _isSpellingRedUnderline;
private Highlighter _hl;
private final Set<TextWatcher> _appliedModifiers = new HashSet<>(); /* Tracks currently applied modifiers */
public final static String PLACE_CURSOR_HERE_TOKEN = "%%PLACE_CURSOR_HERE%%";
private final Handler _updateHandler = new Handler();
private final Runnable _updateRunnable;
public HighlightingEditor(Context context, AttributeSet attrs) {
super(context, attrs);
AppSettings as = new AppSettings(context);
if (as.isHighlightingEnabled()) {
setHighlighter(Highlighter.getDefaultHighlighter(this, new Document(new File("/tmp"))));
enableHighlighterAutoFormat();
setHighlightingEnabled(as.isHighlightingEnabled());
}
_isSpellingRedUnderline = !as.isDisableSpellingRedUnderline();
_updateRunnable = () -> {
highlightWithoutChange();
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
setFallbackLineSpacing(false);
}
addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
cancelUpdate();
if (!_modified) {
return;
}
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Changed text (afterTextChanged)");
}
if (_hl != null) {
int delay = (int) _hl.getHighlightingFactorBasedOnFilesize() * (_hl.isFirstHighlighting() ? 300 : _hl.getHighlightingDelay(getContext()));
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Highlighting run: delay " + delay + "ms, cfactor " + _hl.getHighlightingFactorBasedOnFilesize());
}
_updateHandler.postDelayed(_updateRunnable, delay);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Changed text (onTextChanged)");
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Changed text (beforeTextChanged)");
}
}
});
}
public void setHighlighter(Highlighter newHighlighter) {
disableHighlighterAutoFormat();
_hl = newHighlighter;
enableHighlighterAutoFormat();
highlightWithoutChange();
// Alpha in animation
setAlpha(0.3f);
animate().alpha(1.0f)
.setDuration(500)
.setListener(null);
}
public Highlighter getHighlighter() {
return _hl;
}
public void enableHighlighterAutoFormat() {
postDelayed(() -> {
setFilters(new InputFilter[]{_hl.getAutoFormatter()});
}, 10);
final TextWatcher modifier = (_hl != null) ? _hl.getTextModifier() : null;
if (modifier != null && !_appliedModifiers.contains(modifier)) {
addTextChangedListener(modifier);
_appliedModifiers.add(modifier);
}
}
public void disableHighlighterAutoFormat() {
setFilters(new InputFilter[]{});
final TextWatcher modifier = (_hl != null) ? _hl.getTextModifier() : null;
if (modifier != null) {
removeTextChangedListener(modifier);
_appliedModifiers.remove(modifier);
}
}
private void cancelUpdate() {
_updateHandler.removeCallbacks(_updateRunnable);
}
// Accessibility code is blocked during rapid update events
// such as highlighting and some actions.
// This prevents errors and potential crashes.
@Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
if (_accessibilityEnabled && length() < 10000) {
super.sendAccessibilityEventUnchecked(event);
}
}
// Hleditor will report that it is not autofillable under certain circumstances
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int getAutofillType() {
if (_accessibilityEnabled && length() < 10000) {
return super.getAutofillType();
} else {
return View.AUTOFILL_TYPE_NONE;
}
}
private void highlightWithoutChange() {
if (_hlEnabled) {
_modified = false;
try {
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Start highlighting");
}
setAccessibilityEnabled(false);
_hl.run(getText());
} catch (Exception e) {
// In no case ever let highlighting crash the editor
e.printStackTrace();
} catch (Error e) {
e.printStackTrace();
} finally {
setAccessibilityEnabled(true);
}
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog(_hl._profiler.resetDebugText());
AppSettings.appendDebugLog("Finished highlighting");
}
_modified = true;
}
}
public void simulateKeyPress(int keyEvent_KEYCODE_SOMETHING) {
dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, keyEvent_KEYCODE_SOMETHING, 0));
dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_UP, keyEvent_KEYCODE_SOMETHING, 0));
}
public void insertOrReplaceTextOnCursor(String newText) {
newText = (newText == null ? "" : newText);
int newCursorPos = newText.indexOf(PLACE_CURSOR_HERE_TOKEN);
newText = newText.replace(PLACE_CURSOR_HERE_TOKEN, "");
int start = Math.max(getSelectionStart(), 0);
int end = Math.max(getSelectionEnd(), 0);
getText().replace(Math.min(start, end), Math.max(start, end), newText, 0, newText.length());
if (newCursorPos >= 0) {
setSelection(start + newCursorPos);
}
}
public int getShiftWidth(String text) {
if (text.contains("sw=2") || text.contains("shiftwidth=2")) {
return 2;
} else if (text.contains("sw=8") || text.contains("shiftwidth=8")) {
return 8;
} else {
return 4;
}
}
public int moveCursorToEndOfLine(int offset) {
simulateKeyPress(KeyEvent.KEYCODE_MOVE_END);
setSelection(getSelectionStart() + offset);
return getSelectionStart();
}
public int moveCursorToBeginOfLine(int offset) {
simulateKeyPress(KeyEvent.KEYCODE_MOVE_HOME);
setSelection(getSelectionStart() + offset);
return getSelectionStart();
}
// Set selection to fill whole lines
// Returns original selectionStart
public int setSelectionExpandWholeLines() {
final int[] sel = StringUtils.getSelection(this);
final CharSequence text = getText();
setSelection(
StringUtils.getLineStart(text, sel[0]),
StringUtils.getLineEnd(text, sel[1])
);
return sel[0];
}
//
// Simple getter / setter
//
public void setHighlightingEnabled(final boolean enable) {
if (_hlEnabled && !enable) {
_hlEnabled = false;
Highlighter.clearSpans(getText());
} else if (!_hlEnabled && enable && _hl != null) {
_hlEnabled = true;
highlightWithoutChange();
}
}
public boolean indexesValid(int... indexes) {
int len = length();
for (int index : indexes) {
if (index < 0 || index > len) {
return false;
}
}
return true;
}
@Override
public boolean isSuggestionsEnabled() {
return _isSpellingRedUnderline && super.isSuggestionsEnabled();
}
@Override
public void setSelection(int index) {
if (indexesValid(index)) {
super.setSelection(index);
}
}
@Override
public void setSelection(int start, int stop) {
if (indexesValid(start, stop)) {
super.setSelection(start, stop);
} else if (indexesValid(start, stop - 1)) {
super.setSelection(start, stop - 1);
} else if (indexesValid(start + 1, stop)) {
super.setSelection(start + 1, stop);
}
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
if (MainActivity.IS_DEBUG_ENABLED) {
AppSettings.appendDebugLog("Selection changed: " + selStart + "->" + selEnd);
}
}
public void smoothMoveCursor(final int startIndex, final int endIndex, int... arg0Delay__arg1Duration) {
final int delay = Math.max(1, arg0Delay__arg1Duration != null && arg0Delay__arg1Duration.length > 0 ? arg0Delay__arg1Duration[0] : 500);
final int duration = Math.max(1, arg0Delay__arg1Duration != null && arg0Delay__arg1Duration.length > 1 ? arg0Delay__arg1Duration[1] : 400);
postDelayed(() -> {
if (!hasFocus()) {
requestFocus();
}
ObjectAnimator anim = ObjectAnimator.ofInt(this, "selection", startIndex, endIndex);
anim.setDuration(duration);
anim.start();
}, delay);
}
public void smoothMoveCursorToLine(final int lineNumber, int... arg0Delay__arg1Duration) {
final int delay = Math.max(1, arg0Delay__arg1Duration != null && arg0Delay__arg1Duration.length > 0 ? arg0Delay__arg1Duration[0] : 500);
final int duration = Math.max(1, arg0Delay__arg1Duration != null && arg0Delay__arg1Duration.length > 1 ? arg0Delay__arg1Duration[1] : 400);
this.postDelayed(() -> {
String text = getText().toString();
int index = StringUtils.getIndexFromLineOffset(text, lineNumber, 0);
if (index < 0) {
return;
}
smoothMoveCursor(0, index, 1, duration);
}, delay);
}
public void setAccessibilityEnabled(final boolean enabled) {
_accessibilityEnabled = enabled;
}
public boolean getAccessibilityEnabled() {
return _accessibilityEnabled;
}
}
|
/**
* Copyright 2006-2016 the original author or authors.
*
* 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 org.mybatis.generator.api;
import org.mybatis.generator.codegen.RootClassInfo;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.ShellException;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.mybatis.generator.internal.NullProgressCallback;
import org.mybatis.generator.internal.ObjectFactory;
import org.mybatis.generator.internal.XmlFileMergerJaxp;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.mybatis.generator.internal.util.ClassloaderUtility.getCustomClassloader;
import static org.mybatis.generator.internal.util.messages.Messages.getString;
/**
* This class is the main interface to MyBatis generator. A typical execution of the tool involves these steps:
*
* <ol>
* <li>Create a Configuration object. The Configuration can be the result of a parsing the XML configuration file, or it
* can be created solely in Java.</li>
* <li>Create a MyBatisGenerator object</li>
* <li>Call one of the generate() methods</li>
* </ol>
*
* @author Jeff Butler
* @see org.mybatis.generator.config.xml.ConfigurationParser
*/
public class MyBatisGenerator {
/** The configuration. */
private Configuration configuration;
/** The shell callback. */
private ShellCallback shellCallback;
/** The generated java files. */
private List<GeneratedJavaFile> generatedJavaFiles;
/** The generated xml files. */
private List<GeneratedXmlFile> generatedXmlFiles;
/** The warnings. */
private List<String> warnings;
/** The projects. */
private Set<String> projects;
/**
* Constructs a MyBatisGenerator object.
*
* @param configuration
* The configuration for this invocation
* @param shellCallback
* an instance of a ShellCallback interface. You may specify
* <code>null</code> in which case the DefaultShellCallback will
* be used.
* @param warnings
* Any warnings generated during execution will be added to this
* list. Warnings do not affect the running of the tool, but they
* may affect the results. A typical warning is an unsupported
* data type. In that case, the column will be ignored and
* generation will continue. You may specify <code>null</code> if
* you do not want warnings returned.
* @throws InvalidConfigurationException
* if the specified configuration is invalid
*/
public MyBatisGenerator(Configuration configuration, ShellCallback shellCallback,
List<String> warnings) throws InvalidConfigurationException {
super();
if (configuration == null) {
throw new IllegalArgumentException(getString("RuntimeError.2")); //$NON-NLS-1$
} else {
this.configuration = configuration;
}
if (shellCallback == null) {
this.shellCallback = new DefaultShellCallback(false);
} else {
this.shellCallback = shellCallback;
}
if (warnings == null) {
this.warnings = new ArrayList<String>();
} else {
this.warnings = warnings;
}
generatedJavaFiles = new ArrayList<GeneratedJavaFile>();
generatedXmlFiles = new ArrayList<GeneratedXmlFile>();
projects = new HashSet<String>();
this.configuration.validate();
}
/**
* This is the main method for generating code. This method is long running, but progress can be provided and the
* method can be canceled through the ProgressCallback interface. This version of the method runs all configured
* contexts.
*
* @param callback
* an instance of the ProgressCallback interface, or <code>null</code> if you do not require progress
* information
* @throws SQLException
* the SQL exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* if the method is canceled through the ProgressCallback
*/
public void generate(ProgressCallback callback) throws SQLException,
IOException, InterruptedException {
generate(callback, null, null, true);
}
/**
* This is the main method for generating code. This method is long running, but progress can be provided and the
* method can be canceled through the ProgressCallback interface.
*
* @param callback
* an instance of the ProgressCallback interface, or <code>null</code> if you do not require progress
* information
* @param contextIds
* a set of Strings containing context ids to run. Only the contexts with an id specified in this list
* will be run. If the list is null or empty, than all contexts are run.
* @throws SQLException
* the SQL exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* if the method is canceled through the ProgressCallback
*/
public void generate(ProgressCallback callback, Set<String> contextIds)
throws SQLException, IOException, InterruptedException {
generate(callback, contextIds, null, true);
}
/**
* This is the main method for generating code. This method is long running, but progress can be provided and the
* method can be cancelled through the ProgressCallback interface.
*
* @param callback
* an instance of the ProgressCallback interface, or <code>null</code> if you do not require progress
* information
* @param contextIds
* a set of Strings containing context ids to run. Only the contexts with an id specified in this list
* will be run. If the list is null or empty, than all contexts are run.
* @param fullyQualifiedTableNames
* a set of table names to generate. The elements of the set must be Strings that exactly match what's
* specified in the configuration. For example, if table name = "foo" and schema = "bar", then the fully
* qualified table name is "foo.bar". If the Set is null or empty, then all tables in the configuration
* will be used for code generation.
* @throws SQLException
* the SQL exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* if the method is canceled through the ProgressCallback
*/
public void generate(ProgressCallback callback, Set<String> contextIds,
Set<String> fullyQualifiedTableNames) throws SQLException,
IOException, InterruptedException {
generate(callback, contextIds, fullyQualifiedTableNames, true);
}
/**
* This is the main method for generating code. This method is long running, but progress can be provided and the
* method can be cancelled through the ProgressCallback interface.
*
* @param callback
* an instance of the ProgressCallback interface, or <code>null</code> if you do not require progress
* information
* @param contextIds
* a set of Strings containing context ids to run. Only the contexts with an id specified in this list
* will be run. If the list is null or empty, than all contexts are run.
* @param fullyQualifiedTableNames
* a set of table names to generate. The elements of the set must be Strings that exactly match what's
* specified in the configuration. For example, if table name = "foo" and schema = "bar", then the fully
* qualified table name is "foo.bar". If the Set is null or empty, then all tables in the configuration
* will be used for code generation.
* @param writeFiles
* if true, then the generated files will be written to disk. If false,
* then the generator runs but nothing is written
* @throws SQLException
* the SQL exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* if the method is canceled through the ProgressCallback
*/
public void generate(ProgressCallback callback, Set<String> contextIds,
Set<String> fullyQualifiedTableNames, boolean writeFiles) throws SQLException,
IOException, InterruptedException {
if (callback == null) {
callback = new NullProgressCallback();
}
generatedJavaFiles.clear();
generatedXmlFiles.clear();
ObjectFactory.reset();
RootClassInfo.reset();
// calculate the contexts to run
List<Context> contextsToRun;
if (contextIds == null || contextIds.size() == 0) {
contextsToRun = configuration.getContexts();
} else {
contextsToRun = new ArrayList<Context>();
for (Context context : configuration.getContexts()) {
if (contextIds.contains(context.getId())) {
contextsToRun.add(context);
}
}
}
// setup custom classloader if required
if (configuration.getClassPathEntries().size() > 0) {
ClassLoader classLoader = getCustomClassloader(configuration.getClassPathEntries());
ObjectFactory.addExternalClassLoader(classLoader);
}
// now run the introspections...
int totalSteps = 0;
for (Context context : contextsToRun) {
totalSteps += context.getIntrospectionSteps();
}
callback.introspectionStarted(totalSteps);
for (Context context : contextsToRun) {
context.introspectTables(callback, warnings,
fullyQualifiedTableNames);
}
// now run the generates
totalSteps = 0;
for (Context context : contextsToRun) {
totalSteps += context.getGenerationSteps();
}
callback.generationStarted(totalSteps);
for (Context context : contextsToRun) {
context.generateFiles(callback, generatedJavaFiles,
generatedXmlFiles, warnings);
}
// now save the files
if (writeFiles) {
callback.saveStarted(generatedXmlFiles.size()
+ generatedJavaFiles.size());
for (GeneratedXmlFile gxf : generatedXmlFiles) {
projects.add(gxf.getTargetProject());
writeGeneratedXmlFile(gxf, callback);
}
for (GeneratedJavaFile gjf : generatedJavaFiles) {
projects.add(gjf.getTargetProject());
writeGeneratedJavaFile(gjf, callback);
}
for (String project : projects) {
shellCallback.refreshProject(project);
}
}
callback.done();
}
private void writeGeneratedJavaFile(GeneratedJavaFile gjf, ProgressCallback callback)
throws InterruptedException, IOException {
File targetFile;
String source;
try {
File directory = shellCallback.getDirectory(gjf
.getTargetProject(), gjf.getTargetPackage());
// java 文件改mapper为dao,xml文件去掉mapper
targetFile = new File(directory, gjf.getFileName());
if (targetFile.exists()) {
if (shellCallback.isMergeSupported()) {
source = shellCallback.mergeJavaFile(gjf
.getFormattedContent(), targetFile
.getAbsolutePath(),
MergeConstants.OLD_ELEMENT_TAGS,
gjf.getFileEncoding());
} else if (shellCallback.isOverwriteEnabled()) {
source = gjf.getFormattedContent();
warnings.add(getString("Warning.11", //$NON-NLS-1$
targetFile.getAbsolutePath()));
} else {
source = gjf.getFormattedContent();
targetFile = getUniqueFileName(directory, gjf
.getFileName());
warnings.add(getString(
"Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$
}
} else {
source = gjf.getFormattedContent();
}
callback.checkCancel();
callback.startTask(getString(
"Progress.15", targetFile.getName())); //$NON-NLS-1$
writeFile(targetFile, source, gjf.getFileEncoding());
} catch (ShellException e) {
warnings.add(e.getMessage());
}
}
private void writeGeneratedXmlFile(GeneratedXmlFile gxf, ProgressCallback callback)
throws InterruptedException, IOException {
File targetFile;
String source;
try {
File directory = shellCallback.getDirectory(gxf
.getTargetProject(), gxf.getTargetPackage());
targetFile = new File(directory, gxf.getFileName());
if (targetFile.exists()) {
if (gxf.isMergeable()) {
source = XmlFileMergerJaxp.getMergedSource(gxf,
targetFile);
} else if (shellCallback.isOverwriteEnabled()) {
source = gxf.getFormattedContent();
warnings.add(getString("Warning.11", //$NON-NLS-1$
targetFile.getAbsolutePath()));
} else {
source = gxf.getFormattedContent();
targetFile = getUniqueFileName(directory, gxf
.getFileName());
warnings.add(getString(
"Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$
}
} else {
source = gxf.getFormattedContent();
}
callback.checkCancel();
callback.startTask(getString(
"Progress.15", targetFile.getName())); //$NON-NLS-1$
writeFile(targetFile, source, "UTF-8"); //$NON-NLS-1$
} catch (ShellException e) {
warnings.add(e.getMessage());
}
}
/**
* Writes, or overwrites, the contents of the specified file.
*
* @param file
* the file
* @param content
* the content
* @param fileEncoding
* the file encoding
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeFile(File file, String content, String fileEncoding) throws IOException {
FileOutputStream fos = new FileOutputStream(file, false);
OutputStreamWriter osw;
if (fileEncoding == null) {
osw = new OutputStreamWriter(fos);
} else {
osw = new OutputStreamWriter(fos, fileEncoding);
}
BufferedWriter bw = new BufferedWriter(osw);
bw.write(content);
bw.close();
}
/**
* Gets the unique file name.
*
* @param directory
* the directory
* @param fileName
* the file name
* @return the unique file name
*/
private File getUniqueFileName(File directory, String fileName) {
File answer = null;
// try up to 1000 times to generate a unique file name
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 1000; i++) {
sb.setLength(0);
sb.append(fileName);
sb.append('.');
sb.append(i);
File testFile = new File(directory, sb.toString());
if (!testFile.exists()) {
answer = testFile;
break;
}
}
if (answer == null) {
throw new RuntimeException(getString(
"RuntimeError.3", directory.getAbsolutePath())); //$NON-NLS-1$
}
return answer;
}
/**
* Returns the list of generated Java files after a call to one of the generate methods.
* This is useful if you prefer to process the generated files yourself and do not want
* the generator to write them to disk.
*
* @return the list of generated Java files
*/
public List<GeneratedJavaFile> getGeneratedJavaFiles() {
return generatedJavaFiles;
}
/**
* Returns the list of generated XML files after a call to one of the generate methods.
* This is useful if you prefer to process the generated files yourself and do not want
* the generator to write them to disk.
*
* @return the list of generated XML files
*/
public List<GeneratedXmlFile> getGeneratedXmlFiles() {
return generatedXmlFiles;
}
}
|
package com.jpuyo.android.recyclerviewplayground.ui.videolist.epoxy.view.main;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.airbnb.epoxy.EpoxyHolder;
import com.bumptech.glide.Glide;
import com.jpuyo.android.recyclerviewplayground.R;
import com.jpuyo.android.recyclerviewplayground.ui.videolist.epoxy.view.VideoModel;
public class MainVideoViewHolder extends EpoxyHolder {
private static final String TAG = "Epoxy";
private TextView tvTitle;
private ImageView ivThumbnail;
@Override
protected void bindView(View itemView) {
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
ivThumbnail = (ImageView) itemView.findViewById(R.id.ivThumbnail);
}
public void render(final VideoModel videoModel) {
tvTitle.setText(videoModel.getTitle());
Glide.with(ivThumbnail.getContext())
.load(videoModel.getThumbnail())
.placeholder(R.drawable.placeholder)
.into(ivThumbnail);
tvTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Clicked title: " + videoModel.getTitle());
}
});
ivThumbnail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Clicked thumbnail: " + videoModel.getThumbnail());
}
});
}
}
|
package com.zang.api.params;
import com.zang.api.domain.enums.HttpMethod;
/**
* Utility class for executing the Purchase Incoming Number request
* @see com.zang.api.connectors.IncomingPhoneNumbersConnector
* @see PurchaseIncomingNumberParams
*/
public class PurchaseIncomingNumberParamsBuilder {
private String accountSid;
private String friendlyName;
private String phoneNumber;
private String areaCode;
private Boolean voiceCallerIdLookup;
private String voiceApplicationSid;
private String smsApplicationSid;
private String voiceUrl;
private HttpMethod voiceMethod;
private String voiceFallbackUrl;
private HttpMethod voiceFallbackMethod;
private String smsUrl;
private HttpMethod smsMethod;
private String smsFallbackUrl;
private HttpMethod smsFallbackMethod;
private String heartbeatUrl;
private HttpMethod heartbeatMethod;
private String statusCallback;
private HttpMethod statusCallbackMethod;
private String hangupCallback;
private HttpMethod hangupCallbackMethod;
PurchaseIncomingNumberParamsBuilder() {
}
/**
* Sets accountSid. If left blank the one from the Connector configuration will be used.
* @param accountSid
* @return
*/
public PurchaseIncomingNumberParamsBuilder setAccountSid(String accountSid) {
this.accountSid = accountSid;
return this;
}
/**
* User generated name for the incoming number.
* @param friendlyName
* @return
*/
public PurchaseIncomingNumberParamsBuilder setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
return this;
}
/**
* A specific available phone number you wish to add.
* @param phoneNumber
* @return
*/
public PurchaseIncomingNumberParamsBuilder setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
/**
* The area code from which a random available number will be added.
* @param areaCode
* @return
*/
public PurchaseIncomingNumberParamsBuilder setAreaCode(String areaCode) {
this.areaCode = areaCode;
return this;
}
/**
* Look up the caller’s caller-ID name from the CNAM database (additional charges apply).
* @param voiceCallerIdLookup
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceCallerIdLookup(Boolean voiceCallerIdLookup) {
this.voiceCallerIdLookup = voiceCallerIdLookup;
return this;
}
/**
* The SID of the Voice Application you wish to associate with this incoming number.
* @param voiceApplicationSid
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceApplicationSid(String voiceApplicationSid) {
this.voiceApplicationSid = voiceApplicationSid;
return this;
}
/**
* The SID of the SMS Application you wish to associate with this incoming number.
* @param smsApplicationSid
* @return
*/
public PurchaseIncomingNumberParamsBuilder setSmsApplicationSid(String smsApplicationSid) {
this.smsApplicationSid = smsApplicationSid;
return this;
}
/**
* The URL requested once the call connects. This URL must be valid and should return InboundXML
* containing instructions on how to process your call. A badly formatted Url will NOT fallback to
* the FallbackUrl but return an error without placing the call. Url length is limited
* to 200 characters.
* @param voiceUrl
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceUrl(String voiceUrl) {
this.voiceUrl = voiceUrl;
return this;
}
/**
* The HTTP method used to request the URL once the call connects.
* @param voiceMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceMethod(HttpMethod voiceMethod) {
this.voiceMethod = voiceMethod;
return this;
}
/**
* URL used if the required URL is unavailable or if any errors occur during execution of
* the InboundXML returned by the required URL. Url length is limited to 200 characters.
* @param voiceFallbackUrl
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceFallbackUrl(String voiceFallbackUrl) {
this.voiceFallbackUrl = voiceFallbackUrl;
return this;
}
/**
* The HTTP method used to request the FallbackUrl once the call connects.
* @param voiceFallbackMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setVoiceFallbackMethod(HttpMethod voiceFallbackMethod) {
this.voiceFallbackMethod = voiceFallbackMethod;
return this;
}
/**
* The URL requested when an SMS is received. This URL must be valid and should return InboundXML
* containing instructions on how to process the SMS. A badly formatted URL will NOT fallback to the
* FallbackUrl but return an error without placing the call. URL length is limited to 200 characters.
* @param smsUrl
* @return
*/
public PurchaseIncomingNumberParamsBuilder setSmsUrl(String smsUrl) {
this.smsUrl = smsUrl;
return this;
}
/**
* The HTTP method used to request the URL when an SMS is received.
* @param smsMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setSmsMethod(HttpMethod smsMethod) {
this.smsMethod = smsMethod;
return this;
}
/**
* URL used if the required URL is unavailable or if any errors occur during execution of
* the InboundXML returned by the required URL. Url length is limited to 200 characters.
* @param smsFallbackUrl
* @return
*/
public PurchaseIncomingNumberParamsBuilder setSmsFallbackUrl(String smsFallbackUrl) {
this.smsFallbackUrl = smsFallbackUrl;
return this;
}
/**
* The HTTP method used to request the smsFallbackUrl when an SMS is received.
* @param smsFallbackMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setSmsFallbackMethod(HttpMethod smsFallbackMethod) {
this.smsFallbackMethod = smsFallbackMethod;
return this;
}
/**
* A URL that will be requested every 60 seconds during the call, sending information about
* the call. The HeartbeatUrl will NOT be requested unless at least 60 seconds of call time
* have elapsed. URL length is limited to 200 characters.
* @param heartbeatUrl
* @return
*/
public PurchaseIncomingNumberParamsBuilder setHeartbeatUrl(String heartbeatUrl) {
this.heartbeatUrl = heartbeatUrl;
return this;
}
/**
* The HTTP method used to request the HeartbeatUrl.
* @param heartbeatMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setHeartbeatMethod(HttpMethod heartbeatMethod) {
this.heartbeatMethod = heartbeatMethod;
return this;
}
/**
* A URL that will be requested when the call connects and ends, sending information about
* the call. URL length is limited to 200 characters.
* @param statusCallback
* @return
*/
public PurchaseIncomingNumberParamsBuilder setStatusCallback(String statusCallback) {
this.statusCallback = statusCallback;
return this;
}
/**
* The HTTP method used to request the StatusCallback URL.
* @param statusCallbackMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setStatusCallbackMethod(HttpMethod statusCallbackMethod) {
this.statusCallbackMethod = statusCallbackMethod;
return this;
}
/**
* This is a StatusCallback clone that will be phased out in future versions.
* @param hangupCallback
* @return
*/
public PurchaseIncomingNumberParamsBuilder setHangupCallback(String hangupCallback) {
this.hangupCallback = hangupCallback;
return this;
}
/**
* This is a StatusCallbackMethod clone that will be phased out in future versions.
* @param hangupCallbackMethod
* @return
*/
public PurchaseIncomingNumberParamsBuilder setHangupCallbackMethod(HttpMethod hangupCallbackMethod) {
this.hangupCallbackMethod = hangupCallbackMethod;
return this;
}
public PurchaseIncomingNumberParams build() {
return new PurchaseIncomingNumberParams(accountSid, friendlyName, phoneNumber, areaCode, voiceCallerIdLookup, voiceApplicationSid, smsApplicationSid, voiceUrl, voiceMethod, voiceFallbackUrl, voiceFallbackMethod, smsUrl, smsMethod, smsFallbackUrl, smsFallbackMethod, heartbeatUrl, heartbeatMethod, statusCallback, statusCallbackMethod, hangupCallback, hangupCallbackMethod);
}
}
|
package me.chanjar.weixin.mp.bean.template;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 参考 http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN 发送模板消息接口部分
*/
public class WxMpTemplateMessage implements Serializable {
private static final long serialVersionUID = 5063374783759519418L;
/**
* 接收者openid
*/
private String toUser;
/**
* 模板ID
*/
private String templateId;
/**
* <pre>
* 跳小程序所需数据,不需跳小程序可不用传该数据
* url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。
* 开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。
* </pre>
*/
private String url;
/**
* 模板跳转链接
* @see #url
*/
private MiniProgram miniProgram;
/**
* 模板数据
*/
private List<WxMpTemplateData> data = new ArrayList<>();
public WxMpTemplateMessage() {
}
public String getToUser() {
return this.toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getTemplateId() {
return this.templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public List<WxMpTemplateData> getData() {
return this.data;
}
public void setData(List<WxMpTemplateData> data) {
this.data = data;
}
public void addWxMpTemplateData(WxMpTemplateData datum) {
this.data.add(datum);
}
public MiniProgram getMiniProgram() {
return this.miniProgram;
}
public void setMiniProgram(MiniProgram miniProgram) {
this.miniProgram = miniProgram;
}
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}
public static WxMpTemplateMessageBuilder builder() {
return new WxMpTemplateMessageBuilder();
}
public static class MiniProgram {
private String appid;
private String pagePath;
public MiniProgram() {
}
public MiniProgram(String appid, String pagePath) {
this.appid = appid;
this.pagePath = pagePath;
}
public String getAppid() {
return this.appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getPagePath() {
return this.pagePath;
}
public void setPagePath(String pagePath) {
this.pagePath = pagePath;
}
}
public static class WxMpTemplateMessageBuilder {
private String toUser;
private String templateId;
private String url;
private List<WxMpTemplateData> data = new ArrayList<>();
private MiniProgram miniProgram;
public WxMpTemplateMessageBuilder toUser(String toUser) {
this.toUser = toUser;
return this;
}
public WxMpTemplateMessageBuilder templateId(String templateId) {
this.templateId = templateId;
return this;
}
public WxMpTemplateMessageBuilder url(String url) {
this.url = url;
return this;
}
public WxMpTemplateMessageBuilder data(List<WxMpTemplateData> data) {
this.data = data;
return this;
}
public WxMpTemplateMessageBuilder from(WxMpTemplateMessage origin) {
this.toUser(origin.toUser);
this.templateId(origin.templateId);
this.url(origin.url);
this.data(origin.data);
return this;
}
public WxMpTemplateMessageBuilder miniProgram(MiniProgram miniProgram) {
this.miniProgram = miniProgram;
return this;
}
public WxMpTemplateMessage build() {
WxMpTemplateMessage m = new WxMpTemplateMessage();
m.toUser = this.toUser;
m.templateId = this.templateId;
m.url = this.url;
m.data = this.data;
m.miniProgram = this.miniProgram;
return m;
}
}
}
|
package com.artemis.parallel_world.block.sapling;
import com.artemis.parallel_world.world.gen.feature.TethysConfiguredFeatures;
import net.minecraft.block.sapling.SaplingGenerator;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.TreeFeatureConfig;
import org.jetbrains.annotations.Nullable;
import java.util.Random;
public class ElderberrySaplingGenerator extends SaplingGenerator {
public ElderberrySaplingGenerator() {
}
@Nullable
protected ConfiguredFeature<TreeFeatureConfig, ?> createTreeFeature(Random random, boolean bees) {
return bees ? (ConfiguredFeature<TreeFeatureConfig, ?>) TethysConfiguredFeatures.ELDERBERRY_TREE_BEES : (ConfiguredFeature<TreeFeatureConfig, ?>) TethysConfiguredFeatures.ELDERBERRY_TREE;
}
}
|
package ossrs.net.srssip.controller;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* @ Description ossrs.net.srssip.controller
* @ Author StormBirds
* @ Email xbaojun@gmail.com
* @ Date 20/2/2022 下午10:26
*/
@Slf4j
@RestController()
@RequestMapping("/api/v1/user/")
public class UserController {
@GetMapping("login")
public String doLogin(@RequestParam String username,@RequestParam String password) {
if("admin".equals(username) && "admin".equals(password)) {
StpUtil.login(1);
log.info("user token:{}",StpUtil.getTokenValue());
return "登录成功";
}
return "登录失败";
}
@RequestMapping("isLogin")
public String isLogin() {
return "是否登录:" + StpUtil.isLogin();
}
@RequestMapping("logout")
public String logout() {
StpUtil.logout();
return "ok";
}
}
|
package com.xeiam.xchange.coinfloor.streaming;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.ExchangeException;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.coinfloor.dto.streaming.CoinfloorExchangeEvent;
import com.xeiam.xchange.coinfloor.dto.streaming.CoinfloorStreamingConfiguration;
import com.xeiam.xchange.coinfloor.streaming.RequestFactory.CoinfloorRequest;
import com.xeiam.xchange.dto.Order;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.dto.trade.MarketOrder;
import com.xeiam.xchange.service.streaming.BaseWebSocketExchangeService;
import com.xeiam.xchange.service.streaming.ExchangeEvent;
import com.xeiam.xchange.service.streaming.ExchangeEventType;
import com.xeiam.xchange.service.streaming.StreamingExchangeService;
/**
* @author obsessiveOrange
*/
public class CoinfloorStreamingExchangeService extends BaseWebSocketExchangeService implements StreamingExchangeService {
private final Logger logger = LoggerFactory.getLogger(CoinfloorStreamingExchangeService.class);
private final CoinfloorStreamingConfiguration configuration;
private final CoinfloorEventListener exchangeEventListener;
private final BlockingQueue<ExchangeEvent> systemEventQueue = new LinkedBlockingQueue<ExchangeEvent>();
private final BlockingQueue<CoinfloorExchangeEvent> updateEventQueue = new LinkedBlockingQueue<CoinfloorExchangeEvent>();
ObjectMapper jsonObjectMapper;
/**
* @param exchangeSpecification
* @param exchangeStreamingConfiguration
*/
public CoinfloorStreamingExchangeService(ExchangeSpecification exchangeSpecification, CoinfloorStreamingConfiguration exchangeStreamingConfiguration) {
super(exchangeSpecification, exchangeStreamingConfiguration);
this.configuration = exchangeStreamingConfiguration;
this.exchangeEventListener = new CoinfloorEventListener(consumerEventQueue, systemEventQueue);
this.jsonObjectMapper = new ObjectMapper();
}
@Override
public void connect() {
String apiBase;
if (configuration.isEncryptedChannel()) {
apiBase = String.format("%s:%s", exchangeSpecification.getSslUriStreaming(), exchangeSpecification.getPort());
}
else {
apiBase = String.format("%s:%s", exchangeSpecification.getPlainTextUriStreaming(), exchangeSpecification.getPort());
}
URI uri = URI.create(apiBase);
Map<String, String> headers = new HashMap<String, String>(1);
headers.put("Origin", String.format("%s:%s", exchangeSpecification.getHost(), exchangeSpecification.getPort()));
logger.debug("Streaming URI='{}'", uri);
// Use the default internal connect
internalConnect(uri, exchangeEventListener, headers);
try {
if (getNextSystemEvent().getEventType() != ExchangeEventType.WELCOME) {
throw new ExchangeException("Could not connect.");
}
} catch (InterruptedException e) {
throw new ExchangeException("Could not connect.");
}
if (configuration.getauthenticateOnConnect()) {
authenticate();
}
}
public void authenticate() {
if (exchangeSpecification.getUserName() == null || exchangeSpecification.getUserName() == null || exchangeSpecification.getUserName() == null) {
throw new ExchangeException("Username (UserID), Cookie, and Password cannot be null");
}
try {
Long.valueOf(exchangeSpecification.getUserName());
} catch (NumberFormatException e) {
throw new ExchangeException("Username (UserID) must be the string representation of a integer or long value.");
}
RequestFactory.CoinfloorAuthenticationRequest authVars =
new RequestFactory.CoinfloorAuthenticationRequest(Long.valueOf(exchangeSpecification.getUserName()), (String) exchangeSpecification.getExchangeSpecificParametersItem("cookie"),
exchangeSpecification.getPassword(), exchangeEventListener.getServerNonce());
doNewRequest(authVars, ExchangeEventType.AUTHENTICATION);
}
@SuppressWarnings("incomplete-switch")
private CoinfloorExchangeEvent doNewRequest(final CoinfloorRequest requestObject, ExchangeEventType expectedEventType) {
try {
try {
logger.trace("Sent message: " + jsonObjectMapper.writeValueAsString(requestObject));
send(jsonObjectMapper.writeValueAsString(requestObject));
} catch (JsonProcessingException e) {
throw new ExchangeException("Cannot convert Object to String", e);
}
CoinfloorExchangeEvent nextEvent = checkNextSystemEvent();
while (!nextEvent.getEventType().equals(expectedEventType) || nextEvent.getTag() != requestObject.getTag()) {
switch (nextEvent.getEventType()) {
case USER_WALLET_UPDATE:
case ORDER_ADDED:
case TRADE:
case ORDER_CANCELED:
case TICKER:
case AUTHENTICATION:
case WELCOME:
updateEventQueue.put(getNextSystemEvent());
break;
}
synchronized (this) {
nextEvent = checkNextSystemEvent();
}
}
return getNextSystemEvent();
} catch (Exception e) {
throw new ExchangeException("Error processing request", e);
}
}
/**
* Get user's balances
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorBalances (key "raw")
* > A generic object of type AccountInfo (key "generic")
*/
public CoinfloorExchangeEvent getBalances() {
return doNewRequest(new RequestFactory.GetBalancesRequest(), ExchangeEventType.USER_WALLET);
}
/**
* Get user's open orders
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorOpenOrders (key "raw")
* > A generic object of type OpenOrders (key "generic")
*/
public CoinfloorExchangeEvent getOrders() {
return doNewRequest(new RequestFactory.GetOrdersRequest(), ExchangeEventType.USER_ORDERS_LIST);
}
/**
* Place an order
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorPlaceOrder (key "raw")
* > A generic object of type String, representing the orderID (key "generic")
*/
public CoinfloorExchangeEvent placeOrder(Order order) {
return doNewRequest(new RequestFactory.PlaceOrderRequest(order), ExchangeEventType.USER_ORDER);
}
/**
* Cancel an order
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorCancelOrder (key "raw")
* > A generic object of type LimitOrder, representing the cancelled order (key "generic")
*/
public CoinfloorExchangeEvent cancelOrder(int orderID) {
return doNewRequest(new RequestFactory.CancelOrderRequest(orderID), ExchangeEventType.USER_ORDER_CANCELED);
}
/**
* Get past 30-day trade volume
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorTradeVolume (key "raw")
* > A generic object of type BigDecimal, representing the past-30 day volume (key "generic")
*/
public CoinfloorExchangeEvent getTradeVolume(String currency) {
return doNewRequest(new RequestFactory.GetTradeVolumeRequest(currency), ExchangeEventType.USER_TRADE_VOLUME);
}
/**
* Estimate the results of a market order
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorEstimateMarketOrder (key "raw")
* Note that this method has no (useful) generic return. The "generic" key corresponds to the same item as the "raw" key
*/
public CoinfloorExchangeEvent estimateMarketOrder(MarketOrder order) {
return doNewRequest(new RequestFactory.EstimateMarketOrderRequest(order), ExchangeEventType.USER_MARKET_ORDER_EST);
}
/**
* Watch the orderbook
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorOrderbookReturn (key "raw")
* > A generic object of type Depth (key "generic")
*/
public CoinfloorExchangeEvent watchOrders(String tradableIdentifier, String tradingCurrency) {
return doNewRequest(new RequestFactory.WatchOrdersRequest(tradableIdentifier, tradingCurrency), ExchangeEventType.SUBSCRIBE_ORDERS);
}
/**
* Stop watching the orderbook
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorOrderbookReturn (key "raw")
* > A generic object of type Depth (key "generic")
*/
public CoinfloorExchangeEvent unwatchOrders(String tradableIdentifier, String tradingCurrency) {
return doNewRequest(new RequestFactory.UnwatchOrdersRequest(tradableIdentifier, tradingCurrency), ExchangeEventType.SUBSCRIBE_ORDERS);
}
/**
* Watch the ticker feed
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorTicker (key "raw")
* > A generic object of type Ticker (key "generic")
*/
public CoinfloorExchangeEvent watchTicker(String tradableIdentifier, String tradingCurrency) {
return doNewRequest(new RequestFactory.WatchTickerRequest(tradableIdentifier, tradingCurrency), ExchangeEventType.SUBSCRIBE_TICKER);
}
/**
* Stop watching the ticker feed
* Upon receipt of response, a CoinfloorExchangeEvent with payload Map<String, Object>, consisting of:
* > A raw object of type CoinfloorTicker (key "raw")
* > A generic object of type Ticker (key "generic")
*/
public CoinfloorExchangeEvent unwatchTicker(String tradableIdentifier, String tradingCurrency) {
return doNewRequest(new RequestFactory.UnwatchTickerRequest(tradableIdentifier, tradingCurrency), ExchangeEventType.SUBSCRIBE_TICKER);
}
/**
* Retrieves cached AccountInfo.
* WARNING: EXPERIMENTAL METHOD
*
* @return the AccountInfo, as updated by last BalancesChanged event
* @throws ExchangeException if getBalances() method has not been called, or data not recieved yet.
*/
public AccountInfo getCachedAccountInfo() {
return exchangeEventListener.getAdapterInstance().getCachedAccountInfo();
}
/**
* Retrieves cached OrderBook.
* WARNING: EXPERIMENTAL METHOD
*
* @return the OrderBook, as updated by last OrderOpened, OrdersMatched or OrderClosed event
* @throws ExchangeException if watchOrders() method has not been called, or data not recieved yet.
*/
public OrderBook getCachedOrderBook() {
return exchangeEventListener.getAdapterInstance().getCachedOrderBook();
}
/**
* Retrieves cached Trades.
* WARNING: EXPERIMENTAL METHOD
*
* @return the Trades, as updated by last OrdersMatched event
* @throws ExchangeException if watchOrders() method has not been called, or no trades have occurred yet.
*/
public Trades getCachedTrades() {
return exchangeEventListener.getAdapterInstance().getCachedTrades();
}
/**
* Retrieves cached Ticker.
* WARNING: EXPERIMENTAL METHOD
*
* @return the Ticker, as updated by last TickerChanged event
* @throws ExchangeException if watchTicker() method has not been called, or no ticker data has been recieved.
*/
public Ticker getCachedTicker() {
return exchangeEventListener.getAdapterInstance().getCachedTicker();
}
@Override
public CoinfloorExchangeEvent getNextEvent() throws InterruptedException {
return (CoinfloorExchangeEvent) super.getNextEvent();
}
public CoinfloorExchangeEvent getNextSystemEvent() throws InterruptedException {
CoinfloorExchangeEvent event = (CoinfloorExchangeEvent) systemEventQueue.take();
return event;
}
public CoinfloorExchangeEvent checkNextSystemEvent() throws InterruptedException {
while (true) {
synchronized (systemEventQueue) {
if (systemEventQueue.isEmpty()) {
systemEventQueue.wait();
}
}
CoinfloorExchangeEvent event = (CoinfloorExchangeEvent) systemEventQueue.peek();
if (event == null) {
continue;
}
return event;
}
}
}
|
package com.fanjiao.common.core.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
/**
* 错误信息处理类。
*
* @author bubble
*/
public class ExceptionUtil
{
/**
* 获取exception的详细错误信息。
*/
public static String getExceptionMessage(Throwable e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
return str;
}
public static String getRootErrorMseeage(Exception e)
{
Throwable root = ExceptionUtils.getRootCause(e);
root = (root == null ? e : root);
if (root == null)
{
return "";
}
String msg = root.getMessage();
if (msg == null)
{
return "null";
}
return StringUtils.defaultString(msg);
}
}
|
// Targeted by JavaCPP version 1.5.1: DO NOT EDIT THIS FILE
package org.bytedeco.gsl;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.gsl.global.gsl.*;
@Properties(inherit = org.bytedeco.gsl.presets.gsl.class)
public class _gsl_vector_complex_const_view extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public _gsl_vector_complex_const_view() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public _gsl_vector_complex_const_view(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public _gsl_vector_complex_const_view(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public _gsl_vector_complex_const_view position(long position) {
return (_gsl_vector_complex_const_view)super.position(position);
}
public native @ByRef gsl_vector_complex vector(); public native _gsl_vector_complex_const_view vector(gsl_vector_complex setter);
}
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------
* Effect3D.java
* -------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 14-Nov-2002 : Modified to have independent x and y offsets (DG);
*
*/
package org.jfree.chart;
/**
* An interface that should be implemented by renderers that use a 3D effect.
* This allows the axes to mirror the same effect by querying the renderer.
*/
public interface Effect3D {
/**
* Returns the x-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getXOffset();
/**
* Returns the y-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getYOffset();
}
|
/*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: trust@f4-i.fh-hannover.de
* Website: http://trust.f4.hs-hannover.de/
*
* This file is part of visitmeta-visualization, version 0.5.0,
* implemented by the Trust@HsH research group at the Hochschule Hannover.
* %%
* Copyright (C) 2012 - 2015 Trust@HsH
* %%
* 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.
* #L%
*/
package de.hshannover.f4.trust.visitmeta.gui.util;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import de.hshannover.f4.trust.visitmeta.data.DataserviceDataImpl;
import de.hshannover.f4.trust.visitmeta.exceptions.JSONHandlerException;
import de.hshannover.f4.trust.visitmeta.exceptions.ifmap.ConnectionException;
import de.hshannover.f4.trust.visitmeta.interfaces.connections.DataserviceConnection;
import de.hshannover.f4.trust.visitmeta.interfaces.connections.MapServerConnection;
import de.hshannover.f4.trust.visitmeta.interfaces.data.Data;
import de.hshannover.f4.trust.visitmeta.interfaces.data.DataserviceData;
import de.hshannover.f4.trust.visitmeta.interfaces.data.MapServerData;
import de.hshannover.f4.trust.visitmeta.util.StringHelper;
public class DataserviceRestConnectionImpl extends DataserviceDataImpl implements DataserviceConnection {
private static final Logger LOGGER = Logger.getLogger(DataserviceRestConnectionImpl.class);
private boolean mNotPersised;
private boolean mConnected;
private DataserviceData mOldData;
public DataserviceRestConnectionImpl(String name, String url, boolean rawXml) {
super(name, url, rawXml);
}
public DataserviceRestConnectionImpl(DataserviceData connectionData) {
super(connectionData.getName(), connectionData.getUrl(), connectionData.isRawXml());
}
@Override
public DataserviceRestConnectionImpl copy() {
DataserviceData dataCopy = super.copy();
DataserviceRestConnectionImpl tmpCopy = new DataserviceRestConnectionImpl(dataCopy);
tmpCopy.setNotPersised(true);
return tmpCopy;
}
@Override
public DataserviceRestConnectionImpl clone() {
return (DataserviceRestConnectionImpl) super.clone();
}
@Override
public void connect() throws ConnectionException {
setConnected(true);
}
@Override
public void disconnect() throws ConnectionException {
setConnected(false);
}
@Override
public String getConnectionName() {
return super.getName();
}
public void resetData() {
if (mOldData != null) {
super.changeData(mOldData);
mOldData = null;
}
}
public List<MapServerConnection> loadMapServerConnections() throws ClassNotFoundException, InstantiationException,
IllegalAccessException, JSONHandlerException, JSONException, ConnectionException {
return RestHelper.loadMapServerConnections(this);
}
public void connectMapServer(String mapServerConnectionName) throws ConnectionException {
for (Data d : super.getMapServerData()) {
MapServerConnection connection = (MapServerConnection) d;
if (connection.getConnectionName().equals(mapServerConnectionName)) {
connection.connect();
break;
}
}
}
public void disconnectMapServer(String mapServerConnectionName) throws ConnectionException {
for (Data d : super.getMapServerData()) {
MapServerConnection connection = (MapServerConnection) d;
if (connection.getConnectionName().equals(mapServerConnectionName)) {
connection.disconnect();
break;
}
}
}
@SuppressWarnings("unchecked")
public void update() throws ConnectionException {
List<MapServerData> updateList = null;
try {
updateList = (List<MapServerData>) (List<?>) loadMapServerConnections();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | JSONHandlerException
| JSONException e) {
LOGGER.error(e.toString());
JOptionPane.showMessageDialog(null, StringHelper.breakLongString(e.toString(), 80), e.getClass()
.getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
super.setMapServerData(updateList);
}
@Override
public void setConnected(boolean connected) {
mConnected = connected;
}
@Override
public boolean isConnected() {
return mConnected;
}
public boolean isNotPersised() {
return mNotPersised;
}
public void setNotPersised(boolean b) {
mNotPersised = b;
}
public void setOldData(DataserviceData oldData) {
mOldData = oldData;
}
public DataserviceData getOldData() {
return mOldData;
}
}
|
package com.miniorange.oauth.bamboo.dto;
import com.miniorange.oauth.bamboo.action.MoOAuthAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class TokenResponse {
private String response;
private ProtocolType type;
private static Log LOGGER = LogFactory.getLog(MoOAuthAction.class);
public TokenResponse(String response, ProtocolType type) {
this.response = response;
this.type = type;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public ProtocolType getType() {
return type;
}
public void setType(ProtocolType type) {
this.type = type;
}
@Override
public String toString() {
//LOGGER.debug("INSIDE TOKEN Response");
return "TokenResponse{" +
"response='" + response + '\'' +
", type='" + type + '\'' +
'}';
}
}
|
/*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.authentication;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* Tests for {@link BindAuthenticator}.
*
* @author Luke Taylor
*/
public class BindAuthenticatorTests extends AbstractLdapIntegrationTests {
// ~ Instance fields
// ================================================================================================
private BindAuthenticator authenticator;
private Authentication bob;
// ~ Methods
// ========================================================================================================
@Before
public void setUp() {
this.authenticator = new BindAuthenticator(getContextSource());
this.authenticator.setMessageSource(new SpringSecurityMessageSource());
this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword");
}
@Test(expected = BadCredentialsException.class)
public void emptyPasswordIsRejected() {
this.authenticator
.authenticate(new UsernamePasswordAuthenticationToken("jen", ""));
}
@Test
public void testAuthenticationWithCorrectPasswordSucceeds() {
this.authenticator.setUserDnPatterns(
new String[] { "uid={0},ou=people", "cn={0},ou=people" });
DirContextOperations user = this.authenticator.authenticate(this.bob);
assertThat(user.getStringAttribute("uid")).isEqualTo("bob");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"mouse, jerry", "jerryspassword"));
}
@Test
public void testAuthenticationWithInvalidUserNameFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"nonexistentsuser", "password"));
fail("Shouldn't be able to bind with invalid username");
}
catch (BadCredentialsException expected) {
}
}
@Test
public void testAuthenticationWithUserSearch() throws Exception {
// DirContextAdapter ctx = new DirContextAdapter(new
// DistinguishedName("uid=bob,ou=people"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people",
"(uid={0})", getContextSource()));
this.authenticator.afterPropertiesSet();
DirContextOperations result = this.authenticator.authenticate(this.bob);
//ensure we are getting the same attributes back
assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton");
// SEC-1444
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people",
"(cn={0})", getContextSource()));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"mouse, jerry", "jerryspassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"slash/guy", "slashguyspassword"));
// SEC-1661
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch(
"ou=\\\"quoted people\\\"", "(cn={0})", getContextSource()));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"quote\"guy", "quoteguyspassword"));
this.authenticator.setUserSearch(
new FilterBasedLdapUserSearch("", "(cn={0})", getContextSource()));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"quote\"guy", "quoteguyspassword"));
}
/*
* @Test public void messingWithEscapedChars() throws Exception {
* Hashtable<String,String> env = new Hashtable<>();
* env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
* env.put(Context.PROVIDER_URL, "ldap://127.0.0.1:22389/dc=springsource,dc=com");
* env.put(Context.SECURITY_AUTHENTICATION, "simple");
* env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=springsource,dc=com");
* env.put(Context.SECURITY_CREDENTIALS, "password");
*
* InitialDirContext idc = new InitialDirContext(env); SearchControls searchControls =
* new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
* DistinguishedName baseDn = new DistinguishedName("ou=\\\"quoted people\\\"");
* NamingEnumeration<SearchResult> matches = idc.search(baseDn, "(cn=*)", new Object[]
* {"quoteguy"}, searchControls);
*
* while(matches.hasMore()) { SearchResult match = matches.next(); DistinguishedName
* dn = new DistinguishedName(match.getName()); System.out.println("**** Match: " +
* match.getName() + " ***** " + dn);
*
* } }
*/
@Test
public void testAuthenticationWithWrongPasswordFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(
new UsernamePasswordAuthenticationToken("bob", "wrongpassword"));
fail("Shouldn't be able to bind with wrong password");
}
catch (BadCredentialsException expected) {
}
}
@Test
public void testUserDnPatternReturnsCorrectDn() {
this.authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
assertThat(this.authenticator.getUserDns("Joe").get(0))
.isEqualTo("cn=Joe,ou=people");
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jpa.hibernate.beans;
public class SinglePrototypeInSpringContextTestBean extends TestBean {
}
|
package com.alibaba.otter.canal.adapter.launcher.loader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.otter.canal.adapter.launcher.common.SyncSwitch;
import com.alibaba.otter.canal.adapter.launcher.config.SpringContext;
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
import com.alibaba.otter.canal.client.adapter.support.CanalClientConfig;
import com.alibaba.otter.canal.client.adapter.support.Dml;
import com.alibaba.otter.canal.client.adapter.support.MessageUtil;
import com.alibaba.otter.canal.client.adapter.support.Util;
import com.alibaba.otter.canal.connector.core.config.CanalConstants;
import com.alibaba.otter.canal.connector.core.consumer.CommonMessage;
import com.alibaba.otter.canal.connector.core.spi.CanalMsgConsumer;
import com.alibaba.otter.canal.connector.core.spi.ExtensionLoader;
/**
* 适配处理器
*
* @author rewerma 2020-02-01
* @version 1.0.0
*/
public class AdapterProcessor {
private static final Logger logger = LoggerFactory.getLogger(AdapterProcessor.class);
private static final String CONNECTOR_SPI_DIR = "/plugin";
private static final String CONNECTOR_STANDBY_SPI_DIR = "/canal-adapter/plugin";
private CanalMsgConsumer canalMsgConsumer;
private String canalDestination; // canal实例
private String groupId = null; // groupId
private List<List<OuterAdapter>> canalOuterAdapters; // 外部适配器
private CanalClientConfig canalClientConfig; // 配置
private ExecutorService groupInnerExecutorService; // 组内工作线程池
private volatile boolean running = false; // 是否运行中
private Thread thread = null;
private Thread.UncaughtExceptionHandler handler = (t, e) -> logger
.error("parse events has an error", e);
private SyncSwitch syncSwitch;
public AdapterProcessor(CanalClientConfig canalClientConfig, String destination, String groupId,
List<List<OuterAdapter>> canalOuterAdapters){
this.canalClientConfig = canalClientConfig;
this.canalDestination = destination;
this.groupId = groupId;
this.canalOuterAdapters = canalOuterAdapters;
this.groupInnerExecutorService = Util.newFixedThreadPool(canalOuterAdapters.size(), 5000L);
syncSwitch = (SyncSwitch) SpringContext.getBean(SyncSwitch.class);
// load connector consumer
ExtensionLoader<CanalMsgConsumer> loader = new ExtensionLoader<>(CanalMsgConsumer.class);
canalMsgConsumer = loader
.getExtension(canalClientConfig.getMode().toLowerCase(),destination ,CONNECTOR_SPI_DIR, CONNECTOR_STANDBY_SPI_DIR);
Properties properties = canalClientConfig.getConsumerProperties();
properties.put(CanalConstants.CANAL_MQ_FLAT_MESSAGE, canalClientConfig.getFlatMessage());
properties.put(CanalConstants.CANAL_ALIYUN_ACCESS_KEY, canalClientConfig.getAccessKey());
properties.put(CanalConstants.CANAL_ALIYUN_SECRET_KEY, canalClientConfig.getSecretKey());
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(canalMsgConsumer.getClass().getClassLoader());
canalMsgConsumer.init(properties, canalDestination, groupId);
Thread.currentThread().setContextClassLoader(cl);
}
public void start() {
if (!running) {
thread = new Thread(this::process);
thread.setUncaughtExceptionHandler(handler);
thread.start();
running = true;
}
}
public void writeOut(final List<CommonMessage> commonMessages) {
List<Future<Boolean>> futures = new ArrayList<>();
// 组间适配器并行运行
canalOuterAdapters.forEach(outerAdapters -> {
futures.add(groupInnerExecutorService.submit(() -> {
try {
// 组内适配器穿行运行,尽量不要配置组内适配器
outerAdapters.forEach(adapter -> {
long begin = System.currentTimeMillis();
List<Dml> dmls = MessageUtil.flatMessage2Dml(canalDestination, groupId, commonMessages);
batchSync(dmls, adapter);
if (logger.isDebugEnabled()) {
logger.debug("{} elapsed time: {}",
adapter.getClass().getName(),
(System.currentTimeMillis() - begin));
}
});
return true;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
}));
// 等待所有适配器写入完成
// 由于是组间并发操作,所以将阻塞直到耗时最久的工作组操作完成
RuntimeException exception = null;
for (Future<Boolean> future : futures) {
try {
if (!future.get()) {
exception = new RuntimeException("Outer adapter sync failed! ");
}
} catch (Exception e) {
exception = new RuntimeException(e);
}
}
if (exception != null) {
throw exception;
}
});
}
/**
* 分批同步
*
* @param dmls
* @param adapter
*/
private void batchSync(List<Dml> dmls, OuterAdapter adapter) {
// 分批同步
if (dmls.size() <= canalClientConfig.getSyncBatchSize()) {
adapter.sync(dmls);
} else {
int len = 0;
List<Dml> dmlsBatch = new ArrayList<>();
for (Dml dml : dmls) {
dmlsBatch.add(dml);
if (dml.getData() == null || dml.getData().isEmpty()) {
len += 1;
} else {
len += dml.getData().size();
}
if (len >= canalClientConfig.getSyncBatchSize()) {
adapter.sync(dmlsBatch);
dmlsBatch.clear();
len = 0;
}
}
if (!dmlsBatch.isEmpty()) {
adapter.sync(dmlsBatch);
}
}
}
private void process() {
while (!running) { // waiting until running == true
while (!running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
int retry = canalClientConfig.getRetries() == null
|| canalClientConfig.getRetries() == 0 ? 1 : canalClientConfig.getRetries();
if (retry == -1) {
// 重试次数-1代表异常时一直阻塞重试
retry = Integer.MAX_VALUE;
}
while (running) {
try {
syncSwitch.get(canalDestination);
logger.info("=============> Start to connect destination: {} <=============", this.canalDestination);
canalMsgConsumer.connect();
logger.info("=============> Subscribe destination: {} succeed <=============", this.canalDestination);
while (running) {
try {
syncSwitch.get(canalDestination, 1L, TimeUnit.MINUTES);
} catch (TimeoutException e) {
break;
}
if (!running) {
break;
}
for (int i = 0; i < retry; i++) {
if (!running) {
break;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("destination: {} ", canalDestination);
}
long begin = System.currentTimeMillis();
List<CommonMessage> commonMessages = canalMsgConsumer
.getMessage(this.canalClientConfig.getTimeout(), TimeUnit.MILLISECONDS);
writeOut(commonMessages);
canalMsgConsumer.ack();
if (logger.isDebugEnabled()) {
logger.debug("destination: {} elapsed time: {} ms",
canalDestination,
System.currentTimeMillis() - begin);
}
break;
} catch (Exception e) {
if (i != retry - 1) {
canalMsgConsumer.rollback(); // 处理失败, 回滚数据
logger.error(e.getMessage() + " Error sync and rollback, execute times: " + (i + 1));
} else {
canalMsgConsumer.ack();
logger.error(e.getMessage() + " Error sync but ACK!");
}
Thread.sleep(500);
}
}
}
canalMsgConsumer.disconnect();
} catch (Throwable e) {
logger.error("process error!", e);
}
if (running) { // is reconnect
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}
public void stop() {
try {
if (!running) {
return;
}
running = false;
syncSwitch.release(canalDestination);
logger.info("destination {} is waiting for adapters' worker thread die!", canalDestination);
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
groupInnerExecutorService.shutdown();
logger.info("destination {} adapters worker thread dead!", canalDestination);
canalOuterAdapters.forEach(outerAdapters -> outerAdapters.forEach(OuterAdapter::destroy));
logger.info("destination {} all adapters destroyed!", canalDestination);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
|
package com.enjoy.study.season02_JVM.ch04.load;
/**
* <b>Author</b>: Hsiang Leekwok<br/>
* <b>Date</b>: 2019/06/02 21:28<br/>
* <b>Version</b>: v1.0<br/>
* <b>Subject</b>: <br/>
* <b>Description</b>:
*/
public class SuperClass {
static {
System.out.println("SuperClass init!");
}
public static int value = 123;
public static final String HELLO_WORLD = "Hello World.";
public static final int WHAT = value;
}
|
package cn.sevenyuan.demo;
import cn.sevenyuan.demo.domain.Book;
import cn.sevenyuan.demo.domain.User;
import cn.sevenyuan.demo.service.MailService;
import com.google.common.collect.Lists;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.List;
/**
* @author JingQ at 2019-08-18
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceImplTest {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void sendMailWithImg() {
mailService.sendMailWithImg("augus.ye@qq.com","2225204153@qq.com","测试邮件(带图片",
"<div>hello, 这是一封带图片资源的邮件:" +
"这是图片 1:<div><img src='cid:p01'/></div>" +
"这是图片 2:<div><img src='cid:p02'/></div>" +
"</div>",
new String[]{"/Users/yejingqi/Deploy/Blog/图片分类/mail/mail_sender.png",
"/Users/yejingqi/Deploy/Blog/图片分类/mail/demo.png"},
new String[]{"p01", "p02"});
}
@Test
public void sendHtmlMail() {
try {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
ClassLoader loader = SpringBootLearnApplication.class.getClassLoader();
configuration.setClassLoaderForTemplateLoading(loader, "ftl");
Template template = configuration.getTemplate("mailtemplate.ftl");
StringWriter mail = new StringWriter();
User user = new User();
user.setName("一叶知秋");
user.setAge(23);
template.process(user, mail);
mailService.sendHtmlMail("augus.ye@qq.com", "2225204153@qq.com", "Html样式的邮件", mail.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void sendThymeleafMail() {
Context context = new Context();
context.setVariable("subject", "图书清册");
List<Book> books = Lists.newArrayList();
books.add(new Book("Go 语言基础", 1, "nonename", BigDecimal.TEN));
books.add(new Book("Go 语言实战", 2, "nonename", BigDecimal.TEN));
books.add(new Book("Go 语言进阶", 3, "nonename", BigDecimal.TEN));
context.setVariable("books", books);
String mail = templateEngine.process("mailtemplate.html", context);
mailService.sendHtmlMail("augus.ye@qq.com", "2225204153@qq.com", "图书清册", mail);
}
}
|
/**
*
*/
package com.thinkgem.jeesite.modules.sys.dao;
import java.util.List;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.sys.entity.User;
/**
* 用户DAO接口
* @author libn
* @version 2014-05-16
*/
@MyBatisDao
public interface UserDao extends CrudDao<User> {
/**
* 根据登录名称查询用户
* @param loginName
* @return
*/
public User getByLoginName(User user);
/**
* 通过OfficeId获取用户列表,仅返回用户id和name(树查询用户时用)
* @param user
* @return
*/
public List<User> findUserByOfficeId(User user);
/**
* 查询全部用户数目
* @return
*/
public long findAllCount(User user);
/**
* 更新用户密码
* @param user
* @return
*/
public int updatePasswordById(User user);
/**
* 更新登录信息,如:登录IP、登录时间
* @param user
* @return
*/
public int updateLoginInfo(User user);
/**
* 删除用户角色关联数据
* @param user
* @return
*/
public int deleteUserRole(User user);
/**
* 插入用户角色关联数据
* @param user
* @return
*/
public int insertUserRole(User user);
/**
* 更新用户信息
* @param user
* @return
*/
public int updateUserInfo(User user);
}
|
package cn.bos.common.utils;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class E3Result implements Serializable{
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
// 响应业务状态
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
public static E3Result build(Integer status, String msg, Object data) {
return new E3Result(status, msg, data);
}
public static E3Result ok(Object data) {
return new E3Result(data);
}
public static E3Result ok() {
return new E3Result(null);
}
public E3Result() {
}
public static E3Result build(Integer status, String msg) {
return new E3Result(status, msg, null);
}
public E3Result(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public E3Result(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
// public Boolean isOK() {
// return this.status == 200;
// }
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
/**
* 将json结果集转化为Result对象
*
* @param jsonData json数据
* @param clazz Result中的object类型
* @return
*/
public static E3Result formatToPojo(String jsonData, Class<?> clazz) {
try {
if (clazz == null) {
return MAPPER.readValue(jsonData, E3Result.class);
}
JsonNode jsonNode = MAPPER.readTree(jsonData);
JsonNode data = jsonNode.get("data");
Object obj = null;
if (clazz != null) {
if (data.isObject()) {
obj = MAPPER.readValue(data.traverse(), clazz);
} else if (data.isTextual()) {
obj = MAPPER.readValue(data.asText(), clazz);
}
}
return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
} catch (Exception e) {
return null;
}
}
/**
* 没有object对象的转化
*
* @param json
* @return
*/
public static E3Result format(String json) {
try {
return MAPPER.readValue(json, E3Result.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Object是集合转化
*
* @param jsonData json数据
* @param clazz 集合中的类型
* @return
*/
public static E3Result formatToList(String jsonData, Class<?> clazz) {
try {
JsonNode jsonNode = MAPPER.readTree(jsonData);
JsonNode data = jsonNode.get("data");
Object obj = null;
if (data.isArray() && data.size() > 0) {
obj = MAPPER.readValue(data.traverse(),
MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
}
return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
} catch (Exception e) {
return null;
}
}
}
|
/**
* Copyright (c) 2006-2020 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
package org.love2d.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.Manifest;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import androidx.core.app.ActivityCompat;
public class DownloadActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT >= 29 ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
runDownloader();
finish();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, GameActivity.EXTERNAL_STORAGE_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) {
Log.d("DownloadActivity", "Received a request permission result");
if (requestCode == GameActivity.EXTERNAL_STORAGE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
runDownloader();
finish();
} else {
Log.d("DownloadActivity", "Did not get permission.");
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showExternalStoragePermissionMissingDialog();
}
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
protected void showExternalStoragePermissionMissingDialog() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Storage Permission Missing")
.setMessage("LÖVE for Android will not be able to download games without storage permission.")
.setNeutralButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.create();
dialog.show();
}
protected void runDownloader()
{
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
Intent targetIntent = new Intent(this, DownloadService.class);
targetIntent.putExtra("url", uri.toString());
startService(targetIntent);
}
}
}
|
package greensnow25.com;
import jdk.internal.org.xml.sax.XMLReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
/**
* public class ParserStAX.
*
* @author greensnow25.
* @version 1.
* @since 02.06.2017.
*/
public class ParserStAX {
private XMLInputFactory xmlInputFactory;
private String path = "D:\\java video\\orders.xml";
private HashMap<String, Order> map;
Order order;
public ParserStAX() {
this.xmlInputFactory = XMLInputFactory.newInstance();
this.map = new HashMap<>();
}
public void parse() throws FileNotFoundException, XMLStreamException {
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(new FileReader(path));
while (reader.hasNext()) {
if (reader.isStartElement()) {
String value = reader.getLocalName();
if (value.equals("AddOrder")) {
String id = reader.getAttributeValue(4);
order = new Order(reader.getAttributeValue(0)
, reader.getAttributeValue(1).equals("BUY")
, Double.parseDouble(reader.getAttributeValue(2))
, Integer.parseInt(reader.getAttributeValue(3))
, Integer.parseInt(id));
map.put(id, order);
order = null;
} else if (value.equals("DeleteOrder")) {
map.remove(Integer.parseInt(reader.getAttributeValue(1)));
}
}
}
}
public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
ParserStAX stAX = new ParserStAX();
double start = System.currentTimeMillis();
stAX.parse();
double finish = System.currentTimeMillis();
System.out.println(finish - start);
}
}
|
/*-
* #%L
* Spring Auto REST Docs Core
* %%
* Copyright (C) 2015 - 2020 Scalable Capital GmbH
* %%
* 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.
* #L%
*/
package capital.scalable.restdocs.request;
import static capital.scalable.restdocs.SnippetRegistry.AUTO_PATH_PARAMETERS;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Optional;
import capital.scalable.restdocs.constraints.ConstraintReader;
import capital.scalable.restdocs.javadoc.JavadocReader;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.restdocs.AbstractSnippetTests;
import org.springframework.restdocs.snippet.SnippetException;
import org.springframework.restdocs.templates.TemplateFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.method.HandlerMethod;
public class PathParametersSnippetTest extends AbstractSnippetTests {
private JavadocReader javadocReader;
private ConstraintReader constraintReader;
@Rule
public ExpectedException thrown = ExpectedException.none();
public PathParametersSnippetTest(String name, TemplateFormat templateFormat) {
super(name, templateFormat);
}
@Before
public void setup() {
javadocReader = mock(JavadocReader.class);
constraintReader = mock(ConstraintReader.class);
}
@Test
public void simpleRequest() throws Exception {
HandlerMethod handlerMethod = createHandlerMethod("addItem", Integer.class, String.class,
int.class, String.class, Optional.class);
initParameters(handlerMethod);
mockParamComment("addItem", "id", "An integer");
mockParamComment("addItem", "otherId", "A string");
mockParamComment("addItem", "partId", "An integer");
mockParamComment("addItem", "yetAnotherId", "Another string");
mockParamComment("addItem", "optionalId", "Optional string");
new PathParametersSnippet().document(operationBuilder
.attribute(HandlerMethod.class.getName(), handlerMethod)
.attribute(JavadocReader.class.getName(), javadocReader)
.attribute(ConstraintReader.class.getName(), constraintReader)
.build());
assertThat(this.generatedSnippets.snippet(AUTO_PATH_PARAMETERS)).is(
tableWithHeader("Parameter", "Type", "Optional", "Description")
.row("id", "Integer", "false", "An integer.")
.row("subid", "String", "false", "A string.")
.row("partId", "Integer", "false", "An integer.")
.row("yetAnotherId", "String", "true", "Another string.")
.row("optionalId", "String", "true", "Optional string."));
}
@Test
public void simpleRequestWithEnum() throws Exception {
HandlerMethod handlerMethod = createHandlerMethod("getItemsByShape",
TestResource.Shape.class);
initParameters(handlerMethod);
mockParamComment("getItemsByShape", "shape", "An enum");
mockConstraintMessage(handlerMethod.getMethodParameters()[0],
"Must be one of [SPHERIC, SQUARE]");
new PathParametersSnippet().document(operationBuilder
.attribute(HandlerMethod.class.getName(), handlerMethod)
.attribute(JavadocReader.class.getName(), javadocReader)
.attribute(ConstraintReader.class.getName(), constraintReader)
.build());
assertThat(this.generatedSnippets.snippet(AUTO_PATH_PARAMETERS)).is(
tableWithHeader("Parameter", "Type", "Optional", "Description")
.row("shape", "String", "false",
"An enum.\n\nMust be one of [SPHERIC, SQUARE]."));
}
@Test
public void noParameters() throws Exception {
HandlerMethod handlerMethod = createHandlerMethod("addItem");
new PathParametersSnippet().document(operationBuilder
.attribute(HandlerMethod.class.getName(), handlerMethod)
.build());
assertThat(this.generatedSnippets.snippet(AUTO_PATH_PARAMETERS)).isEqualTo("No parameters.");
}
@Test
public void noHandlerMethod() throws Exception {
new PathParametersSnippet().document(operationBuilder
.build());
assertThat(this.generatedSnippets.snippet(AUTO_PATH_PARAMETERS)).isEqualTo("No parameters.");
}
@Test
public void failOnUndocumentedParams() throws Exception {
HandlerMethod handlerMethod = createHandlerMethod("addItem", Integer.class, String.class,
int.class, String.class, Optional.class);
initParameters(handlerMethod);
thrown.expect(SnippetException.class);
thrown.expectMessage(
"Following path parameters were not documented: [id, subid, partId, yetAnotherId, optionalId]");
new PathParametersSnippet().failOnUndocumentedParams(true).document(operationBuilder
.attribute(HandlerMethod.class.getName(), handlerMethod)
.attribute(JavadocReader.class.getName(), javadocReader)
.attribute(ConstraintReader.class.getName(), constraintReader)
.build());
}
@Test
public void deprecated() throws Exception {
HandlerMethod handlerMethod = createHandlerMethod("removeItem", int.class);
initParameters(handlerMethod);
mockParamComment("removeItem", "index", "item's index");
new PathParametersSnippet().document(operationBuilder
.attribute(HandlerMethod.class.getName(), handlerMethod)
.attribute(JavadocReader.class.getName(), javadocReader)
.attribute(ConstraintReader.class.getName(), constraintReader)
.build());
assertThat(this.generatedSnippets.snippet(AUTO_PATH_PARAMETERS)).is(
tableWithHeader("Parameter", "Type", "Optional", "Description")
.row("index", "Integer", "false", "**Deprecated.**\n\nItem's index."));
}
private void initParameters(HandlerMethod handlerMethod) {
for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
parameter.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
}
}
private void mockParamComment(String methodName, String parameterName, String comment) {
when(javadocReader.resolveMethodParameterComment(TestResource.class, methodName,
parameterName)).thenReturn(comment);
}
private void mockConstraintMessage(MethodParameter param, String comment) {
when(constraintReader.getConstraintMessages(param))
.thenReturn(singletonList(comment));
}
private HandlerMethod createHandlerMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException {
return new HandlerMethod(new TestResource(), name, parameterTypes);
}
private static class TestResource {
enum Shape {
SPHERIC, SQUARE
}
@PostMapping("/items/{id}/subitem/{subid}/{partId}/{yetAnotherId}/{optionalId}")
public void addItem(@PathVariable Integer id,
@PathVariable("subid") String otherId,
// partId is required anyway, because it's a primitive type
@PathVariable(required = false) int partId,
@PathVariable(required = false) String yetAnotherId,
@PathVariable Optional<String> optionalId) {
// NOOP
}
@GetMapping("/items")
public void addItem() {
// NOOP
}
@GetMapping("/items/{shape}")
public void getItemsByShape(@PathVariable Shape shape) {
// NOOP
}
public void removeItem(@Deprecated @PathVariable int index) {
}
}
}
|
//package cn.hikyson.godeye.monitor.modules;
//
//import android.net.Uri;
//
//import java.util.Collection;
//
///**
// * Created by kysonchao on 2017/11/27.
// */
//public abstract class BaseListModule<T> implements Module {
// @Override
// public byte[] process(String path, Uri uri) throws Throwable {
// Collection<T> ts = popData();
// if (ts == null || ts.isEmpty()) {
// return new ResultWrapper("no datas for " + getClass().getSimpleName()).toBytes();
// }
// return new ResultWrapper<>(ts).toBytes();
// }
//
// abstract Collection<T> popData();
//}
|
package com.silentmatt.dss.evaluator;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class GlobalScopeTest {
Scope<Integer> superSuperGlobal;
Scope<Integer> superGlobal;
GlobalScope<Integer> globalScope;
@Before
public void setUp() {
superSuperGlobal = new Scope<>(null, Collections.singletonMap("fromSuperSuperGlobal", 42));
superGlobal = new Scope<>(superSuperGlobal, Collections.singletonMap("fromSuperGlobal", 21));
globalScope = new GlobalScope<>(superGlobal, Collections.singletonMap("fromGlobal", 5));
}
@Test
public void testConstructors() {
Scope<Integer> parent = new Scope<>(null);
parent.declare("fromParent", 99);
globalScope = new GlobalScope<>(parent);
assertEquals(Integer.valueOf(99), globalScope.get("fromParent"));
globalScope = new GlobalScope<>(parent, Arrays.asList("a", "b"));
assertTrue(globalScope.declaresKey("a"));
assertTrue(globalScope.declaresKey("b"));
assertFalse(parent.containsKey("a"));
assertFalse(parent.containsKey("b"));
Map<String, Integer> variables = new HashMap<>();
variables.put("A", 1);
variables.put("B", 2);
globalScope = new GlobalScope<>(parent, variables);
assertEquals(Integer.valueOf(1), globalScope.get("A"));
assertEquals(Integer.valueOf(2), globalScope.get("B"));
assertEquals(Integer.valueOf(99), globalScope.get("fromParent"));
assertFalse(parent.containsKey("A"));
}
@Test
public void actsAsTopLevelScope() {
assertNull(globalScope.parent());
assertSame(globalScope, globalScope.getGlobalScope());
}
@Test
public void ownAndParentValuesAreAccessible() {
assertEquals(Integer.valueOf(5), globalScope.get("fromGlobal"));
assertEquals(Integer.valueOf(21), globalScope.get("fromSuperGlobal"));
assertEquals(Integer.valueOf(42), globalScope.get("fromSuperSuperGlobal"));
}
@Test
public void declaresKeyChecksParents() {
assertTrue(globalScope.declaresKey("fromGlobal"));
assertTrue(globalScope.declaresKey("fromSuperGlobal"));
assertTrue(globalScope.declaresKey("fromSuperSuperGlobal"));
}
}
|
/* loopchute: A Maze-Solving Game
Copyright (C) 2008-2012 Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.loopchute.objects;
import com.puttysoftware.loopchute.generic.ColorConstants;
import com.puttysoftware.loopchute.generic.GenericCheckKey;
public class RedCrystal extends GenericCheckKey {
// Constructors
public RedCrystal() {
super(ColorConstants.COLOR_RED);
}
// Scriptability
@Override
public String getName() {
return "Red Crystal";
}
@Override
public String getPluralName() {
return "Red Crystals";
}
@Override
public String getDescription() {
return "Red Crystals will open Red Crystal Walls.";
}
@Override
public String getBaseName() {
return "Crystal";
}
}
|
/*
* Encog(tm) Core v3.3 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2014 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.mathutil.dimension;
/**
* Specifies a constraint for dimensions, using a lower and upper bound.
*
* @author jheaton
*
*/
public class DimensionConstraint {
/**
* The lower bound for each dimension.
*/
private final MultiDimension lower;
/**
* The upper bound for each dimension.
*/
private final MultiDimension upper;
/**
* Construct the constraint.
*
* @param n
* The number of dimensions.
* @param theLower
* @param theUpper
*/
public DimensionConstraint(int n, int theLower, int theUpper) {
this.lower = new MultiDimension(n);
this.upper = new MultiDimension(n);
for (int i = 0; i < n; i++) {
this.lower.setDimension(i, theLower);
this.upper.setDimension(i, theUpper);
}
}
/**
* @return The lower bound for each dimension.
*/
public MultiDimension getLower() {
return lower;
}
/**
* @return The upper bound for each dimension.
*/
public MultiDimension getUpper() {
return upper;
}
/**
* Get the lower bound for a specific dimension.
*
* @param d
* The dimension.
* @return The lower bound for the specified dimension.
*/
public int getLower(int d) {
return lower.getDimension(d);
}
/**
* Get the upper bound for a specific dimension.
*
* @param d
* The dimension.
* @return The upper bound for the specified dimension.
*/
public int getUpper(int d) {
return upper.getDimension(d);
}
/**
* Get the range (between upper and lower bound) for the specified
* dimension.
*
* @param d
* The dimension.
* @return The range for the specified dimension.
*/
public int getRange(int d) {
return (upper.getDimension(d) - lower.getDimension(d))+1;
}
public int getMiddle(int d) {
return getRange(d)/2;
}
}
|
// AUTOGENERATED CODE. DO NOT MODIFY DIRECTLY! Instead, please modify the tuple/ArrayTupleX.ftl file.
// See the README in the module's src/template directory for details.
package com.linkedin.dagli.tuple;
import java.util.function.IntFunction;
/**
* A tuple of arity 19 that is backed by an array.
* ArrayTuples are less memory-efficient than FieldTuples because they require storing an extra object (the array),
* but are trivially cheap to create from an existing array of tuple elements.
*/
final class ArrayTuple19<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S> extends AbstractTuple implements
Tuple19<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S> {
private static final long serialVersionUID = 1;
private final Object[] _array;
/**
* Creates a new tuple whose elements are stored in the provided array. Note that it is not possible for the
* ArrayTuple to verify that the types of elements in the array satisfy the declared types of elements in the tuple;
* the caller is responsible for ensuring this.
*
* The tuple takes ownership of the array, which should not be subsequently modified.
*/
public ArrayTuple19(Object[] array) {
assert array.length == 19;
_array = array;
}
@Override
@SuppressWarnings("unchecked")
public A get0() {
return (A) _array[0];
}
@Override
@SuppressWarnings("unchecked")
public B get1() {
return (B) _array[1];
}
@Override
@SuppressWarnings("unchecked")
public C get2() {
return (C) _array[2];
}
@Override
@SuppressWarnings("unchecked")
public D get3() {
return (D) _array[3];
}
@Override
@SuppressWarnings("unchecked")
public E get4() {
return (E) _array[4];
}
@Override
@SuppressWarnings("unchecked")
public F get5() {
return (F) _array[5];
}
@Override
@SuppressWarnings("unchecked")
public G get6() {
return (G) _array[6];
}
@Override
@SuppressWarnings("unchecked")
public H get7() {
return (H) _array[7];
}
@Override
@SuppressWarnings("unchecked")
public I get8() {
return (I) _array[8];
}
@Override
@SuppressWarnings("unchecked")
public J get9() {
return (J) _array[9];
}
@Override
@SuppressWarnings("unchecked")
public K get10() {
return (K) _array[10];
}
@Override
@SuppressWarnings("unchecked")
public L get11() {
return (L) _array[11];
}
@Override
@SuppressWarnings("unchecked")
public M get12() {
return (M) _array[12];
}
@Override
@SuppressWarnings("unchecked")
public N get13() {
return (N) _array[13];
}
@Override
@SuppressWarnings("unchecked")
public O get14() {
return (O) _array[14];
}
@Override
@SuppressWarnings("unchecked")
public P get15() {
return (P) _array[15];
}
@Override
@SuppressWarnings("unchecked")
public Q get16() {
return (Q) _array[16];
}
@Override
@SuppressWarnings("unchecked")
public R get17() {
return (R) _array[17];
}
@Override
@SuppressWarnings("unchecked")
public S get18() {
return (S) _array[18];
}
@Override
public Object get(int index) {
return _array[index];
}
@Override
public int size() {
return 19;
}
@Override
public Object[] toArray() {
return _array.clone();
}
@Override
public <TT> TT[] toArray(IntFunction<TT[]> arrayGenerator) {
TT[] result = arrayGenerator.apply(19);
System.arraycopy(_array, 0, result, 0, 19);
return result;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Copyright (C) 2006-2010 Adele Team/LIG/Grenoble University, France
*/
package fede.workspace.tool.view.dialog.create;
import org.eclipse.swt.graphics.Image;
import fr.imag.adele.cadse.core.ui.RuningInteractionController;
public interface InteractifTreeController extends RuningInteractionController {
public String getText(Object obj);
public Image getImage(Object obj);
public Object[] getChildren(Object obj);
}
|
/**
* Spring MVC REST controllers.
*/
package jp.boy.java.web.rest.page01;
|
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.dmn.xls2dmn.cli;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.drools.decisiontable.parser.DecisionTableParser;
import org.drools.decisiontable.parser.xls.ExcelParser;
import org.drools.template.parser.DataListener;
import org.drools.template.parser.DecisionTableParseException;
import org.kie.dmn.api.marshalling.DMNMarshaller;
import org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory;
import org.kie.dmn.feel.codegen.feel11.CodegenStringUtil;
import org.kie.dmn.model.api.DMNElementReference;
import org.kie.dmn.model.api.DRGElement;
import org.kie.dmn.model.api.Decision;
import org.kie.dmn.model.api.DecisionTable;
import org.kie.dmn.model.api.Definitions;
import org.kie.dmn.model.api.HitPolicy;
import org.kie.dmn.model.api.InformationItem;
import org.kie.dmn.model.api.InformationRequirement;
import org.kie.dmn.model.api.InputClause;
import org.kie.dmn.model.api.InputData;
import org.kie.dmn.model.api.LiteralExpression;
import org.kie.dmn.model.api.OutputClause;
import org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase;
import org.kie.dmn.model.v1_2.TDMNElementReference;
import org.kie.dmn.model.v1_2.TDecision;
import org.kie.dmn.model.v1_2.TDecisionTable;
import org.kie.dmn.model.v1_2.TDefinitions;
import org.kie.dmn.model.v1_2.TInformationItem;
import org.kie.dmn.model.v1_2.TInformationRequirement;
import org.kie.dmn.model.v1_2.TInputClause;
import org.kie.dmn.model.v1_2.TInputData;
import org.kie.dmn.model.v1_2.TLiteralExpression;
import org.kie.dmn.model.v1_2.TOutputClause;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class XLS2DMNParser implements DecisionTableParser {
private static final Logger LOG = LoggerFactory.getLogger(XLS2DMNParser.class);
private final File outFile;
public XLS2DMNParser(File outFile) {
this.outFile = outFile;
}
@Override
public void parseFile(InputStream inStream) {
try {
parseWorkbook(WorkbookFactory.create(inStream));
} catch (IOException e) {
throw new DecisionTableParseException(
"Failed to open Excel stream, " + "please check that the content is xls97 format.", e);
}
}
@Override
public void parseFile(File file) {
try {
parseWorkbook(WorkbookFactory.create(file, (String) null, true));
} catch (IOException e) {
throw new DecisionTableParseException(
"Failed to open Excel stream, " + "please check that the content is xls97 format.", e);
}
}
public void parseWorkbook(Workbook workbook) {
Map<String, List<String>> overview = new HashMap<>();
DataFormatter formatter = new DataFormatter();
for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
Sheet sheet = workbook.getSheetAt(s);
int maxRows = sheet.getLastRowNum();
for (int i = 0; i <= maxRows; i++) {
Row row = sheet.getRow(i);
int lastCellNum = row != null ? row.getLastCellNum() : 0;
if (lastCellNum == 0) {
continue; // skip empty row.
}
List<String> header = new ArrayList<>();
for (Cell c : row) {
String text = formatter.formatCellValue(c);
header.add(text);
}
overview.put(sheet.getSheetName(), header);
break; // header found.
}
}
overview.entrySet().forEach(e -> LOG.debug("{}", e));
Map<String, DTHeaderInfo> headerInfos = generateDTHeaderInfo(overview);
LOG.info("Sheets have been indexed as:");
headerInfos.entrySet().forEach(e -> LOG.info("{}", e));
Definitions definitions = new TDefinitions();
setDefaultNSContext(definitions);
definitions.setName("xls2dmn");
String namespace = "xls2dmn_" + UUID.randomUUID();
definitions.setNamespace(namespace);
definitions.getNsContext().put(XMLConstants.DEFAULT_NS_PREFIX, namespace);
definitions.setExporter("kie-dmn-xls2dmn");
appendInputData(definitions, headerInfos);
appendDecisionDT(definitions, headerInfos);
final Map<String, List<DataListener>> sheetListeners = new HashMap<>();
for (DTHeaderInfo hi : headerInfos.values()) {
String sheetName = hi.getSheetName();
DRGElement drgElem = definitions.getDrgElement().stream().filter(e -> e.getName().equals(sheetName)).findFirst().orElseThrow(() -> new XLS2DMNException("Unable to locate DRG element for sheet: " + sheetName));
DecisionTable dt = (DecisionTable) ((Decision) drgElem).getExpression();
DTSheetListener listener = new DTSheetListener(dt, hi);
sheetListeners.put(sheetName, Arrays.asList(listener));
}
new ExcelParser(sheetListeners).parseWorkbook(workbook);
DMNMarshaller dmnMarshaller = DMNMarshallerFactory.newDefaultMarshaller();
String xml = dmnMarshaller.marshal(definitions);
try {
Files.write(outFile.toPath(), xml.getBytes());
} catch (IOException e) {
LOG.error("Unable to write to outputfile.", e);
throw new XLS2DMNException("Unable to write to outputfile", e);
}
LOG.debug("output XML can be displayed at trace level",xml);
LOG.trace("output XML:\n{}",xml);
}
private void appendDecisionDT(Definitions definitions, Map<String, DTHeaderInfo> headerInfos) {
for (DTHeaderInfo hi : headerInfos.values()) {
Decision decision = new TDecision();
decision.setName(hi.getSheetName());
decision.setId("d_" + CodegenStringUtil.escapeIdentifier(hi.getSheetName()));
InformationItem variable = new TInformationItem();
variable.setName(hi.getSheetName());
variable.setId("dvar_" + CodegenStringUtil.escapeIdentifier(hi.getSheetName()));
variable.setTypeRef(new QName("Any"));
decision.setVariable(variable);
for (String ri : hi.getRequiredInput()) {
InformationRequirement ir = new TInformationRequirement();
DMNElementReference er = new TDMNElementReference();
er.setHref("#id_" + CodegenStringUtil.escapeIdentifier(ri));
ir.setRequiredInput(er);
decision.getInformationRequirement().add(ir);
}
for (String ri : hi.getRequiredDecision()) {
InformationRequirement ir = new TInformationRequirement();
DMNElementReference er = new TDMNElementReference();
er.setHref("#d_" + CodegenStringUtil.escapeIdentifier(ri));
ir.setRequiredDecision(er);
decision.getInformationRequirement().add(ir);
}
DecisionTable dt = new TDecisionTable();
dt.setOutputLabel(hi.getSheetName());
dt.setId("ddt_" + CodegenStringUtil.escapeIdentifier(hi.getSheetName()));
dt.setHitPolicy(HitPolicy.ANY);
for (String ri : hi.getRequiredInput()) {
InputClause ic = new TInputClause();
ic.setLabel(ri);
LiteralExpression le = new TLiteralExpression();
le.setText(ri);
ic.setInputExpression(le);
dt.getInput().add(ic);
}
for (String rd : hi.getRequiredDecision()) {
InputClause ic = new TInputClause();
ic.setLabel(rd);
LiteralExpression le = new TLiteralExpression();
le.setText(rd);
ic.setInputExpression(le);
dt.getInput().add(ic);
}
OutputClause oc = new TOutputClause();
dt.getOutput().add(oc);
decision.setExpression(dt);
definitions.getDrgElement().add(decision);
}
}
private void setDefaultNSContext(Definitions definitions) {
Map<String, String> nsContext = definitions.getNsContext();
nsContext.put("feel", KieDMNModelInstrumentedBase.URI_FEEL);
nsContext.put("dmn", KieDMNModelInstrumentedBase.URI_DMN);
nsContext.put("dmndi", KieDMNModelInstrumentedBase.URI_DMNDI);
nsContext.put("di", KieDMNModelInstrumentedBase.URI_DI);
nsContext.put("dc", KieDMNModelInstrumentedBase.URI_DC);
}
private void appendInputData(Definitions definitions, Map<String, DTHeaderInfo> headerInfos) {
Set<String> usedRI = new LinkedHashSet<>();
for ( DTHeaderInfo hi : headerInfos.values()) {
for(String ri : hi.getRequiredInput()) {
if (!usedRI.contains(ri)) {
InputData id = new TInputData();
id.setName(ri);
id.setId("id_"+CodegenStringUtil.escapeIdentifier(ri));
InformationItem variable = new TInformationItem();
variable.setName(ri);
variable.setId("idvar_"+CodegenStringUtil.escapeIdentifier(ri));
variable.setTypeRef(new QName("Any"));
id.setVariable(variable);
definitions.getDrgElement().add(id);
}
usedRI.add(ri);
}
}
}
private Map<String, DTHeaderInfo> generateDTHeaderInfo(Map<String, List<String>> overview) {
Map<String, DTHeaderInfo> result = new HashMap<>();
for (Entry<String, List<String>> kv : overview.entrySet()) {
String sheetName = kv.getKey();
List<String> requiredInput = new ArrayList<>();
List<String> requiredDecision = new ArrayList<>();
int hIndex = kv.getValue().indexOf(sheetName);
if (hIndex < 0) {
throw new XLS2DMNException("There is no result output column in sheet: " + sheetName);
}
if (hIndex != kv.getValue().size()) {
for (int i = hIndex+1; i < kv.getValue().size(); i++) {
String afterIndexValue = kv.getValue().get(i);
if (!(afterIndexValue == null || afterIndexValue.isEmpty())) {
throw new XLS2DMNException("Decision name was not last, on the right I found " + afterIndexValue);
}
}
}
for (int i = 0; i < hIndex; i++) {
String hValue = kv.getValue().get(i);
if (overview.containsKey(hValue)) {
requiredDecision.add(hValue);
} else {
requiredInput.add(hValue);
}
}
DTHeaderInfo info = new DTHeaderInfo(sheetName, kv.getValue(), hIndex, requiredInput, requiredDecision);
result.put(sheetName, info);
}
return result;
}
}
|
package com.mygdx.game;
/**
* Created by Demo on 03/08/2017.
*/
//Interface necessary to Write message from libgdx Core.
public interface IBluetooth {
void write(String str);
boolean isConnected();
}
|
package de.budschie.bmorph.network;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Supplier;
import de.budschie.bmorph.main.BMorphMod;
import de.budschie.bmorph.morph.VisualMorphDataRegistry.VisualMorphData;
import de.budschie.bmorph.network.VisualMorphSynchronizer.VisualMorphPacket;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fmllegacy.network.NetworkEvent.Context;
public class VisualMorphSynchronizer implements ISimpleImplPacket<VisualMorphPacket>
{
@Override
public void encode(VisualMorphPacket packet, FriendlyByteBuf buffer)
{
buffer.writeCollection(packet.getData(), (bufferToWriteTo, visualMorphData) ->
{
bufferToWriteTo.writeFloat(visualMorphData.getScale());
bufferToWriteTo.writeResourceLocation(visualMorphData.getRegistryName());
});
}
@Override
public VisualMorphPacket decode(FriendlyByteBuf buffer)
{
return new VisualMorphPacket(buffer.readCollection(length -> new ArrayList<>(length), bufferToReadFrom ->
{
VisualMorphData data = new VisualMorphData(bufferToReadFrom.readFloat());
data.setRegistryName(bufferToReadFrom.readResourceLocation());
return data;
}));
}
@Override
public void handle(VisualMorphPacket packet, Supplier<Context> ctx)
{
ctx.get().enqueueWork(() ->
{
BMorphMod.VISUAL_MORPH_DATA.clear();
for(VisualMorphData data : packet.getData())
BMorphMod.VISUAL_MORPH_DATA.addVisualMorphData(data);
});
}
public static class VisualMorphPacket
{
private Collection<VisualMorphData> data;
public VisualMorphPacket(Collection<VisualMorphData> data)
{
this.data = data;
}
public Collection<VisualMorphData> getData()
{
return data;
}
}
}
|
/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package org.excitinglab.droplet.config;
import org.excitinglab.droplet.config.impl.ConfigImpl;
import java.util.Map;
/**
* This class holds some static factory methods for building {@link ConfigValue}
* instances. See also {@link ConfigFactory} which has methods for parsing files
* and certain in-memory data structures.
*/
public final class ConfigValueFactory {
private ConfigValueFactory() {
}
/**
* Creates a {@link ConfigValue} from a plain Java boxed value, which may be
* a <code>Boolean</code>, <code>Number</code>, <code>String</code>,
* <code>Map</code>, <code>Iterable</code>, or <code>null</code>. A
* <code>Map</code> must be a <code>Map</code> from String to more values
* that can be supplied to <code>fromAnyRef()</code>. An
* <code>Iterable</code> must iterate over more values that can be supplied
* to <code>fromAnyRef()</code>. A <code>Map</code> will become a
* {@link ConfigObject} and an <code>Iterable</code> will become a
* {@link ConfigList}. If the <code>Iterable</code> is not an ordered
* collection, results could be strange, since <code>ConfigList</code> is
* ordered.
*
* <p>
* In a <code>Map</code> passed to <code>fromAnyRef()</code>, the map's keys
* are plain keys, not path expressions. So if your <code>Map</code> has a
* key "foo.bar" then you will get one object with a key called "foo.bar",
* rather than an object with a key "foo" containing another object with a
* key "bar".
*
* <p>
* The originDescription will be used to set the origin() field on the
* ConfigValue. It should normally be the name of the file the values came
* from, or something short describing the value such as "default settings".
* The originDescription is prefixed to error messages so users can tell
* where problematic values are coming from.
*
* <p>
* Supplying the result of ConfigValue.unwrapped() to this function is
* guaranteed to work and should give you back a ConfigValue that matches
* the one you unwrapped. The re-wrapped ConfigValue will lose some
* information that was present in the original such as its origin, but it
* will have matching values.
*
* <p>
* If you pass in a <code>ConfigValue</code> to this
* function, it will be returned unmodified. (The
* <code>originDescription</code> will be ignored in this
* case.)
*
* <p>
* This function throws if you supply a value that cannot be converted to a
* ConfigValue, but supplying such a value is a bug in your program, so you
* should never handle the exception. Just fix your program (or report a bug
* against this library).
*
* @param object
* object to convert to ConfigValue
* @param originDescription
* name of origin file or brief description of what the value is
* @return a new value
*/
public static ConfigValue fromAnyRef(Object object, String originDescription) {
return ConfigImpl.fromAnyRef(object, originDescription);
}
/**
* See the {@link #fromAnyRef(Object, String)} documentation for details.
* This is a typesafe wrapper that only works on {@link Map} and
* returns {@link ConfigObject} rather than {@link ConfigValue}.
*
* <p>
* If your <code>Map</code> has a key "foo.bar" then you will get one object
* with a key called "foo.bar", rather than an object with a key "foo"
* containing another object with a key "bar". The keys in the map are keys;
* not path expressions. That is, the <code>Map</code> corresponds exactly
* to a single {@code ConfigObject}. The keys will not be parsed or
* modified, and the values are wrapped in ConfigValue. To get nested
* {@code ConfigObject}, some of the values in the map would have to be more
* maps.
*
* <p>
* See also {@link ConfigFactory#parseMap(Map, String)} which interprets the
* keys in the map as path expressions.
*
* @param values map from keys to plain Java values
* @param originDescription description to use in {@link ConfigOrigin} of created values
* @return a new {@link ConfigObject} value
*/
public static ConfigObject fromMap(Map<String, ? extends Object> values,
String originDescription) {
return (ConfigObject) fromAnyRef(values, originDescription);
}
/**
* See the {@link #fromAnyRef(Object, String)} documentation for details.
* This is a typesafe wrapper that only works on {@link Iterable}
* and returns {@link ConfigList} rather than {@link ConfigValue}.
*
* @param values list of plain Java values
* @param originDescription description to use in {@link ConfigOrigin} of created values
* @return a new {@link ConfigList} value
*/
public static ConfigList fromIterable(Iterable<? extends Object> values,
String originDescription) {
return (ConfigList) fromAnyRef(values, originDescription);
}
/**
* See the other overload {@link #fromAnyRef(Object, String)} for details,
* this one just uses a default origin description.
*
* @param object a plain Java value
* @return a new {@link ConfigValue}
*/
public static ConfigValue fromAnyRef(Object object) {
return fromAnyRef(object, null);
}
/**
* See the other overload {@link #fromMap(Map, String)} for details, this one
* just uses a default origin description.
*
* <p>
* See also {@link ConfigFactory#parseMap(Map)} which interprets the keys in
* the map as path expressions.
*
* @param values map from keys to plain Java values
* @return a new {@link ConfigObject}
*/
public static ConfigObject fromMap(Map<String, ? extends Object> values) {
return fromMap(values, null);
}
/**
* See the other overload of {@link #fromIterable(Iterable, String)} for
* details, this one just uses a default origin description.
*
* @param values list of plain Java values
* @return a new {@link ConfigList}
*/
public static ConfigList fromIterable(Iterable<? extends Object> values) {
return fromIterable(values, null);
}
}
|
package gms.shared.mechanisms.configuration;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.fasterxml.jackson.databind.ObjectMapper;
import gms.shared.mechanisms.configuration.util.ObjectSerialization;
import org.junit.jupiter.api.Test;
public class SelectorTests {
private ObjectMapper objectMapper = ObjectSerialization.getObjectMapper();
@Test
public void testSerialization() throws Exception {
final Selector<String> selectorStaIsGeres = Selector.from("STATION", "geres");
final String json = objectMapper.writeValueAsString(selectorStaIsGeres);
assertAll(
() -> assertNotNull(json),
() -> assertEquals(selectorStaIsGeres, objectMapper.readValue(json, Selector.class))
);
}
}
|
/**
* Copyright 2006-2021 the original author or authors.
*
* 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 org.mybatis.generator.codegen.mybatis3.javamapper.elements.sqlprovider;
import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getEscapedColumnName;
import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getParameterClause;
import static org.mybatis.generator.internal.util.JavaBeansUtil.getGetterMethodName;
import static org.mybatis.generator.internal.util.StringUtility.escapeStringForJava;
import java.util.Set;
import java.util.TreeSet;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
/**
*
* @author Jeff Butler
*
*/
public class ProviderInsertSelectiveMethodGenerator extends AbstractJavaProviderMethodGenerator {
public ProviderInsertSelectiveMethodGenerator(boolean useLegacyBuilder) {
super(useLegacyBuilder);
}
@Override
public void addClassElements(TopLevelClass topLevelClass) {
Set<String> staticImports = new TreeSet<String>();
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
if (useLegacyBuilder) {
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.BEGIN"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.INSERT_INTO"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.SQL"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.VALUES"); //$NON-NLS-1$
} else {
importedTypes.add(NEW_BUILDER_IMPORT);
}
FullyQualifiedJavaType fqjt = introspectedTable.getRules()
.calculateAllFieldsClass();
importedTypes.add(fqjt);
Method method = new Method(
introspectedTable.getInsertSelectiveStatementId());
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(FullyQualifiedJavaType.getStringInstance());
method.addParameter(new Parameter(fqjt, "record")); //$NON-NLS-1$
context.getCommentGenerator().addGeneralMethodComment(method,
introspectedTable);
if (useLegacyBuilder) {
method.addBodyLine("BEGIN();"); //$NON-NLS-1$
} else {
method.addBodyLine("SQL sql = new SQL();"); //$NON-NLS-1$
}
method.addBodyLine(String.format("%sINSERT_INTO(\"%s\");", //$NON-NLS-1$
builderPrefix,
escapeStringForJava(introspectedTable.getFullyQualifiedTableNameAtRuntime())));
for (IntrospectedColumn introspectedColumn : ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())) {
method.addBodyLine(""); //$NON-NLS-1$
if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()
&& !introspectedColumn.isSequenceColumn()) {
method.addBodyLine(String.format("if (record.%s() != null) {", //$NON-NLS-1$
getGetterMethodName(introspectedColumn.getJavaProperty(),
introspectedColumn.getFullyQualifiedJavaType())));
}
method.addBodyLine(String.format("%sVALUES(\"%s\", \"%s\");", //$NON-NLS-1$
builderPrefix,
escapeStringForJava(getEscapedColumnName(introspectedColumn)),
getParameterClause(introspectedColumn)));
if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()
&& !introspectedColumn.isSequenceColumn()) {
method.addBodyLine("}"); //$NON-NLS-1$
}
}
method.addBodyLine(""); //$NON-NLS-1$
if (useLegacyBuilder) {
method.addBodyLine("return SQL();"); //$NON-NLS-1$
} else {
method.addBodyLine("return sql.toString();"); //$NON-NLS-1$
}
if (context.getPlugins().providerInsertSelectiveMethodGenerated(method, topLevelClass,
introspectedTable)) {
topLevelClass.addStaticImports(staticImports);
topLevelClass.addImportedTypes(importedTypes);
topLevelClass.addMethod(method);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.