下面列出了java.awt.event.ContainerListener#org.jetbrains.annotations.NotNull 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Decompresses a public key based on the algorithm used to generate it.
*
* @param compressedPublicKey Compressed public key as byte[]
* @param algorithmEmployed Algorithm used during key creation
* @return Decompressed public key as byte[]
* @throws EOSFormatterError when public key decompression fails.
*/
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
AlgorithmEmployed algorithmEmployed)
throws EOSFormatterError {
try {
ECParameterSpec parameterSpec = ECNamedCurveTable
.getParameterSpec(algorithmEmployed.getString());
ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
byte[] x = ecPoint.getXCoord().getEncoded();
byte[] y = ecPoint.getYCoord().getEncoded();
if (y.length > STANDARD_KEY_LENGTH) {
y = Arrays.copyOfRange(y, 1, y.length);
}
return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
} catch (Exception e) {
throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
}
}
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
for (String key : keys) {
final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(id, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
virtualFiles.add(virtualFile);
return true;
}, GlobalSearchScope.allScope(getProject()));
if(notCondition && virtualFiles.size() > 0) {
fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
} else if(!notCondition && virtualFiles.size() == 0) {
fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
}
}
}
public static @NotNull SentryEnvelopeItem fromSession(
final @NotNull ISerializer serializer, final @NotNull Session session) throws IOException {
Objects.requireNonNull(serializer, "ISerializer is required.");
Objects.requireNonNull(session, "Session is required.");
final CachedItem cachedItem =
new CachedItem(
() -> {
try (final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) {
serializer.serialize(session, writer);
return stream.toByteArray();
}
});
SentryEnvelopeItemHeader itemHeader =
new SentryEnvelopeItemHeader(
SentryItemType.Session, () -> cachedItem.getBytes().length, "application/json", null);
return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes());
}
@Override
public HttpResponse process(@NotNull HttpRequests.Request request) throws IOException {
if (StringUtils.isNoneBlank(httpRequest.getBody())) {
request.write(httpRequest.getBody());
}
URLConnection urlConnection = request.getConnection();
if (!(urlConnection instanceof HttpURLConnection)) {
httpResponse.setStatusCode(-1);
return httpResponse;
} else {
httpResponse.setStatusCode(((HttpURLConnection) urlConnection).getResponseCode());
}
try {
httpResponse.setBody(request.readString());
} catch (IOException ignore) {
}
return httpResponse;
}
/**
* Extract serialized transaction from a signable transaction
* <p>
* Signable signature structure:
* <p>
* chainId (64 characters) + serialized transaction + 32 bytes of 0
*
* @param eosTransaction - the input signable transaction
* @return - extracted serialized transaction from the input signable transaction
* @throws EOSFormatterError if input is invalid
*/
public static String extractSerializedTransactionFromSignable(@NotNull String eosTransaction)
throws EOSFormatterError {
if (eosTransaction.isEmpty()) {
throw new EOSFormatterError(ErrorConstants.EMPTY_INPUT_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE);
}
if (eosTransaction.length() <= MINIMUM_SIGNABLE_TRANSACTION_LENGTH) {
throw new EOSFormatterError(String.format(ErrorConstants.INVALID_INPUT_SIGNABLE_TRANS_LENGTH_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE, MINIMUM_SIGNABLE_TRANSACTION_LENGTH));
}
if (!eosTransaction.endsWith(Hex.toHexString(new byte[32]))) {
throw new EOSFormatterError(ErrorConstants.INVALID_INPUT_SIGNABLE_TRANS_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE);
}
try {
String cutChainId = eosTransaction.substring(CHAIN_ID_LENGTH);
return cutChainId.substring(0, cutChainId.length() - Hex.toHexString(new byte[32]).length());
} catch (Exception ex) {
throw new EOSFormatterError(ErrorConstants.EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE_ERROR, ex);
}
}
/**
* Upload string.
*
* @param ossClient the ossClient client
* @param instream the instream
* @param fileName the file name
* @return the string
*/
public String upload(@NotNull OSS ossClient,
@NotNull InputStream instream,
@NotNull String fileName) {
try {
// 创建上传 Object 的 Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(ImageUtils.getImageType(fileName));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
return getUrl(ossClient, filedir, fileName);
} catch (IOException | OSSException | ClientException e) {
log.trace("", e);
}
return "";
}
private static boolean isInsideTestDirectory(final @NotNull PsiJavaFile file) {
Optional<PsiDirectory> optionalDirectory = getDirectoryWithRootPackageFor(file);
if (!optionalDirectory.isPresent()) {
return false;
}
PsiDirectory directory = optionalDirectory.get();
while (directory != null) {
String dirName = directory.getName().toLowerCase();
if (dirName.equals("test") || dirName.equals("tests")) {
return true;
}
directory = directory.getParentDirectory();
}
return false;
}
/**
* 处理被选中的单选框
*
* @param group the group
* @param button the button
*/
private void addChangeTagRadioButton(@NotNull ButtonGroup group, JRadioButton button) {
group.add(button);
// 构造一个监听器,响应checkBox事件
ActionListener actionListener = e -> {
Object sourceObject = e.getSource();
if (sourceObject instanceof JRadioButton) {
JRadioButton sourceButton = (JRadioButton) sourceObject;
if (ImageMarkEnum.CUSTOM.text.equals(sourceButton.getText())) {
customHtmlTypeTextField.setEnabled(true);
} else {
customHtmlTypeTextField.setEnabled(false);
}
}
};
button.addActionListener(actionListener);
}
public TradingParameters(@NotNull final String ssoToken,
@NotNull final String[] tickers,
@NotNull final CandleInterval[] candleIntervals,
final boolean sandboxMode) {
this.ssoToken = ssoToken;
this.tickers = tickers;
this.candleIntervals = candleIntervals;
this.sandboxMode = sandboxMode;
}
public Deobfuscator(JadxArgs args, @NotNull List<DexNode> dexNodes, Path deobfMapFile) {
this.args = args;
this.dexNodes = dexNodes;
this.minLength = args.getDeobfuscationMinLength();
this.maxLength = args.getDeobfuscationMaxLength();
this.useSourceNameAsAlias = args.isUseSourceNameAsClassAlias();
this.deobfPresets = new DeobfPresets(this, deobfMapFile);
}
public static SectionAttribute parse(@NotNull String rawData) {
logger.debug("parsing raw catalog section data into SectionAttribute...");
rawData = rawData.trim();
if (rawData.equals("")) {
logger.warn("Got bad data: empty string");
return null; // the course doesn't exist
}
Document doc = Jsoup.parse(rawData);
Element failed = doc.selectFirst("div.alert.alert-info");
if (failed != null) {
logger.warn("Got bad data: " + failed.text());
return null; // the course doesn't exist
}
Elements elements = doc.select("a");
String link = null;
for (Element element : elements) {
String el = element.attr("href");
if (el.contains("mapBuilding")) {
link = el;
}
}
doc.select("a").unwrap();
doc.select("i").unwrap();
doc.select("b").unwrap();
Element outerDataSection = doc.selectFirst("body > section.main");
Element innerDataSection = outerDataSection.selectFirst("> section");
Element courseNameDiv = innerDataSection.selectFirst("> div.primary-head");
String courseName = courseNameDiv.text();
Elements dataDivs =
innerDataSection.select("> div.section-content.clearfix");
Map<String, String> secData = parseSectionAttributes(dataDivs);
return parsingElements(secData, courseName, link);
}
@Override
public void assertExtraction(@NotNull final Extraction extraction) {
Assertions.assertEquals(1, extraction.getCodeLocations().size());
NameVersionGraphAssert graphAssert = new NameVersionGraphAssert(Forge.ANACONDA, extraction.getCodeLocations().get(0).getDependencyGraph());
graphAssert.hasRootSize(2);
graphAssert.hasRootDependency("mkl", "2017.0.3-0-osx-64");
graphAssert.hasRootDependency("numpy", "1.13.1-py36_0-osx-64");
}
@NotNull
@Override
public void onDisconnect(DisconnectRequest disconnectRequest, Map<?, ?> headers) {
String token = (String) headers.get("authorization");
try {
String userId = database.getUserId(token);
database.setHomegraph(userId, false);
} catch (Exception e) {
LOGGER.error("failed to get user id for token: %d", token);
}
}
@NotNull
@Override
public ByteBuf encodingParams(@Nullable Object[] args, RSocketMimeType encodingType) {
try {
ObjectEncodingHandler handler = handlerMap.get(encodingType);
return handler.encodingParams(args);
} catch (Exception e) {
log.error(RsocketErrorCode.message("RST-700500", "Object[]", encodingType.getName()), e);
return EMPTY_BUFFER;
}
}
/**
* Resolve the given parameter to find possible psalm docs recursively
*
* $foo->foo([])
*
* TODO: method search in recursion
*/
@NotNull
public static Collection<ParameterArrayType> getTypesForParameter(@NotNull PsiElement psiElement) {
PsiElement parent = psiElement.getParent();
if (parent instanceof ParameterList) {
PsiElement functionReference = parent.getParent();
if (functionReference instanceof FunctionReference) {
PsiElement resolve = ((FunctionReference) functionReference).resolve();
if (resolve instanceof Function) {
Parameter[] functionParameters = ((Function) resolve).getParameters();
int currentParameterIndex = PhpElementsUtil.getCurrentParameterIndex((ParameterList) parent, psiElement);
if (currentParameterIndex >= 0 && functionParameters.length - 1 >= currentParameterIndex) {
String name = functionParameters[currentParameterIndex].getName();
PhpDocComment docComment = ((Function) resolve).getDocComment();
if (docComment != null) {
return GenericsUtil.getParameterArrayTypes(docComment, name);
}
}
}
}
}
return Collections.emptyList();
}
public EnvelopeSender(
final @NotNull IHub hub,
final @NotNull IEnvelopeReader envelopeReader,
final @NotNull ISerializer serializer,
final @NotNull ILogger logger,
final long flushTimeoutMillis) {
super(logger, flushTimeoutMillis);
this.hub = Objects.requireNonNull(hub, "Hub is required.");
this.envelopeReader = Objects.requireNonNull(envelopeReader, "Envelope reader is required.");
this.serializer = Objects.requireNonNull(serializer, "Serializer is required.");
this.logger = Objects.requireNonNull(logger, "Logger is required.");
}
@NotNull
private AccountDetailsTO getDetails() {
AccountDetailsTO details = new AccountDetailsTO();
details.setIban(IBAN);
details.setAccountStatus(ENABLED);
details.setAccountType(CASH);
details.setBalances(Collections.singletonList(new AccountBalanceTO(new AmountTO(CURRENCY, BigDecimal.TEN), INTERIM_AVAILABLE, null, null, null, null)));
details.setCurrency(CURRENCY);
return details;
}
@SuppressWarnings("deprecation")
EnvelopeFileObserver(
String path,
IEnvelopeSender envelopeSender,
@NotNull ILogger logger,
final long flushTimeoutMillis) {
super(path);
this.rootPath = Objects.requireNonNull(path, "File path is required.");
this.envelopeSender = Objects.requireNonNull(envelopeSender, "Envelope sender is required.");
this.logger = Objects.requireNonNull(logger, "Logger is required.");
this.flushTimeoutMillis = flushTimeoutMillis;
}
@NotNull
@Override
public String onOffPairId() {
return new StringBuilder("Candle(")
.append(figi)
.append(",")
.append(interval.name())
.append(")")
.toString();
}
/**
* Создаёт экземпляр со всеми его компонентами.
*
* Выбрасывает {@code IllegalArgumentException} при указании лотов менее, чем 1.
*
* @param lots Количество лотов.
* @param operation Тип операции.
* @param price Желаемая цена.
*/
public LimitOrder(final int lots,
@NotNull final Operation operation,
@NotNull final BigDecimal price) {
if (lots < 1) {
throw new IllegalArgumentException("Количество лотов должно быть положительным.");
}
this.lots = lots;
this.operation = operation;
this.price = price;
}
@NotNull
@Override
public Long parse(@NotNull final String value) throws ValueParseException {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw new ValueParseException(value, "long", e);
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
final Project project = event.getProject();
if (project != null) {
MoveToOtherOssSettingsDialog dialog = showDialog();
if (dialog == null) {
return;
}
String domain = dialog.getDomain().getText().trim();
if (StringUtils.isBlank(domain)) {
return;
}
if (!OssState.getStatus(dialog.getCloudComboBox().getSelectedIndex()- 1)) {
return;
}
int cloudIndex = dialog.getCloudComboBox().getSelectedIndex() - 1;
CloudEnum cloudEnum = OssState.getCloudType(cloudIndex);
EventData data = new EventData()
.setActionEvent(event)
.setProject(project)
.setClient(ClientUtils.getClient(cloudEnum))
// client 有可能为 null, 使用 cloudEnum 安全点
.setClientName(cloudEnum.title);
// http://www.jetbrains.org/intellij/sdk/docs/basics/persisting_state_of_components.html
PropertiesComponent propComp = PropertiesComponent.getInstance();
// 过滤掉配置用户输入后的其他标签
propComp.setValue(MarkdownFileFilter.FILTER_KEY, domain.equals(MOVE_ALL) ? "" : domain);
new ActionTask(project,
MikBundle.message("mik.action.move.process", cloudEnum.title),
ActionManager.buildMoveImageChain(data)).queue();
}
}
/**
* Check if an itemType is retry after or not
*
* @param itemType the itemType (eg event, session, etc...)
* @return true if retry after or false otherwise
*/
@SuppressWarnings("JdkObsolete")
@Override
public boolean isRetryAfter(final @NotNull String itemType) {
final DataCategory dataCategory = getCategoryFromItemType(itemType);
final Date currentDate = new Date(currentDateProvider.getCurrentTimeMillis());
// check all categories
final Date dateAllCategories = sentryRetryAfterLimit.get(DataCategory.All);
if (dateAllCategories != null) {
if (!currentDate.after(dateAllCategories)) {
return true;
}
}
// Unknown should not be rate limited
if (DataCategory.Unknown.equals(dataCategory)) {
return false;
}
// check for specific dataCategory
final Date dateCategory = sentryRetryAfterLimit.get(dataCategory);
if (dateCategory != null) {
return !currentDate.after(dateCategory);
}
return false;
}
/**
* Creates a signature for PhpType implementation which must be resolved inside 'getBySignature'
*
* eg. foo(MyClass::class) => "#F\\foo|#K#C\\Foo.class"
*
* foo($this->foo), foo('foobar')
*/
@Nullable
public static String getReferenceSignatureByFirstParameter(@NotNull FunctionReference functionReference, char trimKey) {
String refSignature = functionReference.getSignature();
if(StringUtil.isEmpty(refSignature)) {
return null;
}
PsiElement[] parameters = functionReference.getParameters();
if(parameters.length == 0) {
return null;
}
PsiElement parameter = parameters[0];
// we already have a string value
if ((parameter instanceof StringLiteralExpression)) {
String param = ((StringLiteralExpression)parameter).getContents();
if (StringUtil.isNotEmpty(param)) {
return refSignature + trimKey + param;
}
return null;
}
// whitelist here; we can also provide some more but think of performance
// Service::NAME, $this->name and Entity::CLASS;
if ((parameter instanceof ClassConstantReference || parameter instanceof FieldReference)) {
String signature = ((PhpReference) parameter).getSignature();
if (StringUtil.isNotEmpty(signature)) {
return refSignature + trimKey + signature;
}
}
return null;
}
LifecycleWatcher(
final @NotNull IHub hub,
final long sessionIntervalMillis,
final boolean enableSessionTracking,
final boolean enableAppLifecycleBreadcrumbs) {
this(
hub,
sessionIntervalMillis,
enableSessionTracking,
enableAppLifecycleBreadcrumbs,
CurrentDateProvider.getInstance());
}
public RootChecker(
final @NotNull Context context,
final @NotNull IBuildInfoProvider buildInfoProvider,
final @NotNull ILogger logger) {
this(
context,
buildInfoProvider,
logger,
new String[] {
"/system/app/Superuser.apk",
"/sbin/su",
"/system/bin/su",
"/system/xbin/su",
"/data/local/xbin/su",
"/data/local/bin/su",
"/system/sd/xbin/su",
"/system/bin/failsafe/su",
"/data/local/su",
"/su/bin/su",
"/su/bin",
"/system/xbin/daemonsu"
},
new String[] {
"com.devadvance.rootcloak",
"com.devadvance.rootcloakplus",
"com.koushikdutta.superuser",
"com.thirdparty.superuser",
"eu.chainfire.supersu", // SuperSU
"com.noshufou.android.su" // superuser
},
Runtime.getRuntime());
}
@Override
public boolean onMove(@NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder
, @NotNull RecyclerView.ViewHolder target) {
if(dragFrom == -1) {
dragFrom = viewHolder.getAdapterPosition();
}
dragTo = target.getAdapterPosition();
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Nullable
private static String getRetentionPolicyForQualifiedName(@NotNull String retentionPolicy) {
// Values are same for Kotlin and Java
for (RetentionPolicy policy : RetentionPolicy.values()) {
final String javaQualifiedName = CLASS_JAVA_RETENTION_POLICY + "." + policy.name();
final String kotlinQualifiedName = CLASS_KOTLIN_RETENTION_POLICY + "." + policy.name();
if (javaQualifiedName.equals(retentionPolicy)
|| kotlinQualifiedName.equals(retentionPolicy)) {
return policy.name();
}
}
return null;
}
@NotNull
@Override
public Flux<DataBuffer> encode(@NotNull Publisher<?> inputStream, @NotNull DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
return Flux.from(inputStream)
.handle((obj, sink) -> {
try {
sink.next(encode(obj, bufferFactory));
} catch (Exception e) {
sink.error(e);
}
});
}
public void assertLineMarkerIsEmpty(@NotNull PsiElement psiElement) {
final List<PsiElement> elements = collectPsiElementsRecursive(psiElement);
for (LineMarkerProvider lineMarkerProvider : LineMarkerProviders.INSTANCE.allForLanguage(psiElement.getLanguage())) {
Collection<LineMarkerInfo> lineMarkerInfos = new ArrayList<>();
lineMarkerProvider.collectSlowLineMarkers(elements, lineMarkerInfos);
if(lineMarkerInfos.size() > 0) {
fail(String.format("Fail that line marker is empty because it matches '%s'", lineMarkerProvider.getClass()));
}
}
}