code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* Copyright 2012 brands4friends, Private Sale 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.
*/
package de.brands4friends.daleq.core;
@TableDef("FOO")
public final class ExampleTable {
public static final FieldDef PROP_A = Daleq.fd(DataType.INTEGER);
public static final FieldDef PROP_B = Daleq.fd(DataType.INTEGER);
}
|
brands4friends/daleq
|
daleq-core/src/test/java/de/brands4friends/daleq/core/ExampleTable.java
|
Java
|
apache-2.0
| 850
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_07.html">Class Test_AbaRouteValidator_07</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_14265_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07.html?line=43624#src-43624" >testAbaNumberCheck_14265_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:37:06
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_14265_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=30955#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07_testAbaNumberCheck_14265_good_nvv.html
|
HTML
|
apache-2.0
| 9,181
|
/* ====================================================================
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.poi.ss.formula.functions;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
/**
* @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
*/
public final class TestDate extends TestCase {
private HSSFCell cell11;
private HSSFFormulaEvaluator evaluator;
@Override
public void setUp() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
cell11 = sheet.createRow(0).createCell(0);
cell11.setCellType(CellType.FORMULA);
evaluator = new HSSFFormulaEvaluator(wb);
}
/**
* Test disabled pending a fix in the formula evaluator
* TODO - create MissingArgEval and modify the formula evaluator to handle this
*/
public void DISABLEDtestSomeArgumentsMissing() {
confirm("DATE(, 1, 0)", 0.0);
confirm("DATE(, 1, 1)", 1.0);
}
public void testValid() {
confirm("DATE(1900, 1, 1)", 1);
confirm("DATE(1900, 1, 32)", 32);
confirm("DATE(1900, 222, 1)", 6727);
confirm("DATE(1900, 2, 0)", 31);
confirm("DATE(2000, 1, 222)", 36747.00);
confirm("DATE(2007, 1, 1)", 39083);
}
public void testBugDate() {
confirm("DATE(1900, 2, 29)", 60);
confirm("DATE(1900, 2, 30)", 61);
confirm("DATE(1900, 1, 222)", 222);
confirm("DATE(1900, 1, 2222)", 2222);
confirm("DATE(1900, 1, 22222)", 22222);
}
public void testPartYears() {
confirm("DATE(4, 1, 1)", 1462.00);
confirm("DATE(14, 1, 1)", 5115.00);
confirm("DATE(104, 1, 1)", 37987.00);
confirm("DATE(1004, 1, 1)", 366705.00);
}
private void confirm(String formulaText, double expectedResult) {
cell11.setCellFormula(formulaText);
evaluator.clearAllCachedResultValues();
CellValue cv = evaluator.evaluate(cell11);
if (cv.getCellTypeEnum() != CellType.NUMERIC) {
throw new AssertionFailedError("Wrong result type: " + cv.formatAsString());
}
double actualValue = cv.getNumberValue();
assertEquals(expectedResult, actualValue, 0);
}
}
|
lvweiwolf/poi-3.16
|
src/testcases/org/apache/poi/ss/formula/functions/TestDate.java
|
Java
|
apache-2.0
| 3,405
|
/*
* 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/cloud/documentai/v1beta1/document_understanding.proto
package com.google.cloud.documentai.v1beta1;
/**
*
*
* <pre>
* The desired input location and metadata.
* </pre>
*
* Protobuf type {@code google.cloud.documentai.v1beta1.InputConfig}
*/
public final class InputConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.documentai.v1beta1.InputConfig)
InputConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use InputConfig.newBuilder() to construct.
private InputConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InputConfig() {
mimeType_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new InputConfig();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private InputConfig(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.documentai.v1beta1.GcsSource.Builder subBuilder = null;
if (sourceCase_ == 1) {
subBuilder = ((com.google.cloud.documentai.v1beta1.GcsSource) source_).toBuilder();
}
source_ =
input.readMessage(
com.google.cloud.documentai.v1beta1.GcsSource.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.cloud.documentai.v1beta1.GcsSource) source_);
source_ = subBuilder.buildPartial();
}
sourceCase_ = 1;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
mimeType_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.documentai.v1beta1.DocumentAiProto
.internal_static_google_cloud_documentai_v1beta1_InputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.documentai.v1beta1.DocumentAiProto
.internal_static_google_cloud_documentai_v1beta1_InputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.documentai.v1beta1.InputConfig.class,
com.google.cloud.documentai.v1beta1.InputConfig.Builder.class);
}
private int sourceCase_ = 0;
private java.lang.Object source_;
public enum SourceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
GCS_SOURCE(1),
SOURCE_NOT_SET(0);
private final int value;
private SourceCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SourceCase valueOf(int value) {
return forNumber(value);
}
public static SourceCase forNumber(int value) {
switch (value) {
case 1:
return GCS_SOURCE;
case 0:
return SOURCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public static final int GCS_SOURCE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.documentai.v1beta1.GcsSource getGcsSource() {
if (sourceCase_ == 1) {
return (com.google.cloud.documentai.v1beta1.GcsSource) source_;
}
return com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.documentai.v1beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if (sourceCase_ == 1) {
return (com.google.cloud.documentai.v1beta1.GcsSource) source_;
}
return com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
}
public static final int MIME_TYPE_FIELD_NUMBER = 2;
private volatile java.lang.Object mimeType_;
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The mimeType.
*/
@java.lang.Override
public java.lang.String getMimeType() {
java.lang.Object ref = mimeType_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
mimeType_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for mimeType.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMimeTypeBytes() {
java.lang.Object ref = mimeType_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
mimeType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (sourceCase_ == 1) {
output.writeMessage(1, (com.google.cloud.documentai.v1beta1.GcsSource) source_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(mimeType_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, mimeType_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sourceCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.documentai.v1beta1.GcsSource) source_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(mimeType_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, mimeType_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.documentai.v1beta1.InputConfig)) {
return super.equals(obj);
}
com.google.cloud.documentai.v1beta1.InputConfig other =
(com.google.cloud.documentai.v1beta1.InputConfig) obj;
if (!getMimeType().equals(other.getMimeType())) return false;
if (!getSourceCase().equals(other.getSourceCase())) return false;
switch (sourceCase_) {
case 1:
if (!getGcsSource().equals(other.getGcsSource())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MIME_TYPE_FIELD_NUMBER;
hash = (53 * hash) + getMimeType().hashCode();
switch (sourceCase_) {
case 1:
hash = (37 * hash) + GCS_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGcsSource().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.documentai.v1beta1.InputConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.documentai.v1beta1.InputConfig prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The desired input location and metadata.
* </pre>
*
* Protobuf type {@code google.cloud.documentai.v1beta1.InputConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.documentai.v1beta1.InputConfig)
com.google.cloud.documentai.v1beta1.InputConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.documentai.v1beta1.DocumentAiProto
.internal_static_google_cloud_documentai_v1beta1_InputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.documentai.v1beta1.DocumentAiProto
.internal_static_google_cloud_documentai_v1beta1_InputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.documentai.v1beta1.InputConfig.class,
com.google.cloud.documentai.v1beta1.InputConfig.Builder.class);
}
// Construct using com.google.cloud.documentai.v1beta1.InputConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
mimeType_ = "";
sourceCase_ = 0;
source_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.documentai.v1beta1.DocumentAiProto
.internal_static_google_cloud_documentai_v1beta1_InputConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.documentai.v1beta1.InputConfig getDefaultInstanceForType() {
return com.google.cloud.documentai.v1beta1.InputConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.documentai.v1beta1.InputConfig build() {
com.google.cloud.documentai.v1beta1.InputConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.documentai.v1beta1.InputConfig buildPartial() {
com.google.cloud.documentai.v1beta1.InputConfig result =
new com.google.cloud.documentai.v1beta1.InputConfig(this);
if (sourceCase_ == 1) {
if (gcsSourceBuilder_ == null) {
result.source_ = source_;
} else {
result.source_ = gcsSourceBuilder_.build();
}
}
result.mimeType_ = mimeType_;
result.sourceCase_ = sourceCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.documentai.v1beta1.InputConfig) {
return mergeFrom((com.google.cloud.documentai.v1beta1.InputConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.documentai.v1beta1.InputConfig other) {
if (other == com.google.cloud.documentai.v1beta1.InputConfig.getDefaultInstance())
return this;
if (!other.getMimeType().isEmpty()) {
mimeType_ = other.mimeType_;
onChanged();
}
switch (other.getSourceCase()) {
case GCS_SOURCE:
{
mergeGcsSource(other.getGcsSource());
break;
}
case SOURCE_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.documentai.v1beta1.InputConfig parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.documentai.v1beta1.InputConfig) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int sourceCase_ = 0;
private java.lang.Object source_;
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public Builder clearSource() {
sourceCase_ = 0;
source_ = null;
onChanged();
return this;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.documentai.v1beta1.GcsSource,
com.google.cloud.documentai.v1beta1.GcsSource.Builder,
com.google.cloud.documentai.v1beta1.GcsSourceOrBuilder>
gcsSourceBuilder_;
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.documentai.v1beta1.GcsSource getGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
return (com.google.cloud.documentai.v1beta1.GcsSource) source_;
}
return com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
} else {
if (sourceCase_ == 1) {
return gcsSourceBuilder_.getMessage();
}
return com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(com.google.cloud.documentai.v1beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
} else {
gcsSourceBuilder_.setMessage(value);
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(
com.google.cloud.documentai.v1beta1.GcsSource.Builder builderForValue) {
if (gcsSourceBuilder_ == null) {
source_ = builderForValue.build();
onChanged();
} else {
gcsSourceBuilder_.setMessage(builderForValue.build());
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder mergeGcsSource(com.google.cloud.documentai.v1beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1
&& source_ != com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance()) {
source_ =
com.google.cloud.documentai.v1beta1.GcsSource.newBuilder(
(com.google.cloud.documentai.v1beta1.GcsSource) source_)
.mergeFrom(value)
.buildPartial();
} else {
source_ = value;
}
onChanged();
} else {
if (sourceCase_ == 1) {
gcsSourceBuilder_.mergeFrom(value);
}
gcsSourceBuilder_.setMessage(value);
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder clearGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
onChanged();
}
} else {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
}
gcsSourceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
public com.google.cloud.documentai.v1beta1.GcsSource.Builder getGcsSourceBuilder() {
return getGcsSourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.documentai.v1beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if ((sourceCase_ == 1) && (gcsSourceBuilder_ != null)) {
return gcsSourceBuilder_.getMessageOrBuilder();
} else {
if (sourceCase_ == 1) {
return (com.google.cloud.documentai.v1beta1.GcsSource) source_;
}
return com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* The Google Cloud Storage location to read the input from. This must be a
* single file.
* </pre>
*
* <code>.google.cloud.documentai.v1beta1.GcsSource gcs_source = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.documentai.v1beta1.GcsSource,
com.google.cloud.documentai.v1beta1.GcsSource.Builder,
com.google.cloud.documentai.v1beta1.GcsSourceOrBuilder>
getGcsSourceFieldBuilder() {
if (gcsSourceBuilder_ == null) {
if (!(sourceCase_ == 1)) {
source_ = com.google.cloud.documentai.v1beta1.GcsSource.getDefaultInstance();
}
gcsSourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.documentai.v1beta1.GcsSource,
com.google.cloud.documentai.v1beta1.GcsSource.Builder,
com.google.cloud.documentai.v1beta1.GcsSourceOrBuilder>(
(com.google.cloud.documentai.v1beta1.GcsSource) source_,
getParentForChildren(),
isClean());
source_ = null;
}
sourceCase_ = 1;
onChanged();
;
return gcsSourceBuilder_;
}
private java.lang.Object mimeType_ = "";
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The mimeType.
*/
public java.lang.String getMimeType() {
java.lang.Object ref = mimeType_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
mimeType_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for mimeType.
*/
public com.google.protobuf.ByteString getMimeTypeBytes() {
java.lang.Object ref = mimeType_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
mimeType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The mimeType to set.
* @return This builder for chaining.
*/
public Builder setMimeType(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
mimeType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearMimeType() {
mimeType_ = getDefaultInstance().getMimeType();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mimetype of the input. Current supported mimetypes are
* application/pdf, image/tiff, and image/gif.
* </pre>
*
* <code>string mime_type = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for mimeType to set.
* @return This builder for chaining.
*/
public Builder setMimeTypeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
mimeType_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.documentai.v1beta1.InputConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.documentai.v1beta1.InputConfig)
private static final com.google.cloud.documentai.v1beta1.InputConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.documentai.v1beta1.InputConfig();
}
public static com.google.cloud.documentai.v1beta1.InputConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InputConfig> PARSER =
new com.google.protobuf.AbstractParser<InputConfig>() {
@java.lang.Override
public InputConfig parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new InputConfig(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<InputConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InputConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.documentai.v1beta1.InputConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/java-document-ai
|
proto-google-cloud-document-ai-v1beta1/src/main/java/com/google/cloud/documentai/v1beta1/InputConfig.java
|
Java
|
apache-2.0
| 32,666
|
package publishers
import (
"database/sql"
"fmt"
"strings"
"github.com/bazelbuild/continuous-integration/metrics/metrics"
)
const columnTypeQueryPattern = "SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME IN ('%s');"
type CloudSqlGc struct {
conn *sql.DB
}
func CreateCloudSqlGc(conn *sql.DB) (*CloudSqlGc, error) {
// TODO(fweikert): prepare statements?
return &CloudSqlGc{conn}, nil
}
func (gc *CloudSqlGc) Run(metric metrics.GarbageCollectedMetric) (int64, error) {
handleError := func(err error) error {
return fmt.Errorf("Failed to run Cloud SQL GC for metric %s: %v", metric.Name(), err)
}
strategy, err := gc.selectStrategy(metric)
if err != nil {
return 0, handleError(err)
}
err = gc.ensureRequiredColumnsExist(metric, strategy)
if err != nil {
return 0, handleError(err)
}
rows, err := gc.executeStrategy(metric, strategy)
if err != nil {
return 0, handleError(err)
}
return rows, nil
}
var knownStrategies = map[metrics.MetricType]gcStrategy{metrics.TimeBasedMetric: timeBasedStrategy{}, metrics.BuildBasedMetric: buildBasedStrategy{}}
func (gc *CloudSqlGc) selectStrategy(metric metrics.GarbageCollectedMetric) (gcStrategy, error) {
if strategy, ok := knownStrategies[metric.Type()]; ok {
return strategy, nil
}
return nil, fmt.Errorf("Unknown GC strategy '%v'.", metric.Type())
}
func (gc *CloudSqlGc) ensureRequiredColumnsExist(metric metrics.GarbageCollectedMetric, strategy gcStrategy) error {
actualColumns, err := gc.readActualColumns(metric, strategy)
if err != nil {
return fmt.Errorf("Failed to retrieve actual columns from table %s: %v", metric.Name(), err)
}
errors := make([]string, 0)
for column, expectedType := range strategy.RequiredColumns() {
if actualType, ok := actualColumns[column]; ok {
if actualType != expectedType {
errors = append(errors, fmt.Sprintf("Column '%s' has type '%s', but should have '%s'", column, actualType, expectedType))
}
} else {
errors = append(errors, fmt.Sprintf("Missing column '%s'", column))
}
}
if len(errors) > 0 {
return fmt.Errorf("Table '%s' cannot be garbage collected since it does not have the required structure:\n\t%s", metric.Name(), strings.Join(errors, "\n\t"))
}
return nil
}
func (gc *CloudSqlGc) readActualColumns(metric metrics.GarbageCollectedMetric, strategy gcStrategy) (map[string]string, error) {
keys := getKeys(strategy.RequiredColumns())
query := fmt.Sprintf(columnTypeQueryPattern, metric.Name(), strings.Join(keys, "', '"))
rows, err := gc.conn.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
existingColumns := make(map[string]string)
var cname, ctype string
for rows.Next() {
err := rows.Scan(&cname, &ctype)
if err != nil {
return nil, err
}
existingColumns[cname] = ctype
}
return existingColumns, rows.Err()
}
func getKeys(dict map[string]string) []string {
keys := make([]string, 0)
for k := range dict {
keys = append(keys, k)
}
return keys
}
func (gc *CloudSqlGc) executeStrategy(metric metrics.GarbageCollectedMetric, strategy gcStrategy) (int64, error) {
query := strategy.DeletionQuery(metric.Name(), metric.RelevantDelta())
result, err := gc.conn.Exec(query)
if err != nil {
return 0, err
}
rows, err := result.RowsAffected()
if err != nil {
return 0, err
}
return rows, nil
}
type gcStrategy interface {
RequiredColumns() map[string]string
DeletionQuery(string, int) string
}
// Deletes all rows that were created more than X seconds ago
type timeBasedStrategy struct{}
func (timeBasedStrategy) RequiredColumns() map[string]string {
return map[string]string{"timestamp": "datetime"}
}
//delete t from worker_availability t join (select max(timestamp) as latest from worker_availability) m on timestampdiff(second, t.timestamp, latest) > 3600*24;
func (timeBasedStrategy) DeletionQuery(table string, rangeSeconds int) string {
return fmt.Sprintf("delete t from %[1]s t join (select max(timestamp) as latest from %[1]s) m on timestampdiff(second, t.timestamp, latest) > %d;", table, rangeSeconds)
}
// Deletes all rows that do no contain data for the X most recent builds for each pipeline
type buildBasedStrategy struct{}
func (buildBasedStrategy) RequiredColumns() map[string]string {
return map[string]string{"org": "varchar", "pipeline": "varchar", "build": "int"}
}
//select * from platform_usage t join (select org, pipeline, max(build) as latest from platform_usage group by org, pipeline) m on t.org = m.org and t.pipeline = m.pipeline and latest - t.build > 100;
func (buildBasedStrategy) DeletionQuery(table string, buildRange int) string {
return fmt.Sprintf("select * from %[1]s t join (select org, pipeline, max(build) as latest from %[1]s group by org, pipeline) m on t.org = m.org and t.pipeline = m.pipeline and latest - t.build > %d;", table, buildRange)
}
|
bazelbuild/continuous-integration
|
metrics/publishers/cloudsql_gc.go
|
GO
|
apache-2.0
| 4,882
|
#!/bin/bash
# set what models to train
export TRI2B_BMMI=true
export TRI3B=false
export TRI4_NNET2=false
export TRI4_NNET2_SMBR=false
export TRI5_NNET2_IVECTOR=true
export TRI5_NNET2_SMBR_IVECTOR=true
# EVERY_N utterance is used for training
# EVERY_N=3 -> we use one third of training data
export EVERY_N=1
export TEST_SETS="dev test"
export mfcc_config=./common/mfcc_8khz.conf
# Directories set up
export DATA_ROOT=/net/me/merkur2/vystadial/asr-mixer/cs-voip # expects subdirectories train + $TEST_SETS
export WORK=`pwd`/model_cs_voip
export EXP=$WORK/exp
export TGT_MODELS=exported/cs_voip
export TGT_MODELS2=exported2/cs_voip
# Specify paths to arpa models. Paths may not contain spaces.
# Specify build0 or build1 or build2, .. for building (zero|uni|bi)-gram LM.
# Note: The LM file name should not contain underscore "_"!
# Otherwise the results will be reported without the LM with underscore."
export LM_paths="build0 build2"
export LM_names="build0 build2"
# Use path to prebuilt dictionary or 'build' command in order to build dictionary
# export DICTIONARY="../xxx/dict"
export DICTIONARY="build"
# Borders for estimating LM model weight.
# LMW is tuned on development set and applied on test set.
export min_lmw=4
export max_lmw=15
# Number of states for phonem training
export pdf=1200
# Maximum number of Gaussians used for training
export gauss=19200
export train_mmi_boost=0.05
export mmi_beam=16.0
export mmi_lat_beam=10.0
export smbr_beam=16.0
export smbr_lat_beam=10.0
# --fake -> NO CMVN; empty -> CMVN (pykaldi decoders can not handle CMVN -> fake)
export fake="--fake"
export g2p="local/prepare_cs_transcription.sh"
# set paralelisation
# for standard training using using CPU
export train_cmd="queue.pl -V -l mem_free=2G,h_vmem=4G -p -50 -q '`qselect | sort | egrep -v 'pandora|hyperion|orion|andromeda|lucifer|cosmos' | tr '\n' ',' | sed s/\,$//`'"
export decode_cmd="queue.pl -V -l mem_free=2G,h_vmem=4G -p -50 -q '`qselect | sort | egrep -v 'pandora|hyperion|orion|andromeda|lucifer|cosmos' | tr '\n' ',' | sed s/\,$//`'"
export njobs=100
export njobs_mfcc=20
export njobs_dev_test=100
export num_jobs_nnet=3
# This is a command to run the code on a CUDA enabled machine at UFAL. We do not have CUDA machines at the cluster.
# You must run the training from a CUDA enabled manchine!
export gpu_cmd=run.pl
export gpu_nj=12
mkdir -p $WORK
|
UFAL-DSG/kams
|
kams/cs_voip.sh
|
Shell
|
apache-2.0
| 2,389
|
#!/usr/bin/env php
<?php
use Everyman\Neo4j\Transport,
Everyman\Neo4j\Client,
Everyman\Neo4j\Index\NodeIndex,
Everyman\Neo4j\Relationship,
Everyman\Neo4j\Node,
Everyman\Neo4j\Gremlin;
error_reporting(-1);
ini_set('display_errors', 1);
function loaderTestAutoloader($sClass)
{
$sLibPath = __DIR__.'/../lib/';
$sClassFile = str_replace('\\',DIRECTORY_SEPARATOR,$sClass).'.php';
$sClassPath = $sLibPath.$sClassFile;
if (file_exists($sClassPath)) {
require($sClassPath);
}
}
spl_autoload_register('loaderTestAutoloader');
$cmd = !empty($argv[1]) ? $argv[1] : null;
if (!$cmd) {
echo <<<HELP
Usage:
{$argv[0]}
Display usage instructions
{$argv[0]} init
Initialize the data. This only needs to be done once.
{$argv[0]} actors
Get a list of all actors in the database.
HELP;
exit(0);
}
$transport = new Transport();
$client = new Client($transport);
$actors = new NodeIndex($client, 'actors');
// Initialize the data
if ($cmd == 'init') {
$keanu = $client->makeNode()->setProperty('name', 'Keanu Reeves')->save();
$laurence = $client->makeNode()->setProperty('name', 'Laurence Fishburne')->save();
$jennifer = $client->makeNode()->setProperty('name', 'Jennifer Connelly')->save();
$kevin = $client->makeNode()->setProperty('name', 'Kevin Bacon')->save();
$actors->add($keanu, 'name', $keanu->getProperty('name'));
$actors->add($laurence, 'name', $laurence->getProperty('name'));
$actors->add($jennifer, 'name', $jennifer->getProperty('name'));
$actors->add($kevin, 'name', $kevin->getProperty('name'));
$matrix = $client->makeNode()->setProperty('title', 'The Matrix')->save();
$higherLearning = $client->makeNode()->setProperty('title', 'Higher Learning')->save();
$mysticRiver = $client->makeNode()->setProperty('title', 'Mystic River')->save();
$keanu->relateTo($matrix, 'IN')->save();
$laurence->relateTo($matrix, 'IN')->save();
$laurence->relateTo($higherLearning, 'IN')->save();
$jennifer->relateTo($higherLearning, 'IN')->save();
$laurence->relateTo($mysticRiver, 'IN')->save();
$kevin->relateTo($mysticRiver, 'IN')->save();
// Find all actors in a movie
} else if ($cmd == 'actors') {
$queryTemplate = "g.V.in(type).uniqueObject.sort{it.name}.toList()";
$params = array('type' => 'IN');
$query = new Gremlin\Query($client, $queryTemplate, $params);
$result = $query->getResultSet();
foreach ($result as $row) {
echo "* " . $row[0]->getProperty('name')."\n";
}
}
|
karthikbalu/Neo4jApp
|
htdocs 3/APIS/neo4jphp/examples/gremlin.php
|
PHP
|
apache-2.0
| 2,423
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Gitlab</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/serif.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match(/print-pdf/gi) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName('head')[0].appendChild(link);
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h2>Gitlab</h2>
<img width="20%" src="img/gitlab_logo.png"/>
<p>
guillermo{dot}guerrero{at}fr{dot}fcm{dot}travel
</p>
<p>
<small>June 5th, 2020</small>
</p>
</section>
<section>
<section>
<h2>What is CI (Continuous Integration)?</h2>
<p>
<img width="50%" src="img/continuous-integration.png"/>
</p>
</section>
<section>
<h2>What is CD?</h2>
<p>
<img width="100%" src="img/continuous-delivery-versus-continuous-deployment.png"/>
</p>
</section>
<section>
<h2>Examples:</h2>
<p>
- Continuous delivery:
<img width="100%" src="img/continuous_delivery.png"/>
</p>
<p>
- Continuous deployment:
<img width="100%" src="img/continuous_deployment.png"/>
</p>
</section>
</section>
<section>
<section>
<h2>Hi Gitlab</h2>
<p>
<img width="20%" src="img/gitlab_logo.png"/>
</p>
<p>
From:
</p>
<p>
<ul>
<li>Github</li>
<li>Codeship (CI)</li>
<li>Dockerhub</li>
</p>
</p>
</section>
<section>
<h2>gitlab-ci.yml</h2>
<pre style="font-size: 18px;">
image: "ruby:2.5"
before_script:
- apt-get update -qq && apt-get install -y -qq sqlite3 libsqlite3-dev nodejs
- ruby -v
- gem install bundler --no-document
- bundle install
rspec:
script:
- bundle exec rspec
rubocop:
script:
- bundle exec rubocop
</pre>
<ul>
<li><a href="https://gitlab.com/3mundi/hellofcm/-/jobs" target="_blank">https://gitlab.com/3mundi/hellofcm/-/jobs</a></li>
<li><a href="https://gitlab.com/3mundi/hellofcm/-/jobs/579150203" target="_blank">https://gitlab.com/3mundi/hellofcm/-/jobs/579150203</a></li>
</ul>
</section>
<section>
<h2>Tags</h2>
<ul>
<li>docker</li>
<li>fcm_build</li>
<li>fcm_deploy</li>
<li>test</li>
<li>feature_test</li>
<li>...</li>
</ul>
<pre>
...
rspec:
tags:
- docker
- ruby
- postgres
script:
- bundle exec rspec
</pre>
<ul>
<li><a href="https://gitlab.com/3mundi/hellofcm/-/jobs" target="_blank">https://gitlab.com/3mundi/hellofcm/-/jobs</a></li>
</ul>
</section>
<section>
<h2>Workflows/pipelines</h2>
<pre>
...
stages:
- linter
- test
- build
- deploy
rspec:
stage: test
script:
- bundle exec rspec
</pre>
<p>
<img width="60%" src="img/pipelines_status.png"/>
</p>
<ul>
<li><a href="https://gitlab.com/3mundi/hellofcm/pipelines" target="_blank">https://gitlab.com/3mundi/hellofcm/pipelines</a></li>
</ul>
</section>
<section>
<h2>Cache/Artifacts</h2>
<ul>
<li>Cache: job speed up</li>
<li>Artifact: results</li>
</ul>
<pre>
...
rspec:
cache:
paths:
- vendor/bundle/
artifacts:
when: always
paths:
- coverage/
- tmp/capybara/
script:
- bundle exec rspec
</pre>
<a href="https://gitlab.com/3mundi/hellofcm/-/jobs/579150199" target="_blank">https://gitlab.com/3mundi/hellofcm/-/jobs/579150199</a>
</section>
</section>
<section>
<section>
<h2>Gitlab runners</h2>
<img width="70%" src="img/runners_page.png" />
<a href="https://gitlab.com/3mundi/hellofcm/-/settings/ci_cd" target="_blank">https://gitlab.com/3mundi/hellofcm/-/settings/ci_cd</a>
</section>
<section>
<h2>Gitlab executors</h2>
<a href="https://docs.gitlab.com/runner/install/" target="_blank">https://docs.gitlab.com/runner/install</a>
<br /><br />
<ul>
<li>SSH</li>
<li>Shell</li>
<li>Parallels</li>
<li>VirtualBox</li>
<li>Docker</li>
<li>Docker Machine (auto-scaling)</li>
<li>Kubernetes</li>
</ul>
</section>
<section>
<h2>Docker executor</h2>
/etc/gitlab-runner/config.toml
<pre style="font-size: 15px;">
concurrent = 1
check_interval = 0
[[runners]]
name = "runner one"
url = "https://gitlab.com/"
token = "XXXXXXXXXXX"
executor = "docker"
[runners.docker]
tls_verify = false
image = "ruby:2.4.0"
privileged = false
disable_cache = false
volumes = ["/cache","/var/run/docker.sock:/var/run/docker.sock"]
shm_size = 0
[runners.cache]
Type = "s3"
Shared = true
[runners.cache.s3]
ServerAddress = "s3.amazonaws.com"
AccessKey = "XXXXXXXXXXXXX"
SecretKey = "XXXXXXXXXXXXX"
BucketName = "XXXXXXXXXXXXX"
BucketLocation = "eu-west-3"
Insecure = false
</pre>
<a href="https://gitlab.com/3mundi/hellofcm/-/settings/ci_cd" target="_blank">https://gitlab.com/3mundi/hellofcm/-/settings/ci_cd</a>
</section>
<section>
<h2>Kubernetes executor</h2>
<img width="100%" src="img/gitlab_kubernetes.png" />
</section>
<section>
<h2>Docker machine executor</h2>
<img width="60%" src="img/gitlab_dockermachine.png" />
</section>
<section>
<h2>Docker machine executor</h2>
<pre style="font-size: 11px">
concurrent = 3
check_interval = 0
[session_server]
session_timeout = 1800
[[runners]]
name = "runner-bastion"
url = "https://gitlab.com/"
token = "XXXXXXXXX"
executor = "docker+machine"
[runners.custom_build_dir]
[runners.docker]
tls_verify = false
image = "ruby:2.6"
privileged = false
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
volumes = ["/cache","/var/run/docker.sock:/var/run/docker.sock"]
shm_size = 0
[runners.machine]
IdleCount = 0 # The amount of idle machines we require for CI if build queue is empty
IdleTime = 600 # Each machine can be idle for up to 600 seconds, then destroyed
MachineName = "gitlab-runner-autoscale-%s" # Each machine will have a unique name ('%s' is required and generates a random number)
MachineDriver = "digitalocean" # Docker Machine is using the 'digitalocean' driver
MachineOptions = [
"digitalocean-image=coreos-stable", # The DigitalOcean system image to use by default
"digitalocean-ssh-user=core", # The default SSH user
"digitalocean-access-token=XXXXXXXX", # Access token from Step 7
"digitalocean-region=ams2", # The data center to spawn runners in
"digitalocean-size=2gb", # The size (and price category) of your spawned runners
"digitalocean-private-networking" # Enable private networking on runners
]
[runners.cache]
Type = "s3"
Shared = true
[runners.cache.s3]
ServerAddress = "s3.amazonaws.com"
AccessKey = "XXXXXXXXX"
SecretKey = "XXXXXXXXX"
BucketName = "XXXXXXXXX"
BucketLocation = "eu-west-3"
Insecure = false
</pre>
</section>
</section>
<section>
<h2>Questions?</h2>
<img src="img/final_slide.jpg"/>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{
src: 'lib/js/classList.js', condition: function () {
return !document.body.classList;
}
},
{
src: 'plugin/markdown/marked.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: 'plugin/markdown/markdown.js', condition: function () {
return !!document.querySelector('[data-markdown]');
}
},
{
src: 'plugin/highlight/highlight.js', async: true, callback: function () {
hljs.initHighlightingOnLoad();
}
},
{src: 'plugin/zoom-js/zoom.js', async: true},
{src: 'plugin/notes/notes.js', async: true}
]
});
</script>
</body>
</html>
|
ryanfox1985/slides
|
gitlab101/index.html
|
HTML
|
apache-2.0
| 10,697
|
<?php
function layoutImage( $sec = "ThemeLayout", $tag = FALSE ) {
$src = THEMEDIR . "/Layout/$sec.gif";
$img = sprintf( '<img alt="" src="%s" />', $src );
return $tag ? $img : $src;
}
function layoutImageStyle_Widgets() {
$colList = array(
"colextra_content" => "RotatorExtra",
"coldx_sidebar" => "Rightbar",
"coldx_sidebar_articolo" => "Rightbar",
"archive_widgets" => "Ticker",
"headline_widgets" => "HeadlineWidgets",
"articles_top_widgets" => "HeadlineWidgets",
"articles_bottom_widgets" => "ArtWidgets",
"articles_bottom_home_widgets" => "ArtWidgets",
"article_top_widgets" => "HeadlineWidgets",
"article_bottom_widgets" => "ArtWidgets",
"midline_widgets" => "MidWidgets",
"topAdvLots" => "Leaderboard",
"manchette_1" => "Manchette1",
"manchette_2" => "Manchette2",
"ticker" => "Ticker",
"midbox_1" => "Square1",
"midbox_2" => "Square2",
"endingcontent" => "FooterStats",
"endingpage" => "FooterStats",
"fotogallery" => "Fotogallery",
"vetrine" => "Vetrine"
);
$str = ".wp-admin .widgets-holder-wrap #%s .sidebar-description";
$img = " { background-image: url('%s'); }\n";
echo "<style type=\"text/css\">\n";
foreach( array_keys( $colList ) as $i => $k ) {
if( $i ) echo ",\n";
printf( $str, $k );
}
echo " {\n"
." border-radius: 4px;\n"
." padding: 187px 8px 0 8px;\n"
." width: 234px;\n"
." background-color: #CCC;\n"
." background-repeat: no-repeat;\n"
." text-shadow: #DEDEDE 1px 1px 1px;\n"
." font-weight: bold;\n"
."}\n";
foreach( $colList as $k => $v ) {
printf( $str, $k );
printf( $img, layoutImage( $v ) );
}
echo "</style>\n";
}
function layoutImageStyle() {
$page = basename( $_SERVER["REQUEST_URI"] );
if( $page == "widgets.php" ) layoutImageStyle_Widgets();
}
add_action( 'admin_head', 'layoutImageStyle' );
|
iropicci/wpthemeqnnuhp
|
QN_NuHP/admin_layout_style.php
|
PHP
|
apache-2.0
| 1,814
|
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// SsdataDataserviceRiskAudioSetModel Data Structure.
/// </summary>
[Serializable]
public class SsdataDataserviceRiskAudioSetModel : AopObject
{
/// <summary>
/// 关键词创建人,也即使用者
/// </summary>
[XmlElement("creator")]
public string Creator { get; set; }
/// <summary>
/// 要删除的关键词id
/// </summary>
[XmlArray("id_list")]
[XmlArrayItem("string")]
public List<string> IdList { get; set; }
/// <summary>
/// 新增或查询的关键词。新增时,可以传多个用以批量新增;查询时候,可以不传或只传一个。
/// </summary>
[XmlArray("keyword_list")]
[XmlArrayItem("string")]
public List<string> KeywordList { get; set; }
/// <summary>
/// 修改人,一般的修改指的是删除
/// </summary>
[XmlElement("modifier")]
public string Modifier { get; set; }
/// <summary>
/// add 表示新增;delete 表示删除;query 表示查询;
/// </summary>
[XmlElement("operate_type")]
public string OperateType { get; set; }
/// <summary>
/// 页数
/// </summary>
[XmlElement("page_num")]
public string PageNum { get; set; }
/// <summary>
/// 一页展示数量
/// </summary>
[XmlElement("page_size")]
public string PageSize { get; set; }
/// <summary>
/// 关键词风险类型,批量增加时候,该批关键词为同一风险类型。1-涉政,2-涉黄
/// </summary>
[XmlElement("risk_type")]
public string RiskType { get; set; }
}
}
|
329277920/Snail
|
Snail.Pay.Ali.Sdk/Domain/SsdataDataserviceRiskAudioSetModel.cs
|
C#
|
apache-2.0
| 1,893
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Harmony Class Library Porting: modules/portlib/src/main/native/port/windows/hytty.c File Reference</title>
<link href="hydoxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.4 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul>
</div>
<h1>modules/portlib/src/main/native/port/windows/hytty.c File Reference</h1><hr><a name="_details"></a><h2>Detailed Description</h2>
TTY output.
<p>
All VM output goes to stderr by default. These routines provide the helpers for such output.
<p>
<code>#include <windows.h></code><br>
<code>#include <stdio.h></code><br>
<code>#include "<a class="el" href="hyport_8h.html">hyport.h</a>"</code><br>
<code>#include "portpriv.h"</code><br>
<code>#include "hyportpg.h"</code><br>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">I_32 VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#ce3c3c3112269ee72a649df67bd5fed4">hytty_startup</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">PortLibrary startup. <a href="#ce3c3c3112269ee72a649df67bd5fed4"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#ce79d20d24d40aadce1669ad49474561">hytty_shutdown</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">PortLibrary shutdown. <a href="#ce79d20d24d40aadce1669ad49474561"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#ebb391dcc67d2644a7514e09db35d27c">hytty_printf</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary, const char *format,...)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Write characters to stderr. <a href="#ebb391dcc67d2644a7514e09db35d27c"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">IDATA VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#5bf800de1c99ab8cd410ff7ab097d2dd">hytty_get_chars</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary, char *s, UDATA length)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Read characters from stdin into buffer. <a href="#5bf800de1c99ab8cd410ff7ab097d2dd"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#d300be2bf7ecabeeabf5750eb52d42c5">hytty_err_printf</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary, const char *format,...)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Output message to stderr. <a href="#d300be2bf7ecabeeabf5750eb52d42c5"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">IDATA VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#e6316099ec08b8c816e0581fe6a7f333">hytty_available</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Determine the number of characters remaining to be read from stdin. <a href="#e6316099ec08b8c816e0581fe6a7f333"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#018634a7367405573c2480879176ddc4">hytty_vprintf</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary, const char *format, va_list args)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Output message to stderr. <a href="#018634a7367405573c2480879176ddc4"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void VMCALL </td><td class="memItemRight" valign="bottom"><a class="el" href="hytty_8c.html#5ac16be63abb4fa67ab9fcaf4a65b061">hytty_err_vprintf</a> (struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> *portLibrary, const char *format, va_list args)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Output message to stderr. <a href="#5ac16be63abb4fa67ab9fcaf4a65b061"></a><br></td></tr>
</table>
<hr><h2>Function Documentation</h2>
<a class="anchor" name="e6316099ec08b8c816e0581fe6a7f333"></a><!-- doxytag: member="hytty.c::hytty_available" ref="e6316099ec08b8c816e0581fe6a7f333" args="(struct HyPortLibrary *portLibrary)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">IDATA VMCALL hytty_available </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em> </td>
<td> ) </td>
<td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Determine the number of characters remaining to be read from stdin.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library.</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>number of characters remaining to be read. </dd></dl>
</div>
</div><p>
<a class="anchor" name="d300be2bf7ecabeeabf5750eb52d42c5"></a><!-- doxytag: member="hytty.c::hytty_err_printf" ref="d300be2bf7ecabeeabf5750eb52d42c5" args="(struct HyPortLibrary *portLibrary, const char *format,...)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void VMCALL hytty_err_printf </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"> <em>...</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Output message to stderr.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>format</em> </td><td>The format String. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>...</em> </td><td>argument list.</td></tr>
</table>
</dl>
<dl compact><dt><b><a class="el" href="deprecated.html#_deprecated000003">Deprecated:</a></b></dt><dd>All output goes to stderr, use hytty_printf() </dd></dl>
</div>
</div><p>
<a class="anchor" name="5ac16be63abb4fa67ab9fcaf4a65b061"></a><!-- doxytag: member="hytty.c::hytty_err_vprintf" ref="5ac16be63abb4fa67ab9fcaf4a65b061" args="(struct HyPortLibrary *portLibrary, const char *format, va_list args)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void VMCALL hytty_err_vprintf </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">va_list </td>
<td class="paramname"> <em>args</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Output message to stderr.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>format</em> </td><td>The format String. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>args</em> </td><td>Variable argument list.</td></tr>
</table>
</dl>
<dl compact><dt><b><a class="el" href="deprecated.html#_deprecated000004">Deprecated:</a></b></dt><dd>All output goes to stderr, use hytty_vprintf() </dd></dl>
</div>
</div><p>
<a class="anchor" name="5bf800de1c99ab8cd410ff7ab097d2dd"></a><!-- doxytag: member="hytty.c::hytty_get_chars" ref="5bf800de1c99ab8cd410ff7ab097d2dd" args="(struct HyPortLibrary *portLibrary, char *s, UDATA length)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">IDATA VMCALL hytty_get_chars </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">char * </td>
<td class="paramname"> <em>s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">UDATA </td>
<td class="paramname"> <em>length</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Read characters from stdin into buffer.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library. </td></tr>
<tr><td valign="top"><tt>[out]</tt> </td><td valign="top"><em>s</em> </td><td>Buffer. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>length</em> </td><td>Size of buffer (s).</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>The number of characters read, -1 on error. </dd></dl>
</div>
</div><p>
<a class="anchor" name="ebb391dcc67d2644a7514e09db35d27c"></a><!-- doxytag: member="hytty.c::hytty_printf" ref="ebb391dcc67d2644a7514e09db35d27c" args="(struct HyPortLibrary *portLibrary, const char *format,...)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void VMCALL hytty_printf </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"> <em>...</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Write characters to stderr.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>format</em> </td><td>The format string to be output. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>...</em> </td><td>arguments for format.</td></tr>
</table>
</dl>
<dl class="note" compact><dt><b>Note:</b></dt><dd>Use hyfile_printf for stdout output. </dd></dl>
</div>
</div><p>
<a class="anchor" name="ce79d20d24d40aadce1669ad49474561"></a><!-- doxytag: member="hytty.c::hytty_shutdown" ref="ce79d20d24d40aadce1669ad49474561" args="(struct HyPortLibrary *portLibrary)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void VMCALL hytty_shutdown </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em> </td>
<td> ) </td>
<td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
PortLibrary shutdown.
<p>
This function is called during shutdown of the portLibrary. Any resources that were created by <a class="el" href="hytty_8c.html#ce3c3c3112269ee72a649df67bd5fed4">hytty_startup</a> should be destroyed here.<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library.</td></tr>
</table>
</dl>
<dl class="note" compact><dt><b>Note:</b></dt><dd>Most implementations will be empty. </dd></dl>
</div>
</div><p>
<a class="anchor" name="ce3c3c3112269ee72a649df67bd5fed4"></a><!-- doxytag: member="hytty.c::hytty_startup" ref="ce3c3c3112269ee72a649df67bd5fed4" args="(struct HyPortLibrary *portLibrary)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">I_32 VMCALL hytty_startup </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em> </td>
<td> ) </td>
<td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
PortLibrary startup.
<p>
This function is called during startup of the portLibrary. Any resources that are required for the TTY library operations may be created here. All resources created here should be destroyed in <a class="el" href="hytty_8c.html#ce79d20d24d40aadce1669ad49474561">hytty_shutdown</a>.<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library.</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>0 on success, negative error code on failure. Error code values returned are <ul>
<li>HYPORT_ERROR_STARTUP_TTY </li>
<li>HYPORT_ERROR_STARTUP_TTY_HANDLE </li>
<li>HYPORT_ERROR_STARTUP_TTY_CONSOLE</li>
</ul>
</dd></dl>
<dl class="note" compact><dt><b>Note:</b></dt><dd>Most implementations will simply return success. </dd></dl>
</div>
</div><p>
<a class="anchor" name="018634a7367405573c2480879176ddc4"></a><!-- doxytag: member="hytty.c::hytty_vprintf" ref="018634a7367405573c2480879176ddc4" args="(struct HyPortLibrary *portLibrary, const char *format, va_list args)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void VMCALL hytty_vprintf </td>
<td>(</td>
<td class="paramtype">struct <a class="el" href="structHyPortLibrary.html">HyPortLibrary</a> * </td>
<td class="paramname"> <em>portLibrary</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">va_list </td>
<td class="paramname"> <em>args</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td width="100%"></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Output message to stderr.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>portLibrary</em> </td><td>The port library. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>format</em> </td><td>The format String. </td></tr>
<tr><td valign="top"><tt>[in]</tt> </td><td valign="top"><em>args</em> </td><td>Variable argument list.</td></tr>
</table>
</dl>
<dl class="note" compact><dt><b>Note:</b></dt><dd>Use hyfile_vprintf for stdout output. </dd></dl>
</div>
</div><p>
<hr size="1">
<address style="text-align: center;">
<small>
<p>Genereated on Tue Dec 9 14:12:59 2008 by Doxygen.</p>
<p>(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable. </p>
</small>
</address>
</body>
</html>
|
freeVM/freeVM
|
standard/site/docs/externals/vm_doc/html/hytty_8c.html
|
HTML
|
apache-2.0
| 18,832
|
<?php
defined('IN_PHPCMS') or exit('Access Denied');
defined('UNINSTALL') or exit('Access Denied');
return array('announce');
?>
|
johnshen/phpcms
|
phpcms/modules/announce/uninstall/model.php
|
PHP
|
apache-2.0
| 135
|
/*
* Created on Oct 22, 2005
*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.framework.report;
import jsystem.framework.scenario.JTestContainer;
import jsystem.framework.scenario.flow_control.AntForLoop;
import junit.framework.Test;
import junit.framework.TestListener;
/**
* Used to give additional notification for TestListener's, like endRun
* on scenario execution end.
*
* @author guy.arieli
*
*/
public interface ExtendTestListener extends TestListener {
/**
* Notify that a warning was added to the test.
* @param test
*/
public void addWarning(Test test);
/**
* Serializable start test (used to move the notification over network connection)
* @param testInfo include all the test info parameters
*/
public void startTest(TestInfo testInfo);
/**
* Notify on run execution end.
*
*/
public void endRun();
/**
* notify that a loop started with a number of the loop
*
* @param loop the container object
* @param count the loop number
*/
public void startLoop(AntForLoop loop,int count);
/**
* notify that a loop ended with a number of the loop
*
* @param loop the container object
* @param count the loop number
*/
public void endLoop(AntForLoop loop,int count);
/**
* notify that a container element was started
*
* @param container the container object
*/
public void startContainer(JTestContainer container);
/**
* notify that a container element was finished
*
* @param container the container object
*/
public void endContainer(JTestContainer container);
}
|
Top-Q/jsystem
|
jsystem-core-projects/jsystemCore/src/main/java/jsystem/framework/report/ExtendTestListener.java
|
Java
|
apache-2.0
| 1,607
|
/*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.scelight.gui.dialog;
import hu.belicza.andras.util.VersionView;
import hu.scelight.Scelight;
import hu.scelight.bean.repfilters.RepFilterBean;
import hu.scelight.bean.repfilters.RepFiltersBean;
import hu.scelight.bean.repfolders.RepFolderBean;
import hu.scelight.bean.repfolders.RepFoldersBean;
import hu.scelight.gui.help.Helps;
import hu.scelight.gui.icon.Icons;
import hu.scelight.gui.setting.SettingsGui;
import hu.scelight.search.Connection;
import hu.scelight.search.FilterBy;
import hu.scelight.search.FilterByGroup;
import hu.scelight.search.Operator;
import hu.scelight.search.RepSearchEngine;
import hu.scelight.service.env.Env;
import hu.scelight.service.settings.Settings;
import hu.scelight.util.Utils;
import hu.scelight.util.gui.GuiUtils;
import hu.scelightapi.bean.repfilters.IRepFilterBean;
import hu.scelightapi.bean.repfilters.IRepFiltersBean;
import hu.scelightapi.gui.dialog.IRepFiltersEditorDialog;
import hu.sllauncher.action.XAction;
import hu.sllauncher.gui.comp.Browser;
import hu.sllauncher.gui.comp.HelpIcon;
import hu.sllauncher.gui.comp.Link;
import hu.sllauncher.gui.comp.ToolBarForTable;
import hu.sllauncher.gui.comp.XButton;
import hu.sllauncher.gui.comp.XDialog;
import hu.sllauncher.gui.comp.XFileChooser;
import hu.sllauncher.gui.comp.XLabel;
import hu.sllauncher.gui.comp.XScrollPane;
import hu.sllauncher.gui.comp.XSplitPane;
import hu.sllauncher.gui.comp.XTextField;
import hu.sllauncher.gui.comp.combobox.XComboBox;
import hu.sllauncher.gui.comp.table.XTable;
import hu.sllauncher.gui.comp.table.XTableModel;
import hu.sllauncher.gui.comp.table.editor.BoolCellEditor;
import hu.sllauncher.gui.comp.table.editor.DateCellEditor;
import hu.sllauncher.gui.comp.table.editor.IntegerCellEditor;
import hu.sllauncher.gui.comp.table.renderer.XTableCellRenderer;
import hu.sllauncher.util.SkillLevel;
import hu.sllauncher.util.gui.adapter.ActionAdapter;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JComponent;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.xml.bind.JAXB;
/**
* A dialog to view / edit the attached Replay filters of a Replay folder or a custom replay filters.
*
* @author Andras Belicza
*/
@SuppressWarnings( "serial" )
public class RepFiltersEditorDialog extends XDialog implements IRepFiltersEditorDialog {
/** Extension of the files holding replay filters. */
private static final String REP_FILTERS_FILE_EXT = "slfilt";
/** Default folder to save to / load from replay filters. */
private static final Path SAVE_FOLDER = Env.PATH_WORKSPACE.resolve( "rep-filters" );
static {
if ( !Files.exists( SAVE_FOLDER ) )
try {
Files.createDirectories( SAVE_FOLDER );
} catch ( final IOException ie ) {
Env.LOGGER.error( "Could not create folder: " + SAVE_FOLDER, ie );
}
}
/** Enable selected filters. */
private final XAction enableAction = new XAction( Icons.F_TICK, "Enable Selected Filters", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
final int[] indices = table.getSelectedModelRows();
final List< ? extends IRepFilterBean > filterList = repFiltersBean
.getRepFilterBeanList();
for ( final int idx : indices )
filterList.get( idx ).setEnabled( Boolean.TRUE );
rebuildTable();
}
};
/** Disable selected filters. */
private final XAction disableAction = new XAction( Icons.F_TICK_RED, "Disable Selected Filters", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
final int[] indices = table.getSelectedModelRows();
final List< ? extends IRepFilterBean > filterList = repFiltersBean
.getRepFilterBeanList();
for ( final int idx : indices )
filterList.get( idx ).setEnabled( Boolean.FALSE );
rebuildTable();
}
};
/** Moves up the selected filters. */
private final XAction moveUpAction = new XAction( Icons.F_ARROW_090, "Move Up Selected Filters", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
Utils.moveBackward( repFiltersBean.getRepFilterBeanList(), table.getSelectedModelRows() );
rebuildTable();
}
};
/** Moves down the selected filters. */
private final XAction moveDownAction = new XAction( Icons.F_ARROW_270, "Move Down Selected Filters", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
Utils.moveForward( repFiltersBean.getRepFilterBeanList(), table.getSelectedModelRows() );
rebuildTable();
}
};
/** Removes Selected Filters. */
private final XAction removeAction = new XAction( Icons.F_FUNNEL_MINUS, "Remove Selected Filters... (Delelte)", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
final int[] selectedRows = table.getSelectedModelRows();
if ( !GuiUtils.confirm( Utils.plural(
"Are you sure you want to remove %s Replay Filter%s?", selectedRows.length ) ) )
return;
// Sort rows and remove going downward
Arrays.sort( selectedRows );
final List< ? extends IRepFilterBean > filterList = repFiltersBean
.getRepFilterBeanList();
for ( int i = selectedRows.length - 1; i >= 0; i-- )
filterList.remove( selectedRows[ i ] );
rebuildTable();
};
};
/** Adds a new filter. */
private final XAction addNewAction = new XAction( Icons.F_FUNNEL_PLUS, "Add New Filter", cp ) {
@Override
@SuppressWarnings( "unchecked" )
public void actionPerformed( final ActionEvent event ) {
// TODO comment why safe to ignore warning (is it safe?)
( (List< IRepFilterBean >) repFiltersBean.getRepFilterBeanList() ).add( RepFilterBean
.createNewFilter() );
rebuildTable();
};
};
/** Saves the replay filters to a file. */
private final XAction saveAction = new XAction( Icons.F_DISK, "Save Replay Filters to a File...", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
final XFileChooser fc = new XFileChooser( SAVE_FOLDER );
fc.setDialogTitle( "Choose a file to save Replay Filters" );
fc.setFileFilter( new FileNameExtensionFilter( "Replay Filter files (*."
+ REP_FILTERS_FILE_EXT + ')', REP_FILTERS_FILE_EXT ) );
// Suggested file name
fc.setSelectedFile( Utils.uniqueFile(
SAVE_FOLDER.resolve( "replay-filters." + REP_FILTERS_FILE_EXT ) ).toFile() );
if ( XFileChooser.APPROVE_OPTION != fc.showSaveDialog( RepFiltersEditorDialog.this ) )
return;
Path path = fc.getSelectedPath();
// Ensure proper extension
if ( !path.getFileName().toString().toLowerCase().endsWith( '.' + REP_FILTERS_FILE_EXT ) )
path = path.resolveSibling( path.getFileName().toString() + '.'
+ REP_FILTERS_FILE_EXT );
if ( Files.exists( path ) )
if ( !GuiUtils.confirm( "The selected file already exists?", "Overwrite it?" ) )
return;
try {
JAXB.marshal( repFiltersBean, path.toFile() );
} catch ( final Exception e ) {
Env.LOGGER.error( "Failed to write to file: " + path, e );
GuiUtils.showErrorMsg( "Failed to write to file:", path );
}
}
};
/** Loads replay filters from a file. */
private final XAction loadAction = new XAction( Icons.F_FOLDER_OPEN, "Load Replay Filters from a File...", cp ) {
@Override
public void actionPerformed( final ActionEvent event ) {
final XFileChooser fc = new XFileChooser( SAVE_FOLDER );
fc.setDialogTitle( "Choose a file to load Replay Filters from" );
fc.setFileFilter( new FileNameExtensionFilter( "Replay Filter files (*."
+ REP_FILTERS_FILE_EXT + ")", REP_FILTERS_FILE_EXT ) );
if ( XFileChooser.APPROVE_OPTION != fc.showOpenDialog( RepFiltersEditorDialog.this ) )
return;
try {
repFiltersBean = JAXB
.unmarshal( fc.getSelectedPath().toFile(), RepFiltersBean.class );
if ( rfBean != null )
rfBean.setRepFiltersBean( (RepFiltersBean) repFiltersBean );
} catch ( final Exception e ) {
Env.LOGGER.error(
"Failed to load Replay filters from file: " + fc.getSelectedPath(), e );
GuiUtils.showErrorMsg( "Failed to load Replay filters from file file:",
fc.getSelectedPath() );
return;
}
rebuildTable();
}
};
/** Operator editor combo box. */
private final XComboBox< Operator > operatorEditorComboBox = new XComboBox<>();
/** Table cell editor used to edit operator cells. */
private final TableCellEditor operatorCellEditor = new DefaultCellEditor( operatorEditorComboBox );
/** Table displaying the defined/added filters. */
private final XTable table = new XTable() {
@Override
public TableCellEditor getCellEditor( final int row, final int column ) {
// row and column indices are VIEW indices
final int modelColumn = convertColumnIndexToModel( column );
if ( modelColumn == filterByColIdx || modelColumn == operatorColIdx
|| modelColumn == valueColIdx )
return getCustomCellEditor( row, column );
return super.getCellEditor( row, column );
}
};
/** Replay folders bean holding the replay folder whose attached filters are edited (must be a cloned instance). */
private final RepFoldersBean rfsBean;
/** Replay folder bean whose attached filters to be displayed / edited. */
private final RepFolderBean rfBean;
/** The edited replay filters. */
private IRepFiltersBean repFiltersBean;
/** Tells if the editor was closed with the OK button. */
private boolean ok;
/** {@link RepFilterBean} column model index. */
private int beanColIdx;
/** Connection column model index. */
private int connectionColIdx;
/** Enabled column model index. */
private int enabledColIdx;
/** Filter by group column model index. */
private int filterByGroupColIdx;
/** Filter by column model index. */
private int filterByColIdx;
/** Operator column model index. */
private int operatorColIdx;
/** Value column model index. */
private int valueColIdx;
/** Comment column model index. */
private int commentColIdx;
/** Browser to show an HTML preview of the filters structure. */
private final Browser previewBrowser = new Browser();
/**
* Creates a new {@link RepFiltersEditorDialog}.
*/
public RepFiltersEditorDialog() {
this( null );
}
/**
* Creates a new {@link RepFiltersEditorDialog}.
*
* @param customRepFiltersBean custom replay filters bean to edit
*/
public RepFiltersEditorDialog( final IRepFiltersBean customRepFiltersBean ) {
this( customRepFiltersBean, null, null );
}
/**
* Creates a new {@link RepFiltersEditorDialog}.
*
* <p>
* The editor will display / edit the attached filters of the specified replay folder.
* </p>
*
* @param rfsBean replay folders bean holding the replay folder whose attached filters are edited (must be a cloned instance)
* @param rfBean replay folder bean whose attached filters to be displayed / edited
*
* @throws IllegalArgumentException if one and only one of <code>rfsBean</code> and <code>rfBean</code> is <code>null</code>
*/
public RepFiltersEditorDialog( final RepFoldersBean rfsBean, final RepFolderBean rfBean ) {
this( null, rfsBean, rfBean );
}
/**
* Creates a new {@link RepFiltersEditorDialog}.
*
* <p>
* If <code>customRepFiltersBean</code> is <code>null</code>, the editor will display / edit the attached filters of the specified replay folder.
* </p>
*
* @param customRepFiltersBean custom replay filters bean to edit
* @param rfsBean replay folders bean holding the replay folder whose attached filters are edited (must be a cloned instance)
* @param rfBean replay folder bean whose attached filters to be displayed / edited
*
*/
private RepFiltersEditorDialog( final IRepFiltersBean customRepFiltersBean, final RepFoldersBean rfsBean, final RepFolderBean rfBean ) {
super( Env.MAIN_FRAME );
if ( rfsBean == null ^ rfBean == null )
throw new IllegalArgumentException( "Either both or none of the parameters must be null!" );
this.rfsBean = rfsBean;
this.rfBean = rfBean;
if ( rfBean == null ) {
repFiltersBean = customRepFiltersBean == null ? new RepFiltersBean() : customRepFiltersBean;
setTitle( "Custom Replay Filters" );
} else {
if ( rfBean.getRepFiltersBean() == null )
rfBean.setRepFiltersBean( new RepFiltersBean() );
repFiltersBean = rfBean.getRepFiltersBean();
setTitle( "Attached Replay Filters" + ( rfBean == null ? "" : " - " + rfBean.getPath() ) );
}
setIconImage( Icons.F_FUNNEL_PENCIL.get().getImage() );
buildGui();
restoreDefaultSize();
setVisible( true );
}
/**
* Builds the GUI of the editor dialog.
*/
private void buildGui() {
final ToolBarForTable toolBar = new ToolBarForTable( table );
toolBar.addSelectInfoLabel( "Select a Filter." );
toolBar.addSelEnabledButton( enableAction );
toolBar.addSelEnabledButton( disableAction );
toolBar.addSelEnabledButton( moveUpAction );
toolBar.addSelEnabledButton( moveDownAction );
toolBar.addSeparator();
toolBar.addSelEnabledButton( removeAction );
toolBar.addSeparator();
toolBar.add( addNewAction );
toolBar.addSeparator();
toolBar.add( saveAction );
toolBar.add( loadAction );
toolBar.addSeparator();
toolBar.add( new XLabel( "General" ).leftBorder( 20 ) );
toolBar.add( new HelpIcon( Helps.REPLAY_FILTERS ).leftBorder( 2 ) );
toolBar.addSeparator();
toolBar.add( new XLabel( Helps.PLAYER_FILTERS.title ) );
toolBar.add( new HelpIcon( Helps.PLAYER_FILTERS ).leftBorder( 2 ) );
toolBar.addSeparator();
JComponent comp;
toolBar.add( comp = new Link( "Regexp", Utils.createUrl( "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum" ) ) );
SettingsGui.bindVisibilityToSkillLevel( comp, SkillLevel.NORMAL );
toolBar.add( comp = new HelpIcon( Helps.REGULAR_EXPRESSIONS ).leftBorder( 2 ) );
SettingsGui.bindVisibilityToSkillLevel( comp, SkillLevel.NORMAL );
toolBar.finalizeLayout();
cp.addNorth( toolBar );
final XSplitPane splitPane = new XSplitPane( JSplitPane.VERTICAL_SPLIT );
table.setRowHeight( 24 );
table.setDeleteAction( removeAction );
( (DefaultCellEditor) table.getDefaultEditor( String.class ) ).setClickCountToStart( 1 );
splitPane.setTopComponent( table.createWrapperBox( true ) );
splitPane.setBottomComponent( new XScrollPane( previewBrowser ) );
splitPane.setResizeWeight( 0.6 );
cp.addCenter( splitPane );
final XButton okButton = new XButton( "_OK" );
okButton.addActionListener( new ActionAdapter() {
@Override
public void actionPerformed( final ActionEvent event ) {
// Clear filters bean if no filter remained
if ( repFiltersBean.getRepFilterBeanList().isEmpty() ) {
repFiltersBean = null;
if ( rfBean != null )
rfBean.setRepFiltersBean( null );
}
ok = true;
close();
if ( rfsBean != null ) {
Env.APP_SETTINGS.set( Settings.REPLAY_FOLDERS_BEAN, rfsBean );
// Save settings.
Scelight.INSTANCE().saveSettings();
}
}
} );
getButtonsPanel().add( okButton );
getRootPane().setDefaultButton( okButton );
getButtonsPanel().add( okButton );
addCloseButton( "_Cancel" );
// Table header
final XTableModel model = table.getXTableModel();
final Vector< String > columns = Utils.asNewVector( "Bean", "Enabled?", "Connection", "Filter by Group", "Filter by", "Operator", "Value", "Comment" );
final List< Class< ? > > columnClasses = Utils.< Class< ? > > asNewList( RepFilterBean.class, Boolean.class, Connection.class, FilterByGroup.class,
FilterBy.class, Operator.class, Object.class, String.class );
// Custom cell renderer to indicate errors with red background
table.setTableCellRenderer( new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent( final JTable table, final Object value, final boolean isSelected, final boolean hasFocus,
final int row, final int column ) {
final XTableCellRenderer xTableCellRenderer = RepFiltersEditorDialog.this.table.getXTableCellRenderer();
xTableCellRenderer.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
boolean error = false;
final int col = table.convertColumnIndexToModel( column );
if ( col != commentColIdx && value == null )
error = true;
else {
final RepFilterBean filterBean = (RepFilterBean) model.getValueAt( table.convertRowIndexToModel( row ), beanColIdx );
final FilterByGroup fbg = filterBean.getFilterByGroup();
final FilterBy fb = filterBean.getFilterBy();
final Operator op = filterBean.getOperator();
if ( col == valueColIdx ) {
if ( filterBean.getValue() == null )
error = true;
} else if ( col == operatorColIdx ) {
if ( fb == null || !Utils.contains( fb.operators, op ) )
error = true;
} else if ( col == filterByColIdx ) {
if ( fbg == null || !Utils.contains( fbg.filterBys, fb ) )
error = true;
}
}
if ( !isSelected ) // If selected, this colors is "overridden" (set)
xTableCellRenderer.setBackground( null );
if ( error )
xTableCellRenderer.setBackground( XTextField.ERROR_COLOR );
return xTableCellRenderer;
}
} );
beanColIdx = 0;
enabledColIdx = 1;
connectionColIdx = 2;
filterByGroupColIdx = 3;
filterByColIdx = 4;
operatorColIdx = 5;
valueColIdx = 6;
commentColIdx = 7;
model.setColumnIdentifiers( columns );
model.setColumnClasses( columnClasses );
final XComboBox< Connection > connectionEditorComboBox = new XComboBox<>( Connection.VALUES );
table.getColumnModel().getColumn( connectionColIdx ).setCellEditor( new DefaultCellEditor( connectionEditorComboBox ) );
// Pack connection column by hand (due to editor is wider than header and elements)
table.getColumnModel().getColumn( table.convertColumnIndexToView( connectionColIdx ) )
.setPreferredWidth( connectionEditorComboBox.getPreferredSize().width + 3 );
table.getColumnModel().getColumn( table.convertColumnIndexToView( connectionColIdx ) )
.setMaxWidth( connectionEditorComboBox.getPreferredSize().width + 3 );
final XComboBox< FilterByGroup > filterByGroupEditorComboBox = new XComboBox<>( FilterByGroup.VALUES );
table.getColumnModel().getColumn( filterByGroupColIdx ).setCellEditor( new DefaultCellEditor( filterByGroupEditorComboBox ) );
// Pack connection column by hand (due to editor is wider than header and elements)
table.getColumnModel().getColumn( table.convertColumnIndexToView( filterByGroupColIdx ) )
.setPreferredWidth( filterByGroupEditorComboBox.getPreferredSize().width + 3 );
table.getColumnModel().getColumn( table.convertColumnIndexToView( filterByGroupColIdx ) )
.setMaxWidth( filterByGroupEditorComboBox.getPreferredSize().width + 3 );
model.addTableModelListener( new TableModelListener() {
@Override
public void tableChanged( final TableModelEvent event ) {
if ( !table.isEditing() )
return;
// Model event returns model indices
final int col = event.getColumn();
final int row = event.getFirstRow();
if ( col < 0 ) // Experienced this sometimes if saved filters are loaded which contain invalid enum values...
return;
final Object value = model.getValueAt( row, col );
final RepFilterBean filterBean = (RepFilterBean) model.getValueAt( row, beanColIdx );
if ( col == enabledColIdx ) {
filterBean.setEnabled( (Boolean) value );
rebuildPreview();
} else if ( col == connectionColIdx ) {
filterBean.setConnection( (Connection) value );
rebuildPreview();
} else if ( col == filterByGroupColIdx ) {
// Only proceed if filter by group was really changed
final FilterByGroup oldFbg = filterBean.getFilterByGroup();
if ( oldFbg == null || value == null || oldFbg != value ) { // Filter by group is an enum...
filterBean.setFilterByGroup( (FilterByGroup) value );
// If the new group's filter bys is not the same as the old group's,
// also reset filter by and operator (use the first supported op of the first filter by)
// and value (most likely invalid for another filter by)
if ( oldFbg == null || value == null || oldFbg.filterBys != filterBean.getFilterByGroup().filterBys ) {
filterBean.setFilterBy( filterBean.getFilterByGroup() == null ? null : filterBean.getFilterByGroup().filterBys[ 0 ] );
filterBean.setOperator( filterBean.getFilterBy() == null ? null : filterBean.getFilterBy().operators[ 0 ] );
filterBean.setValue( null );
}
// Rebuild table (model.fireTableRowsUpdated() is not enough, model is not updated only the Bean!)
// Also do this "later" else ArrayIndexOutOfBoundsException occurs (due to the hidden bean column).
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
rebuildTable();
}
} );
}
} else if ( col == filterByColIdx ) {
// Only proceed if filter by was really changed:
if ( filterBean.getFilterBy() != value ) { // Filter by is an enum...
filterBean.setFilterBy( (FilterBy) value );
// Also reset operator (use the first supported op of the filter by)
// and value (most likely invalid for another filter by)
filterBean.setOperator( filterBean.getFilterBy() == null ? null : filterBean.getFilterBy().operators[ 0 ] );
filterBean.setValue( null );
// Rebuild table (model.fireTableRowsUpdated() is not enough, model is not updated only the Bean!)
// Also do this "later" else ArrayIndexOutOfBoundsException occurs (due to the hidden bean column).
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
rebuildTable();
}
} );
}
} else if ( col == operatorColIdx ) {
filterBean.setOperator( (Operator) value );
rebuildPreview();
} else if ( col == valueColIdx ) {
if ( filterBean.getFilterBy() == FilterBy.VERSION ) {
// Remove all non-digits except the dot (leave only numbers and the dot):
if ( value instanceof String ) // Came from the text editor
filterBean.setValue( VersionView.fromString( ( (String) value ).replaceAll( "[^0-9\\.]", "" ) ) );
else
filterBean.setValue( value ); // Might be null or might be an unedited VersionView
// Also set this optionally modified value to the table model (but of course "later"):
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
model.setValueAt( filterBean.getValue(), row, col );
}
} );
} else
filterBean.setValue( value );
rebuildPreview();
} else if ( col == commentColIdx ) {
filterBean.setComment( (String) value );
}
}
} );
table.getColumnModel().removeColumn( table.getColumnModel().getColumn( beanColIdx ) );
table.setSortable( false );
table.setEditable( true );
rebuildTable();
}
/**
* Rebuilds the table.
*/
private void rebuildTable() {
table.saveSelection( beanColIdx );
final XTableModel model = table.getXTableModel();
model.getDataVector().clear();
model.fireTableDataChanged();
for ( final IRepFilterBean filterBean : repFiltersBean.getRepFilterBeanList() ) {
final Vector< Object > row = Utils.< Object > asNewVector( filterBean, filterBean.getEnabled(), filterBean.getConnection(),
filterBean.getFilterByGroup(), filterBean.getFilterBy(), filterBean.getOperator(), filterBean.getValue(), filterBean.getComment() );
model.addRow( row );
}
table.packColumns( table.convertColumnIndexToView( enabledColIdx ) );
// Filter by group and Connection cols are already manually packed.
table.restoreSelection( beanColIdx );
rebuildPreview();
}
/**
* Rebuilds the filters preview HTML table.
*/
private void rebuildPreview() {
final StringBuilder sb = new StringBuilder();
sb.append( "<html><head><style>" );
sb.append( ".conn{font-weight:bold}" );
sb.append( ".fbg{color:#777777}" );
sb.append( ".fby{color:blue;font-style:italic}" );
sb.append( ".op{font-weight:bold}" );
sb.append( ".fval{}" );
sb.append( "</style></head><body><b>Filters Structure Preview:</b><br>" );
new RepSearchEngine( repFiltersBean ).getStructure( sb );
sb.append( "</body></html>" );
previewBrowser.setText( sb.toString() );
previewBrowser.setCaretPosition( 0 );
}
/** General value cell editor. */
private final DefaultCellEditor generalValueCellEditor = new DefaultCellEditor( new XTextField() );
{
generalValueCellEditor.setClickCountToStart( 1 );
}
/** Combo box value editor for filter by column and for filter by's having an enum type. */
private final XComboBox< Object > valueEditorComboBox = new XComboBox<>();
{
// Allow all player filter bys to be visible:
valueEditorComboBox.setMaximumRowCount( FilterBy.PLAYER_VALUES.length );
}
/** Value cell editor for filter by column and for filter by's having an enum type. */
private final DefaultCellEditor valueComboBoxCellEditor = new DefaultCellEditor( valueEditorComboBox );
/**
* Returns a custom cell editor for the filter by, operator and value columns.
*
* @param row row view index to return an editor for
* @param column column view index to return an editor for
* @return a custom cell editor for the filter by, operator and value columns
*/
private TableCellEditor getCustomCellEditor( final int row, final int column ) {
// row and column indices are VIEW indices
final int modelColumn = table.convertColumnIndexToModel( column );
final FilterBy filterBy = (FilterBy) table.getModel().getValueAt( table.convertRowIndexToModel( row ), filterByColIdx );
if ( modelColumn == filterByColIdx ) {
final FilterByGroup filterByGroup = (FilterByGroup) table.getModel().getValueAt( table.convertRowIndexToModel( row ), filterByGroupColIdx );
valueEditorComboBox.removeAllItems();
if ( filterByGroup != null )
for ( final FilterBy o : filterByGroup.filterBys )
valueEditorComboBox.addItem( o );
return valueComboBoxCellEditor;
} else if ( modelColumn == operatorColIdx ) {
// Only offer operators supported by the row's filter by
operatorEditorComboBox.removeAllItems();
if ( filterBy != null )
for ( final Operator op : filterBy.operators )
operatorEditorComboBox.addItem( op );
return operatorCellEditor;
} else if ( modelColumn == valueColIdx ) {
if ( filterBy == null || filterBy.type.isEnum() ) {
valueEditorComboBox.removeAllItems();
if ( filterBy != null )
for ( final Object o : filterBy.type.getEnumConstants() )
valueEditorComboBox.addItem( o );
return valueComboBoxCellEditor;
} else if ( filterBy.type == Date.class ) {
return DateCellEditor.INSTANCE;
} else if ( filterBy.type == Integer.class ) {
return IntegerCellEditor.INSTANCE;
} else if ( filterBy.type == Boolean.class ) {
return BoolCellEditor.INSTANCE;
} else
return generalValueCellEditor;
} else
return null;
}
@Override
public boolean isOk() {
return ok;
}
@Override
public IRepFiltersBean getRepFiltersBean() {
return repFiltersBean;
}
}
|
icza/scelight
|
src-app/hu/scelight/gui/dialog/RepFiltersEditorDialog.java
|
Java
|
apache-2.0
| 36,819
|
var initialize = function ($scope, callback, splash) {
var self;
var constructor = function () {
self = this;
if ( splash != true ) {
$scope.$on('$stateChangeSuccess', function() {
//self.menuBtnWave();
self.menu();
//self.headerBtnWave();
self.allBtnWave();
self.setContainerSize();
if (callback) {
callback();
}
});
}
};
constructor.prototype.initDebug = function () {
if (window.device == undefined) {
window.device = {
model: 'debug',
platform: 'debug',
uuid: 'debug',
version: 1.0
};
}
};
constructor.prototype.menu = function () {
var menuEl = document.getElementById('menu');
if (!AC.TouchMenu) {
AC.TouchMenu = TouchMenuLA({
target: menuEl
});
}
};
constructor.prototype.setContainerSize = function () {
var container = document.querySelector('.content');
if (container && AC.Tools.hasClass(container, 'scroll')) {
document.getElementById('view-index').style.overflow = 'hidden';
container.style.overflow = 'auto';
}
};
constructor.prototype.headerBtnWave = function () {
var links = document.querySelectorAll('.icon-btn');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('touchend', function (e) {
var hoverBall;
hoverBall = document.createElement('div');
hoverBall.className = 'wave-effect';
this.appendChild(hoverBall);
hoverBall.style.webkitTransform = 'scale(1)';
hoverBall.style.opacity = '0.1';
//var timeoutWave = setTimeout(function () {
// hoverBall.style.transition = 'none';
// hoverBall.style.webkitTransform = 'scale(0)';
// if (hoverBall.parentNode) {
// hoverBall.parentNode.removeChild(hoverBall);
// }
// clearTimeout(timeoutWave);
//}, 500);
//var timeoutWaveBg = setTimeout(function () {
// hoverBall.style.opacity = '0';
// clearTimeout(timeoutWaveBg);
//}, 250);
});
}
};
constructor.prototype.allBtnWave = function () {
var btnsWave = document.querySelectorAll('.btn-wave');
for (var i = 0; i < btnsWave.length; i++) {
btnsWave[i].addEventListener('touchend', function (e) {
var waveEffect,
width,
bgColor;
bgColor = AC.Tools.getColorByClass(this.className);
waveEffect = document.createElement('div');
waveEffect.className = 'wave-effect';
this.appendChild(waveEffect);
width = waveEffect.parentNode.clientWidth * 2;
waveEffect.style.width = width + 'px';
waveEffect.style.height = width + 'px';
waveEffect.style.marginTop = -(width / 2) + 'px';
waveEffect.style.marginLeft = -(width / 2) + 'px';
waveEffect.style.top = (e.changedTouches[0].clientY - waveEffect.parentNode.getBoundingClientRect().top) + 'px';
waveEffect.style.left = (e.changedTouches[0].clientX - waveEffect.parentNode.getBoundingClientRect().left) + 'px';
waveEffect.style.webkitTransform = 'scale(1)';
waveEffect.style.background = bgColor;
waveEffect.style.opacity = '0.1';
var timeoutWave = setTimeout(function () {
waveEffect.style.transition = 'none';
waveEffect.style.webkitTransform = 'scale(0)';
if (waveEffect) {
waveEffect.remove();
}
clearTimeout(timeoutWave);
}, 500);
var timeoutWaveBg = setTimeout(function () {
waveEffect.style.opacity = '0';
clearTimeout(timeoutWaveBg);
}, 150);
});
}
};
constructor.prototype.menuBtnWave = function () {
var btnsWave = document.querySelectorAll('.menu-items li:not(.space):not(line)');
for (var i = 0; i < btnsWave.length; i++) {
btnsWave[i].addEventListener('touchend', function (e) {
var waveEffect;
waveEffect = document.createElement('div');
waveEffect.className = 'wave-effect';
this.appendChild(waveEffect);
waveEffect.style.width = '300px';
waveEffect.style.height = '300px';
waveEffect.style.marginTop = '-150px';
waveEffect.style.marginLeft = '-150px';
waveEffect.style.top = (e.changedTouches[0].clientY - waveEffect.parentNode.getBoundingClientRect().top) + 'px';
waveEffect.style.left = (e.changedTouches[0].clientX - waveEffect.parentNode.getBoundingClientRect().left) + 'px';
waveEffect.style.webkitTransform = 'scale(1)';
waveEffect.style.background = '#000000';
waveEffect.style.opacity = '0.1';
var timeoutWave = setTimeout(function () {
waveEffect.style.transition = 'none';
waveEffect.style.webkitTransform = 'scale(0)';
if (waveEffect) {
waveEffect.remove();
}
clearTimeout(timeoutWave);
}, 500);
var timeoutWaveBg = setTimeout(function () {
waveEffect.style.opacity = '0';
clearTimeout(timeoutWaveBg);
}, 100);
});
}
};
return new constructor();
};
AC.initialize = initialize;
|
ericktatsui/Anime-Check
|
www/src/js/initialize.js
|
JavaScript
|
apache-2.0
| 6,169
|
using SunLine.Community.Entities.Dict;
using SunLine.Community.Repositories.Infrastructure;
namespace SunLine.Community.Repositories.Dict
{
public interface ILanguageRepository : IEntityRepository<Language>
{
Language FindByCode(string code);
}
}
|
mczachurski/community-web
|
SunLine.Community.Repositories/Dict/ILanguageRepository.cs
|
C#
|
apache-2.0
| 271
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_144) on Wed Feb 28 00:23:43 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class se.litsec.eidas.opensaml.config.XMLObjectProviderInitializer (eIDAS extension for OpenSAML 3.x - 1.1.0)</title>
<meta name="date" content="2018-02-28">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class se.litsec.eidas.opensaml.config.XMLObjectProviderInitializer (eIDAS extension for OpenSAML 3.x - 1.1.0)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../se/litsec/eidas/opensaml/config/XMLObjectProviderInitializer.html" title="class in se.litsec.eidas.opensaml.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?se/litsec/eidas/opensaml/config/class-use/XMLObjectProviderInitializer.html" target="_top">Frames</a></li>
<li><a href="XMLObjectProviderInitializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class se.litsec.eidas.opensaml.config.XMLObjectProviderInitializer" class="title">Uses of Class<br>se.litsec.eidas.opensaml.config.XMLObjectProviderInitializer</h2>
</div>
<div class="classUseContainer">No usage of se.litsec.eidas.opensaml.config.XMLObjectProviderInitializer</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../se/litsec/eidas/opensaml/config/XMLObjectProviderInitializer.html" title="class in se.litsec.eidas.opensaml.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?se/litsec/eidas/opensaml/config/class-use/XMLObjectProviderInitializer.html" target="_top">Frames</a></li>
<li><a href="XMLObjectProviderInitializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.litsec.se">Litsec AB</a>. All rights reserved.</small></p>
</body>
</html>
|
litsec/eidas-opensaml
|
docs/javadoc/opensaml3/1.1.0/se/litsec/eidas/opensaml/config/class-use/XMLObjectProviderInitializer.html
|
HTML
|
apache-2.0
| 4,952
|
# AUTOGENERATED FILE
FROM balenalib/solidrun-imx6-alpine:3.14-run
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apk add --no-cache ca-certificates libffi \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.9.10
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& buildDeps=' \
curl \
gnupg \
' \
&& apk add --no-cache --virtual .build-deps $buildDeps \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" \
&& echo "6c0599f15256a7c907ee3b8ac2b5ac85535f39f8c8d0881a1add0f5949927c17 Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.14 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.10, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
resin-io-library/base-images
|
balena-base-images/python/solidrun-imx6/alpine/3.14/3.9.10/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 4,131
|
/*
* Copyright 2008 The Closure Compiler 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.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.ControlFlowGraph.AbstractCfgNodeTraversalCallback;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.graph.GraphNode;
import com.google.javascript.jscomp.graph.LatticeElement;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Computes reaching definition for all use of each variables.
*
* A definition of {@code A} in {@code A = foo()} is a reaching definition of
* the use of {@code A} in {@code alert(A)} if all paths from entry node must
* reaches that definition and it is the last definition before the use.
*
*/
final class MustBeReachingVariableDef extends
DataFlowAnalysis<Node, MustBeReachingVariableDef.MustDef> {
// The scope of the function that we are analyzing.
private final Scope jsScope;
private final AbstractCompiler compiler;
private final Set<Var> escaped;
MustBeReachingVariableDef(
ControlFlowGraph<Node> cfg, Scope jsScope, AbstractCompiler compiler) {
super(cfg, new MustDefJoin());
this.jsScope = jsScope;
this.compiler = compiler;
this.escaped = new HashSet<>();
computeEscaped(jsScope, escaped, compiler);
}
/**
* Abstraction of a local variable definition. It represents the node which
* a local variable is defined as well as a set of other local variables that
* this definition reads from. For example N: a = b + foo.bar(c). The
* definition node will be N, the depending set would be {b,c}.
*/
static class Definition {
final Node node;
final Set<Var> depends = new HashSet<>();
private boolean unknownDependencies = false;
Definition(Node node) {
this.node = node;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Definition)) {
return false;
}
Definition otherDef = (Definition) other;
// If the var has the same definition node we can assume they have the
// same depends set.
return otherDef.node == node;
}
@Override
public String toString() {
return "Definition@" + node;
}
@Override
public int hashCode() {
return node.hashCode();
}
}
/**
* Must reaching definition lattice representation. It captures a product
* lattice for each local (non-escaped) variable. The sub-lattice is
* a n + 2 element lattice with all the {@link Definition} in the program,
* TOP and BOTTOM.
*
* <p>Since this is a Must-Define analysis, BOTTOM represents the case where
* there might be more than one reaching definition for the variable.
*
*
* (TOP)
* / | | \
* N1 N2 N3 ....Nn
* \ | | /
* (BOTTOM)
*
*/
static final class MustDef implements LatticeElement {
// TODO(user): Use bit vector instead of maps might get better
// performance. Change it after this is tested to be fully functional.
// When a Var "A" = "TOP", "A" does not exist in reachingDef's keySet.
// When a Var "A" = Node N, "A" maps to that node.
// When a Var "A" = "BOTTOM", "A" maps to null.
final Map<Var, Definition> reachingDef;
public MustDef() {
reachingDef = new HashMap<>();
}
public MustDef(Iterator<Var> vars) {
this();
while (vars.hasNext()) {
Var var = vars.next();
// Every variable in the scope is defined once in the beginning of the
// function: all the declared variables are undefined, all functions
// have been assigned and all arguments has its value from the caller.
reachingDef.put(var, new Definition(var.scope.getRootNode()));
}
}
/**
* Copy constructor.
*
* @param other The constructed object is a replicated copy of this element.
*/
public MustDef(MustDef other) {
reachingDef = new HashMap<>(other.reachingDef);
}
@Override
public boolean equals(Object other) {
return (other instanceof MustDef) &&
((MustDef) other).reachingDef.equals(this.reachingDef);
}
@Override
public int hashCode() {
return reachingDef.hashCode();
}
}
private static class MustDefJoin extends JoinOp.BinaryJoinOp<MustDef> {
@Override
public MustDef apply(MustDef a, MustDef b) {
MustDef result = new MustDef();
Map<Var, Definition> resultMap = result.reachingDef;
// Take the join of all variables that are not TOP in this.
for (Map.Entry<Var, Definition> varEntry : a.reachingDef.entrySet()) {
Var var = varEntry.getKey();
Definition aDef = varEntry.getValue();
if (aDef == null) {
// "a" is BOTTOM implies that the variable has more than one possible
// definition. We set the join of this to be BOTTOM regardless of what
// "b" might be.
resultMap.put(var, null);
continue;
}
if (b.reachingDef.containsKey(var)) {
Definition bDef = b.reachingDef.get(var);
if (aDef.equals(bDef)) {
resultMap.put(var, aDef);
} else {
resultMap.put(var, null);
}
} else {
resultMap.put(var, aDef);
}
}
// Take the join of all variables that are not TOP in other but it is TOP
// in this.
for (Map.Entry<Var, Definition> entry : b.reachingDef.entrySet()) {
Var var = entry.getKey();
if (!a.reachingDef.containsKey(var)) {
resultMap.put(var, entry.getValue());
}
}
return result;
}
}
@Override
boolean isForward() {
return true;
}
@Override
MustDef createEntryLattice() {
return new MustDef(jsScope.getVars());
}
@Override
MustDef createInitialEstimateLattice() {
return new MustDef();
}
@Override
MustDef flowThrough(Node n, MustDef input) {
// TODO(user): We are doing a straight copy from input to output. There
// might be some opportunities to cut down overhead.
MustDef output = new MustDef(input);
// TODO(user): This must know about ON_EX edges but it should handle
// it better than what we did in liveness. Because we are in a forward mode,
// we can used the branched forward analysis.
computeMustDef(n, n, output, false);
return output;
}
/**
* @param n The node in question.
* @param cfgNode The node to add
* @param conditional true if the definition is not always executed.
*/
private void computeMustDef(
Node n, Node cfgNode, MustDef output, boolean conditional) {
switch (n.getType()) {
case Token.BLOCK:
case Token.FUNCTION:
return;
case Token.WHILE:
case Token.DO:
case Token.IF:
computeMustDef(
NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
return;
case Token.FOR:
if (!NodeUtil.isForIn(n)) {
computeMustDef(
NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
} else {
// for(x in y) {...}
Node lhs = n.getFirstChild();
Node rhs = lhs.getNext();
if (lhs.isVar()) {
lhs = lhs.getLastChild(); // for(var x in y) {...}
}
if (lhs.isName()) {
addToDefIfLocal(lhs.getString(), cfgNode, rhs, output);
}
}
return;
case Token.AND:
case Token.OR:
computeMustDef(n.getFirstChild(), cfgNode, output, conditional);
computeMustDef(n.getLastChild(), cfgNode, output, true);
return;
case Token.HOOK:
computeMustDef(n.getFirstChild(), cfgNode, output, conditional);
computeMustDef(n.getSecondChild(), cfgNode, output, true);
computeMustDef(n.getLastChild(), cfgNode, output, true);
return;
case Token.VAR:
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (c.hasChildren()) {
computeMustDef(c.getFirstChild(), cfgNode, output, conditional);
addToDefIfLocal(c.getString(), conditional ? null : cfgNode,
c.getFirstChild(), output);
}
}
return;
default:
if (NodeUtil.isAssignmentOp(n)) {
if (n.getFirstChild().isName()) {
Node name = n.getFirstChild();
computeMustDef(name.getNext(), cfgNode, output, conditional);
addToDefIfLocal(name.getString(), conditional ? null : cfgNode,
n.getLastChild(), output);
return;
} else if (NodeUtil.isGet(n.getFirstChild())) {
// Treat all assignments to arguments as redefining the
// parameters itself.
Node obj = n.getFirstChild().getFirstChild();
if (obj.isName() && "arguments".equals(obj.getString())) {
// TODO(user): More accuracy can be introduced
// i.e. We know exactly what arguments[x] is if x is a constant
// number.
escapeParameters(output);
}
}
}
if (n.isName() && "arguments".equals(n.getString())) {
escapeParameters(output);
}
// DEC and INC actually defines the variable.
if (n.isDec() || n.isInc()) {
Node target = n.getFirstChild();
if (target.isName()) {
addToDefIfLocal(target.getString(),
conditional ? null : cfgNode, null, output);
return;
}
}
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
computeMustDef(c, cfgNode, output, conditional);
}
}
}
/**
* Set the variable lattice for the given name to the node value in the def
* lattice. Do nothing if the variable name is one of the escaped variable.
*
* @param node The CFG node where the definition should be record to.
* {@code null} if this is a conditional define.
*/
private void addToDefIfLocal(String name, @Nullable Node node,
@Nullable Node rValue, MustDef def) {
Var var = jsScope.getVar(name);
// var might be null because the variable might be defined in the extern
// that we might not traverse.
if (var == null || var.scope != jsScope) {
return;
}
for (Var other : def.reachingDef.keySet()) {
Definition otherDef = def.reachingDef.get(other);
if (otherDef == null) {
continue;
}
if (otherDef.depends.contains(var)) {
def.reachingDef.put(other, null);
}
}
if (!escaped.contains(var)) {
if (node == null) {
def.reachingDef.put(var, null);
} else {
Definition definition = new Definition(node);
if (rValue != null) {
computeDependence(definition, rValue);
}
def.reachingDef.put(var, definition);
}
}
}
private void escapeParameters(MustDef output) {
for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) {
Var v = i.next();
if (isParameter(v)) {
// Assume we no longer know where the parameter comes from
// anymore.
output.reachingDef.put(v, null);
}
}
// Also, assume we no longer know anything that depends on a parameter.
for (Entry<Var, Definition> pair : output.reachingDef.entrySet()) {
Definition value = pair.getValue();
if (value == null) {
continue;
}
for (Var dep : value.depends) {
if (isParameter(dep)) {
output.reachingDef.put(pair.getKey(), null);
}
}
}
}
private static boolean isParameter(Var v) {
return v.isParam();
}
/**
* Computes all the local variables that rValue reads from and store that
* in the def's depends set.
*/
private void computeDependence(final Definition def, Node rValue) {
NodeTraversal.traverseEs6(compiler, rValue,
new AbstractCfgNodeTraversalCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isName()) {
Var dep = jsScope.getVar(n.getString());
if (dep == null) {
def.unknownDependencies = true;
} else {
def.depends.add(dep);
}
}
}
});
}
/**
* Gets the must reaching definition of a given node.
*
* @param name name of the variable. It can only be names of local variable
* that are not function parameters, escaped variables or variables
* declared in catch.
* @param useNode the location of the use where the definition reaches.
*/
Definition getDef(String name, Node useNode) {
Preconditions.checkArgument(getCfg().hasNode(useNode));
GraphNode<Node, Branch> n = getCfg().getNode(useNode);
FlowState<MustDef> state = n.getAnnotation();
return state.getIn().reachingDef.get(jsScope.getVar(name));
}
Node getDefNode(String name, Node useNode) {
Definition def = getDef(name, useNode);
return def == null ? null : def.node;
}
boolean dependsOnOuterScopeVars(Definition def) {
if (def.unknownDependencies) {
return true;
}
for (Var s : def.depends) {
if (s.scope != jsScope) {
return true;
}
}
return false;
}
}
|
lgeorgieff/closure-compiler
|
src/com/google/javascript/jscomp/MustBeReachingVariableDef.java
|
Java
|
apache-2.0
| 14,154
|
//--------------------------------------------------------------------------------------
// File: utils.cpp
//
// Helper utilities for the Compute Shader Accelerated BC6H BC7 Encoder/Decoder
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <stdio.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#include <d3dx11.h>
#include <shlobj.h>
#include <string>
#include "utils.h"
HRESULT WINAPI Dynamic_D3D11CreateDevice( IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT32 Flags,
D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT32 SDKVersion,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext )
{
typedef HRESULT (WINAPI * LPD3D11CREATEDEVICE)( IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT32, D3D_FEATURE_LEVEL*, UINT, UINT32, ID3D11Device**, D3D_FEATURE_LEVEL*, ID3D11DeviceContext** );
static LPD3D11CREATEDEVICE s_DynamicD3D11CreateDevice = NULL;
if ( s_DynamicD3D11CreateDevice == NULL )
{
HMODULE hModD3D11 = LoadLibrary( L"d3d11.dll" );
if ( hModD3D11 == NULL )
{
// Ensure this "D3D11 absent" message is shown only once. As sometimes, the app would like to try
// to create device multiple times
static bool bMessageAlreadyShwon = false;
if ( !bMessageAlreadyShwon )
{
OSVERSIONINFOEX osv;
memset( &osv, 0, sizeof(osv) );
osv.dwOSVersionInfoSize = sizeof(osv);
GetVersionEx( (LPOSVERSIONINFO)&osv );
if ( ( osv.dwMajorVersion > 6 )
|| ( osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 1 )
|| ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber > 6002 ) )
{
MessageBox( 0, L"Direct3D 11 components were not found.", L"Error", MB_ICONEXCLAMATION );
// This should not happen, but is here for completeness as the system could be
// corrupted or some future OS version could pull D3D11.DLL for some reason
}
else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber == 6002 )
{
MessageBox( 0, L"Direct3D 11 components were not found, but are available for"\
L" this version of Windows.\n"\
L"For details see Microsoft Knowledge Base Article #971644\n"\
L"http://support.microsoft.com/default.aspx/kb/971644/", L"Error", MB_ICONEXCLAMATION );
}
else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 )
{
MessageBox( 0, L"Direct3D 11 components were not found. Please install the latest Service Pack.\n"\
L"For details see Microsoft Knowledge Base Article #935791\n"\
L" http://support.microsoft.com/default.aspx/kb/935791", L"Error", MB_ICONEXCLAMATION );
}
else
{
MessageBox( 0, L"Direct3D 11 is not supported on this OS.", L"Error", MB_ICONEXCLAMATION );
}
bMessageAlreadyShwon = true;
}
return E_FAIL;
}
s_DynamicD3D11CreateDevice = ( LPD3D11CREATEDEVICE )GetProcAddress( hModD3D11, "D3D11CreateDevice" );
}
return s_DynamicD3D11CreateDevice( pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels,
SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext );
}
HRESULT CreateDevice( ID3D11Device** ppDeviceOut, ID3D11DeviceContext** ppContextOut, BOOL bForceRef /*= FALSE*/ )
{
*ppDeviceOut = NULL;
*ppContextOut = NULL;
HRESULT hr = S_OK;
UINT uCreationFlags = D3D11_CREATE_DEVICE_SINGLETHREADED;
#if defined(DEBUG) || defined(_DEBUG)
uCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL flOut = D3D_FEATURE_LEVEL_9_1;
if ( !bForceRef )
{
hr = Dynamic_D3D11CreateDevice( NULL, // Use default graphics card
D3D_DRIVER_TYPE_HARDWARE, // Try to create a hardware accelerated device
NULL, // Do not use external software rasterizer module
uCreationFlags, // Device creation flags
NULL, // Try to get greatest feature level available
0, // # of elements in the previous array
D3D11_SDK_VERSION, // SDK version
ppDeviceOut, // Device out
&flOut, // Actual feature level created
ppContextOut ); // Context out
}
if ( bForceRef || FAILED(hr) )
{
// Either because of failure on creating a hardware device or we are forced to create a ref device, we create a ref device here
SAFE_RELEASE( *ppDeviceOut );
SAFE_RELEASE( *ppContextOut );
hr = Dynamic_D3D11CreateDevice( NULL, // Use default graphics card
D3D_DRIVER_TYPE_REFERENCE, // Try to create a hardware accelerated device
NULL, // Do not use external software rasterizer module
uCreationFlags, // Device creation flags
NULL, // Try to get greatest feature level available
0, // # of elements in the previous array
D3D11_SDK_VERSION, // SDK version
ppDeviceOut, // Device out
&flOut, // Actual feature level created
ppContextOut ); // Context out
if ( FAILED(hr) )
{
printf( "Reference rasterizer device create failure\n" );
return hr;
}
}
return hr;
}
void GetLocalCacheDir( WCHAR* strPath, UINT cchPath )
{
WCHAR strFolder[MAX_PATH] = L"\\BC6HBC7EncoderDecoder11\\";
SHGetFolderPath( NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath );
wcscat_s( strPath, cchPath, strFolder );
}
HRESULT CreateComputeShaderCached( LPCWSTR pSrcFile, LPCSTR pFunctionName, LPCSTR pProfile,
ID3D11Device* pDevice, ID3D11ComputeShader** ppShaderOut )
{
HRESULT hr;
WCHAR strDirectory[MAX_PATH] = {0};
GetLocalCacheDir( strDirectory, MAX_PATH );
// First check whether our cache dir exists, if not, create it
if ( 0xFFFFFFFF == GetFileAttributes( strDirectory ) )
if ( !CreateDirectory( strDirectory, NULL ) )
return E_FAIL;
// Finds the correct path for the shader file.
// This is only required for this sample to be run correctly from within the Sample Browser,
// in your own projects, these lines could be removed safely
WCHAR str[MAX_PATH];
hr = FindDXSDKShaderFileCch( str, MAX_PATH, pSrcFile );
if ( FAILED(hr) )
{
printf( "Shader file(s) not found. Make sure that BC6HEncode.hlsl, BC6HDecode.hlsl, BC7Encode.hlsl and BC7Decode.hlsl are in directories the exe can find." );
return hr;
}
// Then check whether our cached shader exists,
std::wstring fname( str );
std::wstring::size_type p = fname.rfind( L"\\" );
if ( p == std::wstring::npos )
p = fname.rfind( L"/" );
if ( p != std::wstring::npos )
fname.erase( 0, p + 1 );
fname.erase( fname.rfind( '.' ), fname.length() );
fname += '_';
WCHAR buf[256];
MultiByteToWideChar( CP_ACP, 0, pFunctionName, -1, buf, 256 );
fname += buf;
fname += L".blob";
fname.insert( 0, strDirectory );
ID3DBlob* pBlob = NULL;
again:
if ( 0xFFFFFFFF == GetFileAttributes( &fname[0] ) )
{
// The cached shader file does not exist, then compile it and save it
ID3DBlob* pErrorBlob = NULL;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
hr = D3DX11CompileFromFile( str, NULL, NULL, pFunctionName, pProfile,
dwShaderFlags, NULL, NULL, &pBlob, &pErrorBlob, NULL );
if ( FAILED(hr) )
{
if ( pErrorBlob )
OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() );
SAFE_RELEASE( pErrorBlob );
SAFE_RELEASE( pBlob );
return hr;
}
SAFE_RELEASE( pErrorBlob );
// Write the compiled blob into the cache file
HANDLE hFile = CreateFile( fname.c_str(), FILE_WRITE_DATA, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_FLAG_SEQUENTIAL_SCAN, NULL );
if ( INVALID_HANDLE_VALUE == hFile )
return E_FAIL;
DWORD dwVersion = D3DX11_SDK_VERSION;
DWORD dwBytesWritten = 0;
WriteFile( hFile, &dwVersion, sizeof(dwVersion), &dwBytesWritten, NULL );
WriteFile( hFile, pBlob->GetBufferPointer(), (DWORD)pBlob->GetBufferSize(), &dwBytesWritten, NULL );
CloseHandle( hFile );
} else
{
// The cached shader file exists, load it as shader blob
HANDLE hFile = CreateFile( fname.c_str(), FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL );
if ( INVALID_HANDLE_VALUE == hFile )
return E_FAIL;
DWORD dwVersion = 0;
DWORD dwBytesRead = 0;
// Check if we have an updated hlsl compiler and re-generate the shader cache as necessary
ReadFile( hFile, &dwVersion, sizeof(dwVersion), &dwBytesRead, NULL );
if ( dwVersion != D3DX11_SDK_VERSION )
{
CloseHandle( hFile );
DeleteFile( fname.c_str() );
goto again;
}
D3DCreateBlob( GetFileSize( hFile, NULL ) - sizeof(dwVersion), &pBlob );
ReadFile( hFile, pBlob->GetBufferPointer(), (DWORD)pBlob->GetBufferSize(), &dwBytesRead, NULL );
CloseHandle( hFile );
}
hr = pDevice->CreateComputeShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, ppShaderOut );
#if defined(DEBUG) || defined(PROFILE)
if ( *ppShaderOut )
(*ppShaderOut)->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pFunctionName), pFunctionName );
#endif
SAFE_RELEASE( pBlob );
return hr;
}
void RunComputeShader( ID3D11DeviceContext* pd3dImmediateContext,
ID3D11ComputeShader* pComputeShader,
ID3D11ShaderResourceView** pShaderResourceViews,
UINT uNumSRVs,
ID3D11Buffer* pCBCS,
ID3D11UnorderedAccessView* pUnorderedAccessView,
UINT X, UINT Y, UINT Z )
{
pd3dImmediateContext->CSSetShader( pComputeShader, NULL, 0 );
pd3dImmediateContext->CSSetShaderResources( 0, uNumSRVs, pShaderResourceViews );
pd3dImmediateContext->CSSetUnorderedAccessViews( 0, 1, &pUnorderedAccessView, NULL );
pd3dImmediateContext->CSSetConstantBuffers( 0, 1, &pCBCS );
pd3dImmediateContext->Dispatch( X, Y, Z );
ID3D11UnorderedAccessView* ppUAViewNULL[1] = { NULL };
pd3dImmediateContext->CSSetUnorderedAccessViews( 0, 1, ppUAViewNULL, NULL );
ID3D11ShaderResourceView* ppSRVNULL[3] = { NULL, NULL, NULL };
pd3dImmediateContext->CSSetShaderResources( 0, 3, ppSRVNULL );
ID3D11Buffer* ppBufferNULL[1] = { NULL };
pd3dImmediateContext->CSSetConstantBuffers( 0, 1, ppBufferNULL );
}
HRESULT LoadTextureFromFile( ID3D11Device* pd3dDevice, LPCTSTR lpFileName, DXGI_FORMAT fmtLoadAs, ID3D11Texture2D** ppTextureOut )
{
HRESULT hr = S_OK;
D3DX11_IMAGE_LOAD_INFO img_load_info;
img_load_info.Width = D3DX11_DEFAULT;
img_load_info.Height = D3DX11_DEFAULT;
img_load_info.Depth = D3DX11_DEFAULT;
img_load_info.FirstMipLevel = D3DX11_DEFAULT;
img_load_info.MipLevels = 1;
img_load_info.Usage = D3D11_USAGE_STAGING;
img_load_info.BindFlags = 0;
img_load_info.CpuAccessFlags = D3D11_CPU_ACCESS_READ;
img_load_info.MiscFlags = 0;
img_load_info.Format = fmtLoadAs;
img_load_info.Filter = D3DX11_DEFAULT;
img_load_info.MipFilter = D3DX11_DEFAULT;
img_load_info.pSrcInfo = NULL;
D3DX11CreateTextureFromFile( pd3dDevice, lpFileName, &img_load_info, NULL,
(ID3D11Resource**)(ppTextureOut), &hr );
if ( FAILED( hr ) && (pd3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_11_0) && FileExists( lpFileName ) )
{
// The texture file exists but failed to be loaded, and our device < FL11
// Might be a BC6H or BC7 texture, which needs a FL11 device to load it
ID3D11Device* pDeviceFL11 = NULL;
ID3D11DeviceContext* pContextFL11 = NULL;
UINT uCreationFlags = D3D11_CREATE_DEVICE_SINGLETHREADED;
#if defined(DEBUG) || defined(_DEBUG)
uCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL flIn[] = { D3D_FEATURE_LEVEL_11_0 };
D3D_FEATURE_LEVEL flOut = D3D_FEATURE_LEVEL_9_1;
hr = Dynamic_D3D11CreateDevice( NULL,
D3D_DRIVER_TYPE_NULL,
NULL,
uCreationFlags, // Device creation flags
flIn,
1,
D3D11_SDK_VERSION, // SDK version
&pDeviceFL11, // Device out
&flOut, // Actual feature level created
&pContextFL11 ); // Context out
if ( FAILED( hr ) )
return hr;
// Later this texture will be converted on CPU to a FL10 accessible resource,
// so change the flags to make the texture CPU friendly
img_load_info.BindFlags = 0;
img_load_info.CpuAccessFlags = D3D11_CPU_ACCESS_READ;
img_load_info.Usage = D3D11_USAGE_STAGING;
D3DX11CreateTextureFromFile( pDeviceFL11, lpFileName, &img_load_info, NULL,
(ID3D11Resource**)(ppTextureOut), &hr );
SAFE_RELEASE( pDeviceFL11 );
SAFE_RELEASE( pContextFL11 );
}
return hr;
}
ID3D11Buffer* CreateAndCopyToCPUBuf( ID3D11Device* pDevice, ID3D11DeviceContext* pd3dImmediateContext, ID3D11Buffer* pBuffer )
{
ID3D11Buffer* cpubuf = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
pBuffer->GetDesc( &desc );
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0;
if ( SUCCEEDED(pDevice->CreateBuffer(&desc, NULL, &cpubuf)) )
{
#if defined(DEBUG) || defined(PROFILE)
cpubuf->SetPrivateData( WKPDID_D3DDebugObjectName, sizeof( "CPU" ) - 1, "CPU" );
#endif
pd3dImmediateContext->CopyResource( cpubuf, pBuffer );
}
return cpubuf;
}
HRESULT FindDXSDKShaderFileCch( WCHAR* strDestPath, int cchDest,
LPCWSTR strFilename )
{
if( NULL == strFilename || strFilename[0] == 0 || NULL == strDestPath || cchDest < 10 )
return E_INVALIDARG;
// Get the exe name, and exe path
WCHAR strExePath[MAX_PATH] =
{
0
};
WCHAR strExeName[MAX_PATH] =
{
0
};
WCHAR* strLastSlash = NULL;
GetModuleFileName( NULL, strExePath, MAX_PATH );
strExePath[MAX_PATH - 1] = 0;
strLastSlash = wcsrchr( strExePath, TEXT( '\\' ) );
if( strLastSlash )
{
wcscpy_s( strExeName, MAX_PATH, &strLastSlash[1] );
// Chop the exe name from the exe path
*strLastSlash = 0;
// Chop the .exe from the exe name
strLastSlash = wcsrchr( strExeName, TEXT( '.' ) );
if( strLastSlash )
*strLastSlash = 0;
}
// Search in directories:
// .\
// %EXE_DIR%\..\..\%EXE_NAME%
wcscpy_s( strDestPath, cchDest, strFilename );
if( GetFileAttributes( strDestPath ) != 0xFFFFFFFF )
return true;
swprintf_s( strDestPath, cchDest, L"%s\\..\\..\\%s\\%s", strExePath, strExeName, strFilename );
if( GetFileAttributes( strDestPath ) != 0xFFFFFFFF )
return true;
// On failure, return the file as the path but also return an error code
wcscpy_s( strDestPath, cchDest, strFilename );
return E_FAIL;
}
BOOL FileExists( const WCHAR* pszFilename )
{
FILE *f = NULL;
if ( _wfopen_s( &f, pszFilename, L"rb" ) != 0 )
{
return FALSE;
}
fclose(f);
return TRUE;
}
|
MorrigansWings/GamePhysics
|
PlanetSim/DirectX/Samples/C++/Direct3D11/BC6HBC7EncoderDecoder11/utils.cpp
|
C++
|
apache-2.0
| 18,205
|
define(function (require) {
"use strict";
var fixtures = require("fixtures");
var net = require("net");
QUnit.module("Unit test: net/http/header");
QUnit.test("Can parse HTTP request headers with line break '\\n'", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
});
QUnit.test("Can parse a HTTP request with line break '\\r\\n'", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\r\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
});
QUnit.test("Request header is either separated from body with empty line or the whole payload is header.", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData + "\n\nIGNORE: THIS");
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
QUnit.strictEqual(httpHeader.getHeaderValue("IGNORE"), null, "Ignoring things after empty line.");
});
QUnit.test("Can read valid request header values and they are case insensitive", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.withKeyValuePair("CONTENT-TYPE", "text/xml")
.withKeyValuePair("CONTENT-LENGTH", "1234")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.action, "POST", "The request action could be read.");
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "HOST value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-type"), "text/xml", "CONTENT-TYPE value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-LENGTH"), "1234", "CONTENT-LENGTH value is correct.");
});
QUnit.test("Can read response header values and they are case insensitive", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withRequestLine("HTTP/1.1 418 I'm a teapot")
.withKeyValuePair("CONTENT-TYPE", "coffee")
.withKeyValuePair("CONTENT-LENGTH", "0")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.code, 418, "The response code could be read.");
QUnit.strictEqual(httpHeader.statusMessage, "I'm a teapot", "The response status message could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-type"), "coffee", "CONTENT-TYPE value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-LENGTH"), "0", "CONTENT-LENGTH value is correct.");
});
}
);
|
oddbit/sonosjs
|
test/unit/net/http/header-tests.js
|
JavaScript
|
apache-2.0
| 4,570
|
/*
* Copyright 2015 Mariusz.
*
* 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.watchrabbit.crawler.driver.service;
import com.watchrabbit.crawler.driver.util.LoadingStrategy;
import java.util.List;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author Mariusz
*/
@Service
public class LoaderServiceImpl implements LoaderService {
private static final Logger LOGGER = LoggerFactory.getLogger(LoaderServiceImpl.class);
@Autowired
List<LoadingStrategy> loadingStrategies;
@Override
public void waitFor(RemoteWebDriver driver) {
loadingStrategies.stream()
.filter(strategy -> strategy.shouldWait(driver))
.forEach(strategy -> waitUsing(strategy, driver));
}
private void waitUsing(LoadingStrategy strategy, RemoteWebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, strategy.getWaitTime());
try {
wait.until(strategy.hasFinishedProcessing());
} catch (TimeoutException ex) {
LOGGER.info("Timed out on {}", driver.getCurrentUrl());
}
}
}
|
watchrabbit/rabbit-crawler
|
crawler-driver/src/main/java/com/watchrabbit/crawler/driver/service/LoaderServiceImpl.java
|
Java
|
apache-2.0
| 1,889
|
package com.tinkerpop.blueprints.impls.orient;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.tinkerpop.blueprints.EdgeTestSuite;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.GraphQueryTestSuite;
import com.tinkerpop.blueprints.GraphTestSuite;
import com.tinkerpop.blueprints.IndexTestSuite;
import com.tinkerpop.blueprints.IndexableGraphTestSuite;
import com.tinkerpop.blueprints.KeyIndexableGraphTestSuite;
import com.tinkerpop.blueprints.TestSuite;
import com.tinkerpop.blueprints.TransactionalGraphTestSuite;
import com.tinkerpop.blueprints.VertexQueryTestSuite;
import com.tinkerpop.blueprints.VertexTestSuite;
import com.tinkerpop.blueprints.impls.GraphTest;
import com.tinkerpop.blueprints.util.io.gml.GMLReaderTestSuite;
import com.tinkerpop.blueprints.util.io.graphml.GraphMLReaderTestSuite;
import com.tinkerpop.blueprints.util.io.graphson.GraphSONReaderTestSuite;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test suite for OrientDB graph implementation.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com) (http://orientdb.com)
*/
public abstract class OrientGraphTest extends GraphTest {
protected Map<String, OrientGraph> currentGraphs = new HashMap<String, OrientGraph>();
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testVertexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new VertexTestSuite(this));
printTestPerformance("VertexTestSuite", this.stopWatch());
}
@Test
public void testEdgeTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new EdgeTestSuite(this));
printTestPerformance("EdgeTestSuite", this.stopWatch());
}
@Test
@Ignore
public void testGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphTestSuite(this));
printTestPerformance("GraphTestSuite", this.stopWatch());
}
@Test
public void testVertexQueryTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new VertexQueryTestSuite(this));
printTestPerformance("VertexQueryTestSuite", this.stopWatch());
}
@Test
@Ignore
public void testGraphQueryTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphQueryTestSuite(this));
printTestPerformance("GraphQueryTestSuite", this.stopWatch());
}
@Test
public void testIndexableGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new IndexableGraphTestSuite(this));
printTestPerformance("IndexableGraphTestSuite", this.stopWatch());
}
@Test
public void testIndexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new IndexTestSuite(this));
printTestPerformance("IndexTestSuite", this.stopWatch());
}
@Test
public void testKeyIndexableGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new KeyIndexableGraphTestSuite(this));
printTestPerformance("KeyIndexableGraphTestSuite", this.stopWatch());
}
@Test
public void testTransactionalGraphTestSuite() throws Exception {
try {
this.stopWatch();
doTestSuite(new TransactionalGraphTestSuite(this));
printTestPerformance("TransactionGraphTestSuite", this.stopWatch());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Test
public void testGraphMLReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphMLReaderTestSuite(this));
printTestPerformance("GraphMLReaderTestSuite", this.stopWatch());
}
@Test
public void testGraphSONReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphSONReaderTestSuite(this));
printTestPerformance("GraphSONReaderTestSuite", this.stopWatch());
}
@Test
public void testGMLReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GMLReaderTestSuite(this));
printTestPerformance("GMLReaderTestSuite", this.stopWatch());
}
//
// orientdb specific test
//
@Test
public void testOrientGraphSpecificTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new OrientGraphSpecificTestSuite(this));
printTestPerformance("OrientGraphSpecificTestSuite", this.stopWatch());
}
public Graph generateGraph() {
return generateGraph("graph");
}
public Graph generateGraph(final String graphDirectoryName) {
final String url = getStorageType() + ":" + getWorkingDirectory() + "/" + graphDirectoryName;
OrientGraph graph = currentGraphs.get(url);
if (graph != null) {
if (graph.isClosed()) currentGraphs.remove(url);
else {
ODatabaseRecordThreadLocal.instance().set(graph.getRawGraph());
return graph;
}
}
graph = new OrientGraph(url);
graph.setWarnOnForceClosingTx(false);
graph.setStandardExceptions(true);
currentGraphs.put(url, graph);
return graph;
}
public void doTestSuite(final TestSuite testSuite) throws Exception {
dropGraph("graph");
for (Method method : testSuite.getClass().getDeclaredMethods()) {
if (method.getName().startsWith("test")) {
System.out.println("Testing " + method.getName() + "...");
method.invoke(testSuite);
dropGraph("graph");
}
}
}
@Override
public void dropGraph(final String graphDirectoryName) {
// this is necessary on windows systems: deleting the directory is not enough because it takes a
// while to unlock files
final String graphDirectory = getWorkingDirectory() + "/" + graphDirectoryName;
final String url = getStorageType() + ":" + graphDirectory;
try {
OrientGraph graph = currentGraphs.remove(url);
if (graph == null || graph.isClosed()) graph = new OrientGraph(url);
graph.drop();
} catch (Exception e) {
e.printStackTrace();
}
deleteDirectory(new File(graphDirectory));
}
protected String getWorkingDirectory() {
return this.computeTestDataRoot().getAbsolutePath();
}
public static enum ENV {
DEV,
RELEASE,
CI
}
public static ENV getEnvironment() {
String envName = System.getProperty("orientdb.test.env", "dev").toUpperCase(Locale.ENGLISH);
ENV result = null;
try {
result = ENV.valueOf(envName);
} catch (IllegalArgumentException e) {
}
if (result == null) result = ENV.DEV;
return result;
}
public static String getStorageType() {
if (getEnvironment().equals(ENV.DEV)) return "memory";
return "plocal";
}
}
|
orientechnologies/orientdb
|
graphdb/src/test/java/com/tinkerpop/blueprints/impls/orient/OrientGraphTest.java
|
Java
|
apache-2.0
| 6,805
|
package com.alixander.nutrihawk;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;
import android.content.Context;
public class NutrientInformationJSONSerializer {
private Context mContext;
private String mFilename;
public NutrientInformationJSONSerializer(Context c, String f) {
mContext = c;
mFilename = f;
}
public void saveNutrients(ArrayList<Nutrient> nutrients) throws JSONException, IOException {
JSONArray array = new JSONArray();
for (Nutrient n : nutrients) {
array.put(n.toJSON());
}
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null) {
writer.close();
}
}
}
public ArrayList<Nutrient> loadNutrients() throws IOException, JSONException {
ArrayList<Nutrient> nutrients = new ArrayList<Nutrient>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
for (int i = 0; i < array.length(); i++) {
nutrients.add(new Nutrient(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
} finally {
if (reader != null) {
reader.close();
}
}
return nutrients;
}
}
|
alixander/NutriHawk
|
src/com/alixander/nutrihawk/NutrientInformationJSONSerializer.java
|
Java
|
apache-2.0
| 1,874
|
#include "map/framework.hpp"
#include "software_renderer/cpu_drawer.hpp"
#include "software_renderer/feature_processor.hpp"
#include "software_renderer/frame_image.hpp"
#include "drape_frontend/visual_params.hpp"
#include "geometry/mercator.hpp"
#include "base/string_utils.hpp"
#include "std/exception.hpp"
#include "std/fstream.hpp"
#include "std/iomanip.hpp"
#include "std/iostream.hpp"
#include "std/string.hpp"
#include "3party/gflags/src/gflags/gflags.h"
#pragma mark Define options
//----------------------------------------------------------------------------------------
DEFINE_bool(c, false, "Read places from stdin");
DEFINE_string(place, "", "Define place in format \"lat;lon;zoom\"");
DEFINE_string(outpath, "./", "Path for output files");
DEFINE_string(datapath, "", "Path to data directory");
DEFINE_string(mwmpath, "", "Path to mwm files");
DEFINE_int32(width, 480, "Resulting image width");
DEFINE_int32(height, 640, "Resulting image height");
//----------------------------------------------------------------------------------------
namespace
{
struct Place
{
double lat;
double lon;
int zoom;
int width;
int height;
};
Place ParsePlace(string const & src)
{
Place p;
try
{
strings::SimpleTokenizer token(src, ";");
p.lat = stod(*token);
p.lon = stod(*(++token));
p.zoom = static_cast<int>(stoi(*(++token)));
}
catch (exception & e)
{
cerr << "Error in [" << src << "]: " << e.what() << endl;
exit(1);
}
return p;
}
string FilenameSeq(string const & path)
{
static size_t counter = 0;
stringstream filename;
filename << path << "mapshot" << setw(6) << setfill('0') << counter++ << ".png";
return filename.str();
}
unique_ptr<software_renderer::CPUDrawer> cpuDrawer;
bool IsFrameRendererInitialized()
{
return cpuDrawer != nullptr;
}
void InitFrameRenderer(float visualScale)
{
using namespace software_renderer;
if (cpuDrawer == nullptr)
{
string resPostfix = df::VisualParams::GetResourcePostfix(visualScale);
cpuDrawer = make_unique_dp<CPUDrawer>(CPUDrawer::Params(resPostfix, visualScale));
}
}
void ReleaseFrameRenderer()
{
if (IsFrameRendererInitialized())
cpuDrawer.reset();
}
/// @param center - map center in Mercator
/// @param zoomModifier - result zoom calculate like "base zoom" + zoomModifier
/// if we are have search result "base zoom" calculate that my position and search result
/// will be see with some bottom clamp.
/// if we are't have search result "base zoom" == scales::GetUpperComfortScale() - 1
/// @param pxWidth - result image width.
/// It must be equal render buffer width. For retina it's equal 2.0 * displayWidth
/// @param pxHeight - result image height.
/// It must be equal render buffer height. For retina it's equal 2.0 * displayHeight
/// @param symbols - configuration for symbols on the frame
/// @param image [out] - result image
void DrawFrame(Framework & framework,
m2::PointD const & center, int zoomModifier,
uint32_t pxWidth, uint32_t pxHeight,
software_renderer::FrameSymbols const & symbols,
software_renderer::FrameImage & image)
{
ASSERT(IsFrameRendererInitialized(), ());
int resultZoom = -1;
ScreenBase screen = cpuDrawer->CalculateScreen(center, zoomModifier, pxWidth, pxHeight, symbols, resultZoom);
ASSERT_GREATER(resultZoom, 0, ());
uint32_t const bgColor = drule::rules().GetBgColor(resultZoom);
cpuDrawer->BeginFrame(pxWidth, pxHeight, dp::Extract(bgColor, 255 - (bgColor >> 24)));
m2::RectD renderRect = m2::RectD(0, 0, pxWidth, pxHeight);
m2::RectD selectRect;
m2::RectD clipRect;
double const inflationSize = 24 * cpuDrawer->GetVisualScale();
screen.PtoG(m2::Inflate(renderRect, inflationSize, inflationSize), clipRect);
screen.PtoG(renderRect, selectRect);
uint32_t const tileSize = static_cast<uint32_t>(df::CalculateTileSize(pxWidth, pxHeight));
int const drawScale = df::GetDrawTileScale(screen, tileSize, cpuDrawer->GetVisualScale());
software_renderer::FeatureProcessor doDraw(make_ref(cpuDrawer), clipRect, screen, drawScale);
int const upperScale = scales::GetUpperScale();
framework.GetIndex().ForEachInRect(doDraw, selectRect, min(upperScale, drawScale));
cpuDrawer->Flush();
//cpuDrawer->DrawMyPosition(screen.GtoP(center));
if (symbols.m_showSearchResult)
{
if (!screen.PixelRect().IsPointInside(screen.GtoP(symbols.m_searchResult)))
cpuDrawer->DrawSearchArrow(ang::AngleTo(center, symbols.m_searchResult));
else
cpuDrawer->DrawSearchResult(screen.GtoP(symbols.m_searchResult));
}
cpuDrawer->EndFrame(image);
}
void RenderPlace(Framework & framework, Place const & place, string const & filename)
{
software_renderer::FrameImage frame;
software_renderer::FrameSymbols sym;
sym.m_showSearchResult = false;
// If you are interested why, look at CPUDrawer::CalculateScreen.
// It is almost UpperComfortScale but there is some magic involved.
int constexpr kMagicBaseScale = 17;
DrawFrame(framework, MercatorBounds::FromLatLon(place.lat, place.lon),
place.zoom - kMagicBaseScale, place.width, place.height, sym, frame);
ofstream file(filename.c_str());
file.write(reinterpret_cast<char const *>(frame.m_data.data()), frame.m_data.size());
file.close();
}
} // namespace
int main(int argc, char * argv[])
{
google::SetUsageMessage(
"Generate screenshots of MAPS.ME maps in chosen places, specified by coordinates and zoom.");
google::ParseCommandLineFlags(&argc, &argv, true);
if (!FLAGS_c && FLAGS_place.empty())
{
cerr << "Either -c or -place must be set" << endl;
return 1;
}
if (!FLAGS_datapath.empty())
GetPlatform().SetResourceDir(FLAGS_datapath);
if (!FLAGS_mwmpath.empty())
GetPlatform().SetWritableDirForTests(FLAGS_mwmpath);
try
{
Framework f;
auto processPlace = [&](string const & place)
{
Place p = ParsePlace(place);
p.width = FLAGS_width;
p.height = FLAGS_height;
string const & filename = FilenameSeq(FLAGS_outpath);
RenderPlace(f, p, filename);
cout << "Rendering " << place << " into " << filename << " is finished." << endl;
};
// This magic constant was determined in several attempts.
// It is a scale level, basically, dpi factor. 1 means 90 or 96, it seems,
// and with 1.1 the map looks subjectively better.
InitFrameRenderer(1.1 /* visualScale */);
if (!FLAGS_place.empty())
processPlace(FLAGS_place);
if (FLAGS_c)
{
for (string line; getline(cin, line);)
processPlace(line);
}
ReleaseFrameRenderer();
return 0;
}
catch (exception & e)
{
ReleaseFrameRenderer();
cerr << e.what() << endl;
}
return 1;
}
|
dobriy-eeh/omim
|
mapshot/mapshot.cpp
|
C++
|
apache-2.0
| 6,865
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetCore.Analyzers.Data.ReviewSqlQueriesForSecurityVulnerabilities,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetCore.Analyzers.Data.ReviewSqlQueriesForSecurityVulnerabilities,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Data.UnitTests
{
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.ValueContentAnalysis)]
public class ReviewSQLQueriesForSecurityVulnerabilitiesTests_FlowAnalysis : ReviewSQLQueriesForSecurityVulnerabilitiesTests
{
private static DiagnosticResult GetCSharpResultAt(int line, int column, string invokedSymbol, string containingMethod)
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
.WithArguments(invokedSymbol, containingMethod);
private static DiagnosticResult GetBasicResultAt(int line, int column, string invokedSymbol, string containingMethod)
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
.WithArguments(invokedSymbol, containingMethod);
[Fact]
public async Task FlowAnalysis_LocalWithConstantInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str = """";
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String = """"
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LocalWithConstantAssignment_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str;
str = """";
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String
str = """"
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_ParameterWithConstantAssignment_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string str)
{{
str = """";
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(str As String)
str = """"
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LocalWithAllConstantAssignments_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string nonconst, bool flag)
{{
string str = """", str2 = """", str3 = ""nonempty"";
if (flag) {{ str = str2; }}
else {{ str = str3; }}
Command c = new Command1(str, str);
str = nonconst; // assignment with non-constant value after call should not affect
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(nonconst as String, flag as Boolean)
Dim str = """", str2 = """", str3 = ""nonempty""
If flag Then
str = str2
Else
str = str3
End If
Dim c As New Command1(str, str)
str = nonconst ' assignment with non-constant value after call should not affect
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_ParameterWithAllConstantAssignments_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string nonconst, bool flag, string str)
{{
string str2 = """", str3 = ""nonempty"";
str = """";
if (flag) {{ str = str2; }}
else {{ str = str3; }}
Command c = new Command1(str, str);
str = nonconst; // assignment with non-constant value after call should not affect
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(nonconst as String, flag as Boolean, str as String)
Dim str2 = """", str3 = ""nonempty""
str = """"
If flag Then
str = str2
Else
str = str3
End If
Dim c As New Command1(str, str)
str = nonconst ' assignment with non-constant value after call should not affect
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_ConstantFieldInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
const string _field = """";
void M1()
{{
string str = _field;
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Const _field As String = """"
Sub M1()
Dim str As String = _field
Dim c As New Command1(str, str)
End Sub
End Class");
}
[Fact]
public async Task FlowAnalysis_ConversionsInInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
object obj = """"; // Implicit conversion from string to object
string str = (string)obj; // Explicit conversion from object to string
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Sub M1()
Dim obj As Object = """" ' Implicit conversion from string to object
Dim str As String = DirectCast(obj, String) ' Explicit conversion from object to string
Dim c As New Command1(str, str)
End Sub
End Class");
}
[Fact]
public async Task FlowAnalysis_ImplicitUserDefinedConversionsInInitializer_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
Test(string s)
{{
}}
void M1()
{{
Test t = """"; // Implicit user defined conversion
string str = t; // Implicit user defined conversion
Command c = new Command1(str, str);
}}
public static implicit operator Test(string value)
{{
return null;
}}
public static implicit operator string(Test value)
{{
return null;
}}
}}
",
GetCSharpResultAt(103, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Private Sub New(ByVal s As String)
MyBase.New
End Sub
Private Sub M1()
Dim t As Test = """" ' Implicit user defined conversion
Dim str As String = t ' Implicit user defined conversion
Dim c As New Command1(str, str)
End Sub
Public Shared Widening Operator CType(ByVal value As String) As Test
Return Nothing
End Operator
Public Shared Widening Operator CType(ByVal value As Test) As String
Return Nothing
End Operator
End Class",
GetBasicResultAt(140, 18, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_ExplicitUserDefinedConversionsInInitializer_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
Test(string s)
{{
}}
void M1()
{{
Test t = (Test)""""; // Explicit user defined conversion
string str = (string)t; // Explicit user defined conversion
Command c = new Command1(str, str);
}}
public static explicit operator Test(string value)
{{
return null;
}}
public static explicit operator string(Test value)
{{
return null;
}}
}}
",
GetCSharpResultAt(103, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
Option Strict On
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Private Sub New(ByVal s As String)
MyBase.New
End Sub
Private Sub M1()
Dim t As Test = CType("""", Test) ' Explicit user defined conversion
Dim str As String = CType(t, String) ' Explicit user defined conversion
Dim c As New Command1(str, str)
End Sub
Public Shared Narrowing Operator CType(ByVal value As String) As Test
Return Nothing
End Operator
Public Shared Narrowing Operator CType(ByVal value As Test) As String
Return Nothing
End Operator
End Class",
GetBasicResultAt(142, 18, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_LocalInitializerWithInvocation_Diagnostic()
{
// Currently, we do not do any interprocedural or context sensitive flow analysis.
// So method calls are assumed to always return a MayBe result.
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string command)
{{
}}
}}
class Test
{{
void M1()
{{
string str = SomeString();
Adapter c = new Adapter1(str, str);
}}
string SomeString() => """";
}}
",
GetCSharpResultAt(98, 21, "Adapter1.Adapter1(string cmd, string command)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, command As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String = SomeString()
Dim c As New Adapter1(str, str)
End Sub
Function SomeString()
Return """"
End Function
End Module",
GetBasicResultAt(134, 18, "Sub Adapter1.New(cmd As String, command As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_LocalWithByRefEscape_Diagnostic()
{
// Local/parameter passed by ref/out are assumed to be non-constant after the usage.
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
M2(ref str);
Adapter c = new Adapter1(str, str);
param = """";
M2(ref param);
c = new Adapter1(param, param);
}}
void M2(ref string str)
{{
str = """";
}}
}}
",
GetCSharpResultAt(99, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(103, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String = """"
M2(str)
Dim c As New Adapter1(str, str)
param = """"
M2(param)
c = New Adapter1(param, param)
End Sub
Sub M2(ByRef str as String)
str = """"
End Sub
End Module",
GetBasicResultAt(135, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(139, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_StringEmptyInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str = string.Empty;
Adapter c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String = String.Empty
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_NameOfExpression_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = nameof(param);
Adapter c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String = NameOf(param)
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_NullOrDefaultValue_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str = default(string);
Adapter c = new Adapter1(str, str);
str = null;
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String = Nothing
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_InterpolatedString_Constant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
var local = """";
string str = $""text_{{""literal""}}_{{local}}"";
Adapter c = new Adapter1(str, str);
str = $"""";
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim local = """"
Dim str As String = $""text_{{""literal""}}_{{local}}""
Dim c As New Adapter1(str, str)
str = $""""
c = New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_InterpolatedString_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
var local = """";
string str = $""text_{{""literal""}}_{{local}}_{{param}}""; // param might be non-constant.
Adapter c = new Adapter1(str, str);
}}
}}
",
GetCSharpResultAt(99, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim local = """"
Dim str As String = $""text_{{""literal""}}_{{local}}_{{param}}"" ' param might be non-constant.
Dim c As New Adapter1(str, str)
End Sub
End Module",
GetBasicResultAt(135, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_BinaryAdd_Constant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str1 = """", str2 = """";
string str = str1 + str2 + (str1 + str2);
Adapter c = new Adapter1(str, str);
str += str1;
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str1 = """", str2 = """"
Dim str As String = str1 + str2 + (str1 + str2)
Dim c As New Adapter1(str, str)
str += str1
c = New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_BinaryAdd_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str1 = """";
string str = str1 + param;
Adapter c = new Adapter1(str, str);
str = """";
str += param;
c = new Adapter1(str, str);
}}
}}
",
GetCSharpResultAt(99, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(103, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str1 = """"
Dim str As String = str1 + param
Dim c As New Adapter1(str, str)
str1 = """"
str += param
c = New Adapter1(str, str)
End Sub
End Module",
GetBasicResultAt(135, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(139, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_NullCoalesce_Constant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str1 = """";
string str = str1 ?? param;
Adapter c = new Adapter1(str, str);
str1 = null;
str = str1 ?? """";
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str1 = """"
Dim str As String = If(str1, param)
Dim c As New Adapter1(str, str)
str1 = Nothing
str = If(str1, """")
c = New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_NullCoalesce_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string str1, string param)
{{
string str = str1 ?? """";
Adapter c = new Adapter1(str, str);
str1 = null;
str = str1 ?? param;
c = new Adapter1(str, str);
str1 = param;
str = str1 ?? """";
c = new Adapter1(str, str);
}}
}}
",
GetCSharpResultAt(98, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(102, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(106, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(str1 as String, param As String)
Dim str As String = If(str1, """")
Dim c As New Adapter1(str, str)
str1 = Nothing
str = If(str1, param)
c = New Adapter1(str, str)
str1 = param
str = If(str1, """")
c = New Adapter1(str, str)
End Sub
End Module",
GetBasicResultAt(134, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(138, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(142, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1569")]
public async Task FlowAnalysis_ConditionalAccess_Constant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public readonly string X = """";
}}
class Test
{{
void M1(A a)
{{
string str = a?.X;
Adapter c = new Adapter1(str, str);
a = new A();
str = a?.X;
c = new Adapter1(str, str);
a = null;
str = a?.X;
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public ReadOnly X As String = """"
End Class
Module Test
Sub M1(a As A)
Dim str As String = a?.X
Dim c As New Adapter1(str, str)
a = new A()
str = a?.X
c = New Adapter1(str, str)
a = Nothing
str = a?.X
c = New Adapter1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_ConditionalAccess_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string X;
}}
class Test
{{
void M1(A a, string param)
{{
string str = a?.X;
Adapter c = new Adapter1(str, str);
a = new A();
str = a?.X;
c = new Adapter1(str, str);
a.X = """";
str = a?.X;
c = new Adapter1(str, str);
a.X = param;
str = a?.X;
c = new Adapter1(str, str);
a = null;
str = a?.X; // result is always null, so no diagnostic
c = new Adapter1(str, str);
}}
}}
",
GetCSharpResultAt(103, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(107, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
GetCSharpResultAt(115, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public X As String
End Class
Module Test
Sub M1(a As A, param As String)
Dim str As String = a?.X
Dim c As New Adapter1(str, str)
a = new A()
str = a?.X
c = New Adapter1(str, str)
a.X = """"
str = a?.X
c = New Adapter1(str, str)
a.X = param
str = a?.X
c = New Adapter1(str, str)
a = Nothing
str = a?.X ' result is always null, so no diagnostic
c = New Adapter1(str, str)
End Sub
End Module",
GetBasicResultAt(138, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(142, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
GetBasicResultAt(150, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_WhileLoop_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
while (true)
{{
Adapter c = new Adapter1(str, str);
str = param;
}}
}}
}}
",
GetCSharpResultAt(100, 25, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str = """"
While True
Dim c As New Adapter1(str, str)
str = param
End While
End Sub
End Module",
GetBasicResultAt(135, 22, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_ForLoop_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
for (int i = 0; i < 10; i++)
{{
Adapter c = new Adapter1(str, str);
str = param;
}}
}}
}}
",
GetCSharpResultAt(100, 25, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str = """"
For i As Integer = 0 To 10
Dim c As New Adapter1(str, str)
str = param
Next
End Sub
End Module",
GetBasicResultAt(135, 22, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_ForEachLoop_NonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
foreach (var i in new[] {{ 1, 2, 3 }})
{{
Adapter c = new Adapter1(str, str);
str = param;
}}
}}
}}
",
GetCSharpResultAt(100, 25, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str = """"
For Each i In New Integer() {{1, 2, 3}}
Dim c As New Adapter1(str, str)
str = param
Next
End Sub
End Module",
GetBasicResultAt(135, 22, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_Conditional_Constant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
if (param == """")
{{
Adapter c = new Adapter1(param, param);
}}
Adapter c2 = param == """" ? new Adapter1(param, param) : null;
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
If param = """" Then
Dim c As New Adapter1(param, param)
End If
Dim c2 As Adapter = If(param = """", New Adapter1(param, param), Nothing)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LocalFunctionInvocation_EmptyBody_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str;
str = """";
void MyLocalFunction()
{{
}};
MyLocalFunction(); // This should not change state of 'str'.
Command c = new Command1(str, str);
}}
}}
");
// VB has no local functions.
}
[Fact]
public async Task FlowAnalysis_LocalFunctionInvocation_ChangesCapturedValueToConstant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = param;
void MyLocalFunction()
{{
str = """";
}};
MyLocalFunction(); // This should change state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
// VB has no local functions.
}
[Fact]
public async Task FlowAnalysis_LocalFunctionInvocation_ChangesCapturedValueToNonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Command3 : Command
{{
public Command3(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str, str2 = param;
str = """";
void MyLocalFunction()
{{
str2 = str;
str = param;
}};
MyLocalFunction(); // This should change state of 'str' to be a non-constant and 'str2' to be a constant.
Command c = new Command1(str, str); // Diagnostic
c = new Command2(str2, str2); // No Diagnostic
MyLocalFunction(); // This should change state of 'str2' to also be a non-constant.
c = new Command3(str2, str2); // Diagnostic
}}
}}
",
// Test0.cs(121,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(121, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(125,13): warning CA2100: Review if the query string passed to 'Command3.Command3(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(125, 13, "Command3.Command3(string cmd, string parameter2)", "M1"));
// VB has no local functions.
}
[Fact]
public async Task FlowAnalysis_LocalFunctionInvocation_ChangesCapturedValueContextSensitive_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = """";
void MyLocalFunction(string param2)
{{
str = param2;
}};
MyLocalFunction(str); // This should change state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
// VB has no local functions.
}
[Fact]
public async Task FlowAnalysis_LocalFunctionInvocation_ReturnValueContextSensitive_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = """";
string MyLocalFunction(string param2)
{{
return param2;
}};
str = MyLocalFunction(str); // This should change state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
// VB has no local functions.
}
[Fact]
public async Task FlowAnalysis_LambdaInvocation_EmptyBody_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1()
{{
string str;
str = """";
System.Action myLambda = () =>
{{
}};
myLambda(); // This should not change state of 'str'.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1()
Dim str As String
str = """"
Dim myLambda As System.Action = Sub()
End Sub
myLambda() ' This should not change state of 'str'.
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LambdaInvocation_ChangesCapturedValueToConstant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = param;
System.Action myLambda = () =>
{{
str = """";
}};
myLambda(); // This should change the state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String
str = param
Dim myLambda As System.Action = Sub()
str = """"
End Sub
myLambda() ' This should change the state of 'str' to be a constant.
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LambdaInvocation_ChangesCapturedValueToNonConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Command3 : Command
{{
public Command3(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str, str2 = param;
str = """";
System.Action myLambda = () =>
{{
str2 = str;
str = param;
}};
myLambda(); // This should change state of 'str' to be a non-constant and 'str2' to be a constant.
Command c = new Command1(str, str); // Diagnostic
c = new Command2(str2, str2); // No Diagnostic
myLambda(); // This should change state of 'str2' to also be a non-constant.
c = new Command3(str2, str2); // Diagnostic
}}
}}
",
// Test0.cs(121,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(121, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(125,13): warning CA2100: Review if the query string passed to 'Command3.Command3(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(125, 13, "Command3.Command3(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command3
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String, str2 As String = param
str = """"
Dim myLambda As System.Action = Sub()
str2 = str
str = param
End Sub
myLambda() ' This should change state of 'str' to be a non-constant and 'str2' to be a constant.
Dim c As Command = New Command1(str, str) ' Diagnostic
c = New Command2(str2, str2) ' No Diagnostic
myLambda() ' This should change state of 'str' to also be a non-constant.
c = New Command3(str2, str2) ' Diagnostic
End Sub
End Module",
// Test0.vb(156,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(156, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(160,13): warning CA2100: Review if the query string passed to 'Sub Command3.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(160, 13, "Sub Command3.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_LambdaInvocation_ChangesCapturedValueContextSensitive_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = """";
System.Action<string> myLambda = (string param2) =>
{{
str = param2;
}};
myLambda(str); // This should change state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String
str = """"
Dim myLambda As System.Action(Of String) = Sub(param2 As String)
str = param2
End Sub
myLambda(str) ' This should change state of 'str' to be a constant.
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Fact]
public async Task FlowAnalysis_LambdaInvocation_ReturnValueContextSensitive_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str;
str = """";
System.Func<string, string> myLambda = (string param2) =>
{{
return param2;
}};
str = myLambda(str); // This should change state of 'str' to be a constant.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str As String
str = """"
Dim myLambda As System.Func(Of String, String) = Function (param2 As String)
Return param2
End Function
str = myLambda(str) ' This should change state of 'str' to be a constant.
Dim c As New Command1(str, str)
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsToAnalysis_CopySemanticsForString_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
public string Field;
void M1(Test t, string param)
{{
t.Field = """";
string str = t.Field;
t.Field = param; // This should not affect location/value of 'str'.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Public Field As String
Sub M1(t As Test, param As String)
t.Field = """"
Dim str As String = t.Field
t.Field = param ' This should not affect location/value of 'str'.
Dim c As New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeCopy_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
public string Field;
void M1(Test t)
{{
t.Field = """";
Test t2 = t;
string str = t2.Field;
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Public Field As String
Sub M1(t As Test)
t.Field = """"
Dim t2 As Test = t
Dim str As String = t2.Field
Dim c As New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeCopy_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct Test
{{
public string Field;
void M1(Test t)
{{
t.Field = """";
Test t2 = t;
string str = t2.Field;
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure Test
Public Field As String
Sub M1(t As Test)
t.Field = """"
Dim t2 As Test = t
Dim str As String = t2.Field
Dim c As New Command1(str, str)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeNestingCopy_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
t.a.Field = """";
Test t2 = t;
string str = t2.a.Field;
Command c = new Command1(str, str);
str = param;
A a = t.a;
str = a.Field;
c = new Command1(str, str);
t.a.Field = param;
a = t.a;
A b = a;
t2.a.Field = """";
str = b.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Sub M1(t As Test, param As String)
t.a.Field = """"
Dim t2 As Test = t
Dim str As String = t2.a.Field
Dim c As New Command1(str, str)
str = param
Dim a As A = t.a
str = a.Field
c = New Command1(str, str)
t.a.Field = param
a = t.a
Dim b As A = a
t2.a.Field = """"
str = b.Field
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeNestingCopy_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
t.a.Field = """";
Test t2 = t;
string str = t2.a.Field;
Command c = new Command1(str, str);
str = param;
A a = t.a;
str = a.Field;
c = new Command1(str, str);
t.a.Field = param;
a = t.a;
A b = a;
t2.a.Field = """"; // 't2.a' and 'b' point to different value type objects.
str = b.Field;
c = new Command1(str, str);
}}
}}
",
// Test0.cs(118,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(118, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Class Test
Public a As A
Sub M1(t As Test, param As String)
t.a.Field = """"
Dim t2 As Test = t
Dim str As String = t2.a.Field
Dim c As New Command1(str, str)
str = param
Dim a As A = t.a
str = a.Field
c = New Command1(str, str)
t.a.Field = param
a = t.a
Dim b As A = a
t2.a.Field = """" ' 't2.a' and 'b' point to different value type objects.
str = b.Field
c = New Command1(str, str)
End Sub
End Class",
// Test0.vb(153,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(153, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeNestingCopy_02_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
t.a.Field = """";
Test t2 = new Test();
t = t2; // This should clear out all the data about 't'
string str = t.a.Field;
Command c = new Command1(str, str);
t.a.Field = """";
A a = new A() {{ Field = param }};
t2 = new Test(){{ a = a }};
t = t2; // This should clear out all the data about 't'
str = t.a.Field;
c = new Command1(str, str);
}}
}}
",
// Test0.cs(107,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(107, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Class Test
Public a As A
Sub M1(t As Test, param As String)
t.a.Field = """"
Dim t2 As New Test()
t = t2 ' This should clear out all the data about 't'
Dim str As String = t.a.Field
Dim c As New Command1(str, str)
t.a.Field = """"
Dim a As New A() With {{ .Field = param }}
t2 = New Test() With {{ .a = a }}
t = t2 ' This should clear out all the data about 't'
str = t.a.Field
c = New Command1(str, str)
End Sub
End Class",
// Test0.vb(142,18): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(142, 18, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(149,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(149, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeAllocationAndInitializer_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
t = new Test();
string str = t.a.Field; // Unknown value.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(105,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(105, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal t As Test, ByVal param As String)
t = New Test()
Dim str As String = t.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(143,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeAllocationAndInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
A b = new A();
b.Field = """";
t = new Test() {{ a = b }};
string str = t.a.Field; // 'a' and 'b' point to same object.
Command c = new Command1(str, str);
str = param;
t = new Test() {{ a = {{ Field = """" }} }};
str = t.a.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal t As Test, ByVal param As String)
Dim b As A = New A()
b.Field = """"
t = New Test() With {{.a = b}}
Dim str As String = t.a.Field
Dim c As Command = New Command1(str, str)
str = param
t = New Test() With {{.a = New A() With {{.Field = """", .Field2 = .Field}} }}
str = t.a.Field2
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeAllocationAndInitializer_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
t = new Test();
string str = t.a.Field; // Unknown value.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(105,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(105, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
Public Field2 As String
End Structure
Class Test
Public a As A
Private Sub M1(ByVal t As Test, ByVal param As String)
t = New Test()
Dim str As String = t.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(143,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeAllocationAndInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(Test t, string param)
{{
A b = new A();
b.Field = """";
t = new Test() {{ a = b }};
string str = t.a.Field; // 'a' and 'b' have the same value.
Command c = new Command1(str, str);
t.a.Field = param;
str = param;
t = new Test() {{ a = {{ Field = """" }} }};
str = t.a.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
Public Field2 As String
End Structure
Class Test
Public a As A
Private Sub M1(ByVal t As Test, ByVal param As String)
Dim b As A = New A()
b.Field = """"
t = New Test() With {{.a = b}}
Dim str As String = t.a.Field
Dim c As Command = New Command1(str, str)
str = param
t = New Test() With {{.a = New A() With {{.Field = """", .Field2 = .Field}} }}
str = t.a.Field2
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueTypeAllocationAndInitializer_02_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
void M1(Test t, string param)
{{
A b = new A();
b.Field = """";
t = new Test() {{ a = b }};
Test t2 = t;
string str = t2.a.Field; // 'a' and 'b' have the same value.
Command1 c = new Command1(str, str);
t.a.Field = param;
str = param;
t = new Test() {{ a = {{ Field = """" }} }};
t2 = t;
str = t2.a.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
Public Field2 As String
End Structure
Structure Test
Public a As A
Private Sub M1(ByVal t As Test, ByVal param As String)
Dim b As A = New A()
b.Field = """"
t = New Test() With {{.a = b}}
Dim t2 As Test = t
Dim str As String = t2.a.Field
Dim c As Command = New Command1(str, str)
str = param
t = New Test() With {{.a = New A() With {{.Field = """", .Field2 = .Field}} }}
t2 = t
str = t2.a.Field2
c = New Command1(str, str)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeCollectionInitializer_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(string param)
{{
var list = new System.Collections.Generic.List<string>() {{ """", param }};
string str = list[1];
Command c = new Command1(str, str);
var list2 = new System.Collections.Generic.List<Test>() {{
new Test() {{ a = {{ Field = """" }} }},
new Test() {{ a = {{ Field = param }} }}
}};
str = list2[1].a.Field;
c = new Command1(str, str);
}}
}}
",
// Test0.cs(105,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(105, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(112,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(112, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal param As String)
Dim list = New System.Collections.Generic.List(Of String) From {{"""", param}}
Dim str As String = list(1)
Dim c As Command = New Command1(str, str)
Dim list2 = New System.Collections.Generic.List(Of Test) From {{
New Test() With {{ .a = New A() With {{ .Field = """", .Field2 = .Field }} }},
New Test() With {{ .a = New A() With {{ .Field = param, .Field2 = .Field }} }}
}}
str = list2(1).a.Field2
c = New Command1(str, str)
End Sub
End Class",
// Test0.vb(143,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(151,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(151, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1570")]
public async Task FlowAnalysis_PointsTo_ReferenceTypeCollectionInitializer_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(string param)
{{
var list = new System.Collections.Generic.List<string>() {{ """", param }};
string str = list[0];
Command c = new Command1(str, str);
var list2 = new System.Collections.Generic.List<Test>() {{
new Test() {{ a = {{ Field = """" }} }},
new Test() {{ a = {{ Field = param }} }}
}};
str = list2[0].a.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal param As String)
Dim list = New System.Collections.Generic.List(Of String) From {{"""", param}}
Dim str As String = list(1)
Dim c As Command = New Command1(str, str)
Dim list2 = New System.Collections.Generic.List(Of Test) From {{
New Test() With {{ .a = New A() With {{ .Field = """", .Field2 = .Field }} }},
New Test() With {{ .a = New A() With {{ .Field = param, .Field2 = .Field }} }}
}}
str = list2(1).a.Field2
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_DynamicObjectCreation_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public Test(int i)
{{
}}
public Test(string s)
{{
}}
void M1(Test t, string param, dynamic d)
{{
t = new Test(d);
string str = t.a.Field; // Unknown value.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(112,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(112, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_DynamicObjectCreation_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public Test(int i)
{{
}}
public Test(string s)
{{
}}
void M1(Test t, string param, dynamic d)
{{
A b = new A();
b.Field = """";
t = new Test(d) {{ a = b }};
string str = t.a.Field; // 'a' and 'b' point to same object.
Command c = new Command1(str, str);
str = param;
t = new Test(d) {{ a = {{ Field = """" }} }};
str = t.a.Field;
c = new Command1(str, str);
}}
}}
");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_AnonymousObjectCreation_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
var t = new {{ Field = """", Field2 = param }};
string str = t.Field2; // Unknown value.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(99,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(99, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Private Sub M1(ByVal param As String)
Dim t As New With {{Key .Field1 = """", .Field2 = param }}
Dim str As String = t.Field2 ' Unknown value.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(135,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(135, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task CSharp_FlowAnalysis_PointsTo_AnonymousObjectCreation_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
var t = new {{ Field = """", Field2 = param }};
var t2 = new {{ Field = param, Field2 = """" }};
string str = t.Field;
Command c = new Command1(str, str);
str = param;
t = t2;
str = t.Field2 + t2.Field2;
c = new Command1(str, str);
}}
}}
");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1568")]
public async Task VisualBasic_FlowAnalysis_PointsTo_AnonymousObjectCreation_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Private Sub M1(ByVal param As String)
Dim t As New With {{Key .Field1 = """", .Field2 = .Field1 }}
Dim t2 As New With {{Key .Field1 = param, .Field2 = """" }}
Dim str As String = t.Field2
Dim c As Command = New Command1(str, str)
str = param
t = t2
str = t.Field2 + t2.Field2
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_BaseDerived__Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Base
{{
public string Field;
}}
class Derived : Base
{{
}}
class Test
{{
public Base B;
void M1(string param)
{{
Test t = new Test();
Derived d = new Derived();
d.Field = param;
t.B = new Base();
t.B.Field = """";
t.B = d; // t.B now points to d
string str = t.B.Field; // d.Field has unknown value.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(113,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(113, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Base
Public Field As String
End Class
Class Derived
Inherits Base
End Class
Class Test
Public b As Base
Private Sub M1(ByVal param As String)
Dim t As New Test()
Dim d As New Derived()
d.Field = param
t.B = New Base()
t.B.Field = """"
t.B = d ' t.B now points to d
Dim str As String = t.B.Field ' d.Field has unknown value.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(150,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_BaseDerived_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Base
{{
public string Field;
}}
class Derived : Base
{{
}}
class Test
{{
public Base B;
void M1(string param)
{{
Test t = new Test();
Derived d = new Derived();
d.Field = """";
t.B = new Base();
t.B.Field = param;
t.B = d; // t.B now points to d
string str = t.B.Field; // d.Field is empty string.
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Base
Public Field As String
End Class
Class Derived
Inherits Base
End Class
Class Test
Public b As Base
Private Sub M1(ByVal param As String)
Dim t As New Test()
Dim d As New Derived()
d.Field = """"
t.B = New Base()
t.B.Field = param
t.B = d ' t.B now points to d
Dim str As String = t.B.Field ' d.Field is empty string.
Dim c As Command = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_BaseDerived_IfStatement_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Base
{{
public string Field;
}}
class Derived : Base
{{
}}
class Test
{{
public Base B;
void M1(string param)
{{
Test t = new Test();
t.B = new Base();
t.B.Field = param;
if (param != null)
{{
Derived d = new Derived();
d.Field = param;
t.B = d; // t.B now points to d
}}
else
{{
Base b = new Base();
b.Field = """";
t.B = b; // t.B now points to b
}}
string str = t.B.Field; // t.B now points to either b or d, but d.Field could be an unknown value (param) in one code path.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(123,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(123, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Base
Public Field As String
End Class
Class Derived
Inherits Base
End Class
Class Test
Public b As Base
Private Sub M1(ByVal param As String)
Dim t As New Test()
t.B = New Base()
t.B.Field = param
If param IsNot Nothing Then
Dim d As New Derived()
d.Field = param
t.B = d ' t.B now points to d
Else
Dim b As New Base()
b.Field = """"
t.B = b ' t.B now points to b
End If
Dim str As String = t.B.Field ' t.B now points to either b or d, but d.Field could be an unknown value (param) in one code path.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(156,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(156, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_BaseDerived_IfStatement_02_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Base
{{
public string Field;
}}
class Derived : Base
{{
}}
class Test
{{
public Base B;
void M1(string param, string param2)
{{
Test t = new Test();
t.B = new Base();
t.B.Field = param;
if (param != null)
{{
Derived d = new Derived();
d.Field = """";
t.B = d; // t.B now points to d
if (param2 != null)
{{
d.Field = param; // t.B.Field is unknown in this code path.
}}
}}
else
{{
Base b = new Base();
b.Field = """";
t.B = b; // t.B now points to b
}}
string str = t.B.Field; // t.B now points to either b or d, but d.Field could be an unknown value (param) in one code path.
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(127,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(127, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Base
Public Field As String
End Class
Class Derived
Inherits Base
End Class
Class Test
Public b As Base
Private Sub M1(ByVal param As String, ByVal param2 As String)
Dim t As New Test()
t.B = New Base()
t.B.Field = param
If param IsNot Nothing Then
Dim d As New Derived()
d.Field = """"
t.B = d ' t.B now points to d
If param2 IsNot Nothing Then
d.Field = param ' t.B.Field is unknown in this code path.
End If
Else
Dim b As New Base()
b.Field = """"
t.B = b ' t.B now points to b
End If
Dim str As String = t.B.Field ' t.B now points to either b or d, but d.Field could be an unknown value (param) in one code path.
Dim c As Command = New Command1(str, str)
End Sub
End Class",
// Test0.vb(159,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(159, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_BaseDerived_IfStatement_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Base
{{
public string Field;
}}
class Derived : Base
{{
}}
class Test
{{
public Base B;
void M1(string param)
{{
Test t = new Test();
t.B = new Base();
t.B.Field = param;
if (param != null)
{{
Derived d = new Derived();
d.Field = """";
t.B = d; // t.B now points to d
}}
else
{{
Base b = new Base();
b.Field = """";
t.B = b; // t.B now points to b
}}
string str = t.B.Field; // t.B now points to either b or d, both of which have .Field = """"
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Base
Public Field As String
End Class
Class Derived
Inherits Base
End Class
Class Test
Public b As Base
Private Sub M1(ByVal param As String)
Dim t As New Test()
t.B = New Base()
t.B.Field = param
If param IsNot Nothing Then
Dim d As New Derived()
d.Field = """"
t.B = d ' t.B now points to d
Else
Dim b As New Base()
b.Field = """"
t.B = b ' t.B now points to b
End If
Dim str As String = t.B.Field ' t.B now points to either b or d, both of which have .Field = """"
Dim c As Command = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_ThisInstanceReference_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public string Field;
void M1(string param)
{{
string str = this.a.Field; // Unknown value.
Command c = new Command1(str, str);
str = this.Field; // Unknown value.
c = new Command1(str, str);
}}
}}
",
// Test0.cs(106,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(106, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(109,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(109, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim str As String = Me.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
str = Me.Field ' Unknown value.
c = New Command1(str, str)
End Sub
End Class",
// Test0.vb(143,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(146,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(146, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_ThisInstanceReference_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public string Field;
void M1(string param)
{{
A b = new A();
b.Field = """";
this.a = b;
string str = this.a.Field;
Command1 c = new Command1(str, str);
str = param;
this.a = new A() {{ Field = """" }};
str = this.a.Field;
c = new Command1(str, str);
str = param;
Field = """";
str = this.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
Public Field2 As String
End Class
Class Test
Public a As A
Public Field As String
Public Field2 As String
Private Sub M1(ByVal param As String)
Dim b As A = New A()
b.Field = """"
Me.a = b
Dim str As String = a.Field
Dim c As New Command1(str, str)
str = param
Me.a = New A() With {{.Field = """", .Field2 = .Field}}
str = a.Field2
c = New Command1(str, str)
str = param
Me.Field = """"
Field2 = Field
str = Me.Field2
c = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_ThisInstanceReference_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
string str = this.a.Field; // Unknown value.
Command c = new Command1(str, str);
str = this.Field; // Unknown value.
c = new Command1(str, str);
}}
}}
",
// Test0.cs(106,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(106, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(109,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(109, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
Public Field2 As String
End Structure
Structure Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim str As String = Me.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
str = Me.Field ' Unknown value.
c = New Command1(str, str)
End Sub
End Structure",
// Test0.vb(143,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(146,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(146, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_ThisInstanceReference_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
A b = new A();
b.Field = """";
this.a = b;
string str = this.a.Field;
Command1 c = new Command1(str, str);
str = param;
this.a = new A() {{ Field = """" }};
str = this.a.Field;
c = new Command1(str, str);
str = param;
Field = """";
str = this.Field;
c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
Public Field2 As String
End Structure
Structure Test
Public a As A
Public Field As String
Public Field2 As String
Private Sub M1(ByVal param As String)
Dim b As A = New A()
b.Field = """"
Me.a = b
Dim str As String = a.Field
Dim c As New Command1(str, str)
str = param
Me.a = New A() With {{.Field = """", .Field2 = .Field}}
str = a.Field2
c = New Command1(str, str)
str = param
Me.Field = """"
Field2 = Field
str = Me.Field2
c = New Command1(str, str)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_InvocationInstanceReceiver_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public string Field;
void M1(string param)
{{
this.a.Field = """";
this.M2();
string str = this.a.Field; // Unknown value.
Command c = new Command1(str, str);
Test t = new Test();
t.Field = """";
t.M2();
str = t.Field; // Unknown value.
c = new Command1(str, str);
}}
public void M2()
{{
}}
}}
",
// Test0.cs(108,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(108, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Me.a.Field = """"
Me.M2()
Dim str As String = Me.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
Dim t As New Test()
t.Field = """"
t.M2()
str = Me.Field ' Unknown value.
c = New Command1(str, str)
End Sub
Public Sub M2()
End Sub
End Class",
// Test0.vb(144,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(144, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_InvocationInstanceReceiver_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
this.a.Field = """";
this.M2();
string str = this.a.Field; // Unknown value.
Command c = new Command1(str, str);
Test t = new Test();
t.Field = """";
t.M2();
str = t.Field; // Unknown value.
c = new Command1(str, str);
}}
public void M2()
{{
}}
}}
",
// Test0.cs(108,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(108, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Structure Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Me.a.Field = """"
Me.M2()
Dim str As String = Me.a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
Dim t As New Test()
t.Field = """"
t.M2()
str = Me.Field ' Unknown value.
c = New Command1(str, str)
End Sub
Public Sub M2()
End Sub
End Structure",
// Test0.vb(144,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(144, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_Argument_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public string Field;
void M1(string param)
{{
Test t = new Test();
t.Field = """";
M2(t);
string str = t.Field; // Unknown value.
Command c = new Command1(str, str);
t.a.Field = """";
this.M2(t);
str = t.a.Field; // Unknown value.
c = new Command1(str, str);
t.a.Field = """";
this.M3(ref t);
str = t.a.Field; // Unknown value.
c = new Command1(str, str);
}}
public void M2(Test t)
{{
}}
public void M3(ref Test t)
{{
}}
}}
",
// Test0.cs(109,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(109, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 13, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(119,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(119, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim t As New Test()
t.Field = """"
M2(t)
Dim str As String = t.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
t.a.Field = """"
Me.M2(t)
str = t.a.Field ' Unknown value.
c = New Command1(str, str)
t.a.Field = """"
Me.M3(t)
str = t.a.Field ' Unknown value.
c = New Command1(str, str)
End Sub
Public Sub M2(t As Test)
End Sub
Public Sub M3(ByRef t as Test)
End Sub
End Class",
// Test0.vb(145,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(145, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(155,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(155, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceType_ThisArgument_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
public string Field;
void M1(string param)
{{
Test t = new Test();
this.a.Field = """";
t.M2(this);
string str = a.Field; // Unknown value.
Command c = new Command1(str, str);
this.Field = """";
t.M2(this);
str = Field; // Unknown value.
c = new Command1(str, str);
}}
public void M2(Test t)
{{
}}
}}
",
// Test0.cs(109,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(109, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 13, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim t as New Test()
Me.a.Field = """"
t.M2(Me)
Dim str As String = a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
Me.Field = """"
t.M2(Me)
str = Field ' Unknown value.
c = New Command1(str, str)
End Sub
Public Sub M2(t As Test)
End Sub
End Class",
// Test0.vb(145,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(145, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_Argument_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
Test t = new Test();
t.Field = """";
M2(t); // Passing by value cannot change contents of a value type.
string str = t.Field;
Command c = new Command1(str, str);
t.a.Field = """";
this.M2(t); // Passing by value cannot change contents of a value type.
str = t.a.Field;
c = new Command1(str, str);
}}
public void M2(Test t)
{{
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Structure Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim t As New Test()
t.Field = """"
M2(t) ' Passing by value cannot change contents of a value type.
Dim str As String = t.Field
Dim c As Command = New Command1(str, str)
t.a.Field = """"
Me.M2(t) ' Passing by value cannot change contents of a value type.
str = t.a.Field
c = New Command1(str, str)
End Sub
Public Sub M2(t As Test)
End Sub
Public Sub M3(ByRef t as Test)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_Argument_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
Test t = new Test();
t.a.Field = """";
this.M2(ref t);
string str = t.a.Field; // Passing by ref can change contents of a value type.
Command c = new Command1(str, str);
}}
public void M2(ref Test t)
{{
}}
}}
",
// Test0.cs(109,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(109, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Structure Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim t As New Test()
t.a.Field = """"
Me.M2(t) ' Passing by ref can change contents of a value type.
Dim str As String = t.a.Field
Dim c As Command = New Command1(str, str)
End Sub
Public Sub M2(ByRef t as Test)
End Sub
End Structure",
// Test0.vb(145,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(145, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ValueType_ThisArgument_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string Field;
}}
struct Test
{{
public A a;
public string Field;
void M1(string param)
{{
Test t = new Test();
this.a.Field = """";
t.M2(this); // Passing by value cannot change contents of a value type.
string str = a.Field;
Command c = new Command1(str, str);
this.Field = """";
t.M2(this); // Passing by value cannot change contents of a value type.
str = Field;
c = new Command1(str, str);
}}
public void M2(Test t)
{{
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public Field As String
End Structure
Structure Test
Public a As A
Public Field As String
Private Sub M1(ByVal param As String)
Dim t as New Test()
Me.a.Field = """"
t.M2(Me)
Dim str As String = a.Field ' Unknown value.
Dim c As Command = New Command1(str, str)
Me.Field = """"
t.M2(Me)
str = Field ' Unknown value.
c = New Command1(str, str)
End Sub
Public Sub M2(t As Test)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ConstantArrayElement_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string[] strArray)
{{
strArray[0] = """";
string str = strArray[0];
Adapter c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(strArray As String())
strArray(0) = """"
Dim str As String = strArray(0)
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_NonConstantArrayElement_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string[] strArray, string param)
{{
strArray[0] = param;
string str = strArray[0];
Adapter c = new Adapter1(str, str);
}}
}}
",
// Test0.cs(99,21): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(99, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(strArray As String(), param As String)
strArray(0) = param
Dim str As String = strArray(0)
Dim c As New Adapter1(str, str)
End Sub
End Module",
// Test0.vb(135,18): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(135, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1577")]
public async Task FlowAnalysis_PointsTo_ConstantArrayElement_NonConstantIndex_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string[] strArray, int i)
{{
strArray[i] = """";
string str = strArray[i];
Adapter c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(strArray As String(), i As Integer)
strArray(i) = """"
Dim str As String = strArray(i)
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_NonConstantArrayElement_NonConstantIndex_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string[] strArray, int i, int j)
{{
strArray[i] = """";
i = j; // We don't know value of 'i' now
string str = strArray[i]; // Unknown value
Adapter c = new Adapter1(str, str);
}}
}}
",
// Test0.cs(100,21): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(100, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(strArray As String(), i As Integer, j As Integer)
strArray(i) = """"
i = j
Dim str As String = strArray(i)
Dim c As New Adapter1(str, str)
End Sub
End Module",
// Test0.vb(136,18): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(136, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ArrayInitializer_ConstantArrayElement_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string[] strArray = new string[] {{ """", param }} ;
string str = strArray[0];
Adapter c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim strArray As String() = New String() {{ """", param }}
Dim str As String = strArray(0)
Dim c As New Adapter1(str, str)
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ArrayInitializer_NonConstantArrayElement_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string[] strArray = new string[] {{ """", param }} ;
string str = strArray[1];
Adapter c = new Adapter1(str, str);
}}
}}
",
GetCSharpResultAt(99, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim strArray As String() = New String() {{ """", param }}
Dim str As String = strArray(1)
Dim c As New Adapter1(str, str)
End Sub
End Module",
GetBasicResultAt(135, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ConstantArrayElement_ArrayFieldInReferenceType_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string[] StringArrayA;
}}
class Test
{{
public A a;
public string[] StringArray;
void M1(Test t, string[] strArray1, string[] strArray2, string[] strArray3)
{{
t.StringArray = strArray1;
strArray1[0] = """";
string str = t.StringArray[0];
Adapter c = new Adapter1(str, str);
strArray2[1] = """";
t.StringArray = strArray2;
str = t.StringArray[1];
c = new Adapter1(str, str);
strArray3[1000] = """";
t.a.StringArrayA = strArray3;
Test t2 = t;
str = t2.a.StringArrayA[1000];
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public StringArrayA As String()
End Class
Class Test
Public a As A
Public StringArray As String()
Sub M1(t As Test, strArray1 As String(), strArray2 As String(), strArray3 As String())
t.StringArray = strArray1
strArray1(0) = """"
Dim str As String = t.StringArray(0)
Dim c As New Adapter1(str, str)
strArray2(1) = """"
t.StringArray = strArray2
str = t.StringArray(1)
c = New Adapter1(str, str)
strArray3(1000) = """"
t.a.StringArrayA = strArray3
Dim t2 As Test = t
str = t2.a.StringArrayA(1000)
c = New Adapter1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_NonConstantArrayElement_ArrayFieldInReferenceType_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string[] StringArrayA;
}}
class Test
{{
public A a;
public string[] StringArray;
void M1(Test t, string[] strArray1, string[] strArray2, string[] strArray3, string param)
{{
t.StringArray = strArray1;
string str = t.StringArray[1];
Adapter c = new Adapter1(str, str);
strArray2[1] = """";
t.StringArray = strArray2;
strArray2[1] = param;
str = t.StringArray[1];
c = new Adapter1(str, str);
strArray3[1000] = """";
t.a.StringArrayA = strArray3;
Test t2 = t;
string[] strArray4 = strArray3;
strArray4[1000] = param;
str = t2.a.StringArrayA[1000];
c = new Adapter1(str, str);
}}
}}
",
// Test0.cs(107,21): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(107, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
// Test0.cs(113,13): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(113, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
// Test0.cs(121,13): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(121, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public StringArrayA As String()
End Class
Class Test
Public a As A
Public StringArray As String()
Sub M1(t As Test, strArray1 As String(), strArray2 As String(), strArray3 As String(), param As String)
t.StringArray = strArray1
Dim str As String = t.StringArray(0)
Dim c As New Adapter1(str, str)
strArray2(1) = """"
t.StringArray = strArray2
strArray2(1) = param
str = t.StringArray(1)
c = New Adapter1(str, str)
strArray3(1000) = """"
t.a.StringArrayA = strArray3
Dim t2 As Test = t
Dim strArray4 As String() = strArray3
strArray4(1000) = param
str = t2.a.StringArrayA(1000)
c = New Adapter1(str, str)
End Sub
End Class",
// Test0.vb(142,18): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(142, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(148,13): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(148, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(156,13): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(156, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ConstantArrayElement_ArrayFieldInValueType_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string[] StringArrayA;
}}
struct Test
{{
public A a;
public string[] StringArray;
void M1(Test t, string[] strArray1, string[] strArray2, string[] strArray3)
{{
t.StringArray = strArray1;
strArray1[0] = """";
string str = t.StringArray[0];
Adapter c = new Adapter1(str, str);
strArray2[1] = """";
t.StringArray = strArray2;
str = t.StringArray[1];
c = new Adapter1(str, str);
strArray3[1000] = """";
t.a.StringArrayA = strArray3;
Test t2 = t;
str = t2.a.StringArrayA[1000];
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public StringArrayA As String()
End Structure
Structure Test
Public a As A
Public StringArray As String()
Sub M1(t As Test, strArray1 As String(), strArray2 As String(), strArray3 As String())
t.StringArray = strArray1
strArray1(0) = """"
Dim str As String = t.StringArray(0)
Dim c As New Adapter1(str, str)
strArray2(1) = """"
t.StringArray = strArray2
str = t.StringArray(1)
c = New Adapter1(str, str)
strArray3(1000) = """"
t.a.StringArrayA = strArray3
Dim t2 As Test = t
str = t2.a.StringArrayA(1000)
c = New Adapter1(str, str)
End Sub
End Structure");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_NonConstantArrayElement_ArrayFieldInValueType_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
struct A
{{
public string[] StringArrayA;
}}
struct Test
{{
public A a;
public string[] StringArray;
void M1(Test t, string[] strArray1, string[] strArray2, string[] strArray3, string param)
{{
t.StringArray = strArray1;
string str = t.StringArray[1];
Adapter c = new Adapter1(str, str);
strArray2[1] = """";
t.StringArray = strArray2;
strArray2[1] = param;
str = t.StringArray[1];
c = new Adapter1(str, str);
strArray3[1000] = """";
t.a.StringArrayA = strArray3;
Test t2 = t;
string[] strArray4 = strArray3;
strArray4[1000] = param;
str = t2.a.StringArrayA[1000];
c = new Adapter1(str, str);
}}
}}
",
// Test0.cs(107,21): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(107, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
// Test0.cs(113,13): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(113, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
// Test0.cs(121,13): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(121, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Structure A
Public StringArrayA As String()
End Structure
Structure Test
Public a As A
Public StringArray As String()
Sub M1(t As Test, strArray1 As String(), strArray2 As String(), strArray3 As String(), param As String)
t.StringArray = strArray1
Dim str As String = t.StringArray(0)
Dim c As New Adapter1(str, str)
strArray2(1) = """"
t.StringArray = strArray2
strArray2(1) = param
str = t.StringArray(1)
c = New Adapter1(str, str)
strArray3(1000) = """"
t.a.StringArrayA = strArray3
Dim t2 As Test = t
Dim strArray4 As String() = strArray3
strArray4(1000) = param
str = t2.a.StringArrayA(1000)
c = New Adapter1(str, str)
End Sub
End Structure",
// Test0.vb(142,18): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(142, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(148,13): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(148, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(156,13): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(156, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ConstantArrayElement_IndexerFieldInReferenceType_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
private string[] _stringArray;
public string this[int i]
{{
get => _stringArray[i];
set => _stringArray[i] = value;
}}
}}
class Test
{{
public A a;
private string[] _stringArray;
public string this[int i]
{{
get => _stringArray[i];
set => _stringArray[i] = value;
}}
void M1(Test t, string[] strArray1)
{{
strArray1[0] = """";
t[0] = strArray1[0];
string str = t[0];
Adapter c = new Adapter1(str, str);
A a = new A();
t.a = a;
Test t2 = t;
a[1000] = """";
str = t2.a[1000];
c = new Adapter1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Private _stringArray As String()
Public Property StringArray(i As Integer) As String
Get
Return _stringArray(i)
End Get
Set(value As String)
_stringArray(i) = value
End Set
End Property
End Class
Class Test
Public a As A
Private _stringArray As String()
Public Property StringArray(i As Integer) As String
Get
Return _stringArray(i)
End Get
Set(value As String)
_stringArray(i) = value
End Set
End Property
Sub M1(t As Test, strArray1 As String())
strArray1(0) = """"
t.StringArray(0) = strArray1(0)
Dim str As String = t.StringArray(0)
Dim c As New Adapter1(str, str)
Dim a As new A()
t.a = a
Dim t2 As Test = t
a.StringArray(1000) = """"
str = t2.a.StringArray(1000)
c = New Adapter1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_NonConstantArrayElement_IndexerFieldInReferenceType_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Adapter1 : Adapter
{{
public Adapter1(string cmd, string parameter2)
{{
}}
}}
class A
{{
private string[] _stringArray;
public string this[int i]
{{
get => _stringArray[i];
set => _stringArray[i] = value;
}}
}}
class Test
{{
public A a;
private string[] _stringArray;
public string this[int i]
{{
get => _stringArray[i];
set => _stringArray[i] = value;
}}
void M1(Test t, string[] strArray1, string param)
{{
t[0] = """";
string str = t[1];
Adapter c = new Adapter1(str, str);
A a = new A();
t.a = a;
Test t2 = t;
a[1000] = param;
str = t2.a[1000];
c = new Adapter1(str, str);
}}
}}
",
// Test0.cs(119,21): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(119, 21, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"),
// Test0.cs(126,13): warning CA2100: Review if the query string passed to 'Adapter1.Adapter1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(126, 13, "Adapter1.Adapter1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Adapter1
Inherits Adapter
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Private _stringArray As String()
Public Property StringArray(i As Integer) As String
Get
Return _stringArray(i)
End Get
Set(value As String)
_stringArray(i) = value
End Set
End Property
End Class
Class Test
Public a As A
Private _stringArray As String()
Public Property StringArray(i As Integer) As String
Get
Return _stringArray(i)
End Get
Set(value As String)
_stringArray(i) = value
End Set
End Property
Sub M1(t As Test, strArray1 As String(), param As String)
t.StringArray(0) = """"
Dim str As String = t.StringArray(1)
Dim c As New Adapter1(str, str)
Dim a As new A()
t.a = a
Dim t2 As Test = t
a.StringArray(1000) = param
str = t2.a.StringArray(1000)
c = New Adapter1(str, str)
End Sub
End Class",
// Test0.vb(159,18): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(159, 18, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(166,13): warning CA2100: Review if the query string passed to 'Sub Adapter1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(166, 13, "Sub Adapter1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeArray_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(string param)
{{
A b = new A() {{ Field = """" }};
A c = new A() {{ Field = param }};
Test t = new Test() {{ a = c }};
Test[] testArray = new Test[] {{ new Test() {{ a = b }}, t }};
string str = testArray[1].a.Field; // testArray[1].a points to c.
Command cmd = new Command1(str, str);
b.Field = param;
str = testArray[0].a.Field; // testArray[0].a points to b.
cmd = new Command1(str, str);
}}
}}
",
// Test0.cs(108,23): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(108, 23, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(112,15): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(112, 15, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal param As String)
Dim b As A = New A() With {{.Field = """"}}
Dim c As A = New A() With {{.Field = param}}
Dim t As Test = New Test() With {{.a = c}}
Dim testArray As Test() = New Test() {{New Test() With {{.a = b}}, t}}
Dim str As String = testArray(1).a.Field ' testArray[1].a points to c.
Dim cmd As Command = New Command1(str, str)
b.Field = param
str = testArray(0).a.Field ' testArray[0].a points to b.
cmd = New Command1(str, str)
End Sub
End Class
",
// Test0.vb(144,30): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(144, 30, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(148,15): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(148, 15, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_ReferenceTypeArray_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class A
{{
public string Field;
}}
class Test
{{
public A a;
void M1(string param)
{{
A b = new A() {{ Field = """" }};
A c = new A() {{ Field = param }};
Test t = new Test() {{ a = c }};
Test[] testArray = new Test[] {{ new Test() {{ a = b }}, t }};
string str = testArray[0].a.Field; // testArray[0].a points to b.
Command cmd = new Command1(str, str);
c.Field = b.Field;
str = testArray[1].a.Field; // testArray[1].a points to c.
cmd = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class A
Public Field As String
End Class
Class Test
Public a As A
Private Sub M1(ByVal param As String)
Dim b As A = New A() With {{.Field = """"}}
Dim c As A = New A() With {{.Field = param}}
Dim t As Test = New Test() With {{.a = c}}
Dim testArray As Test() = New Test() {{New Test() With {{.a = b}}, t}}
Dim str As String = testArray(0).a.Field ' testArray[0].a points to b.
Dim cmd As Command = New Command1(str, str)
c.Field = b.Field
str = testArray(1).a.Field ' testArray[1].a points to c.
cmd = New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_AutoGeneratedProperty_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
public string AutoGeneratedProperty {{ get; set; }}
void M1()
{{
AutoGeneratedProperty = """";
string str = AutoGeneratedProperty;
Command c = new Command1(str, str);
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Public Property AutoGeneratedProperty As String
Sub M1()
AutoGeneratedProperty = """"
Dim str As String = AutoGeneratedProperty
Dim c As New Command1(str, str)
End Sub
End Class");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PointsToAnalysis)]
[Fact]
public async Task FlowAnalysis_PointsTo_CustomProperty_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
string _value;
string _value2;
public string MyProperty {{ get => _value; set => _value = value + _value2; }}
void M1(string param)
{{
_value2 = param;
MyProperty = """";
string str = MyProperty;
Command c = new Command1(str, str);
}}
}}
",
// Test0.cs(104,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(104, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Test
Private _value, _value2 As String
Public Property MyProperty As String
Get
Return _value
End Get
Set(value As String)
_value = value + _value2
End Set
End Property
Sub M1(param As String)
_value2 = param
MyProperty = """"
Dim str As String = MyProperty
Dim c As New Command1(str, str)
End Sub
End Class",
// Test0.vb(146,18): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(146, 18, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithConstant_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
if (param == """")
{{
Command c = new Command1(param, param);
}}
if ("""" == param)
{{
Command c2 = new Command1(param, param);
}}
if (param != """")
{{
}}
else
{{
Command c3 = new Command1(param, param);
}}
if ("""" != param)
{{
}}
else
{{
Command c4 = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
If param = """" Then
Dim c As New Command1(param, param)
End If
If """" = param Then
Dim c2 As New Command1(param, param)
End If
If param <> """" Then
Else
Dim c3 As New Command1(param, param)
End If
If """" <> param Then
Else
Dim c4 As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithConstant_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
if (param != """")
{{
Command c = new Command1(param, param);
}}
if ("""" != param)
{{
Command c2 = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(99,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(99, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(104,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(104, 26, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
If param <> """" Then
Dim c As New Command1(param, param)
End If
If """" <> param Then
Dim c2 As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(134,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(134, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(138,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(138, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithConstant_WithNegation_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
if (!(param != """"))
{{
Command c = new Command1(param, param);
}}
if (!("""" != param))
{{
Command c2 = new Command1(param, param);
}}
if (!!(param != """"))
{{
}}
else
{{
Command c3 = new Command1(param, param);
}}
if (!("""" == param))
{{
}}
else
{{
Command c4 = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
If Not (param <> """") Then
Dim c As New Command1(param, param)
End If
If Not ("""" <> param) Then
Dim c2 As New Command1(param, param)
End If
If Not Not (param <> """") Then
Else
Dim c3 As New Command1(param, param)
End If
If Not ("""" = param) Then
Else
Dim c4 As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithConstant_WithNegation_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
if (!(param == """"))
{{
Command c = new Command1(param, param);
}}
if (!!("""" != param))
{{
Command c2 = new Command1(param, param);
}}
if (!("""" != param))
{{
}}
else
{{
Command c3 = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(99,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(99, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(104,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(104, 26, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(112,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(112, 26, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
If Not (param = """") Then
Dim c As New Command1(param, param)
End If
If Not Not ("""" <> param) Then
Dim c2 As New Command1(param, param)
End If
If Not ("""" <> param) Then
Else
Dim c3 As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(134,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(134, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(138,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(138, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(143,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(143, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithLocal_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
if (param == str)
{{
Command c = new Command1(param, param);
}}
if (str == param)
{{
Command c2 = new Command1(param, param);
}}
if (param != str)
{{
}}
else
{{
Command c3 = new Command1(param, param);
}}
if (str != param)
{{
}}
else
{{
Command c4 = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim str = """"
If param = str Then
Dim c As New Command1(param, param)
End If
If str = param Then
Dim c2 As New Command1(param, param)
End If
If param <> str Then
Else
Dim c3 As New Command1(param, param)
End If
If str <> param Then
Else
Dim c4 As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ParameterComparedWithLocal_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = flag ? param2 : """";
string str2 = param2;
if (param == str)
{{
Command c = new Command1(param, param);
}}
if (str2 == param)
{{
Command c2 = new Command1(param, param);
}}
if (param != str2)
{{
}}
else
{{
Command c3 = new Command1(param, param);
}}
if (str != param)
{{
}}
else
{{
Command c4 = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(101,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(101, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(106,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(106, 26, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(114,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(114, 26, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(122,26): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(122, 26, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = If(flag, param2, """")
Dim str2 = param2
If param = str Then
Dim c As New Command1(param, param)
End If
If str2 = param Then
Dim c2 As New Command1(param, param)
End If
If param <> str2 Then
Else
Dim c3 As New Command1(param, param)
End If
If str <> param Then
Else
Dim c4 As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(136,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(136, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(140,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(140, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(145,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(145, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,23): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 23, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_NestedIfElse_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2)
{{
string str = """";
if (param == str)
{{
if (param2 != str)
{{
}}
else
{{
Command c = new Command1(param, param);
c = new Command1(param2, param2);
}}
}}
if (str == param)
{{
Command c = new Command1(param, param);
}}
else if (param2 != str)
{{
if ((str + ""a"") != param)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String)
Dim str = """"
If param = str Then
If param2 <> str Then
Else
Dim c As Command = New Command1(param, param)
c = New Command1(param2, param2)
End If
End If
If str = param Then
Dim c As Command = New Command1(param, param)
ElseIf param2 <> str Then
If(str & ""a"") <> param Then
Else
Dim c As Command = New Command1(param, param)
End If
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_NestedIfElse_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Command3 : Command
{{
public Command3(string cmd, string parameter2)
{{
}}
}}
class Command4 : Command
{{
public Command4(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2)
{{
string str = """";
string str2 = param2;
if (param == str || param != str2)
{{
Command c = new Command1(param, param);
if (param == param2)
{{
Command c2 = new Command2(param2, param2);
}}
}}
if (param == str)
{{
}}
else
{{
if (str != param2 || param2 == str)
{{
Command c = new Command3(param2, param2);
}}
else
{{
}}
Command c2 = new Command4(param, param);
}}
}}
}}
",
// Test0.cs(122,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(122, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(125,30): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(125, 30, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(136,29): warning CA2100: Review if the query string passed to 'Command3.Command3(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(136, 29, "Command3.Command3(string cmd, string parameter2)", "M1"),
// Test0.cs(142,26): warning CA2100: Review if the query string passed to 'Command4.Command4(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(142, 26, "Command4.Command4(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Public Sub New(ByVal cmd As String, ByVal parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Public Sub New(ByVal cmd As String, ByVal parameter2 As String)
End Sub
End Class
Class Command3
Inherits Command
Public Sub New(ByVal cmd As String, ByVal parameter2 As String)
End Sub
End Class
Class Command4
Inherits Command
Public Sub New(ByVal cmd As String, ByVal parameter2 As String)
End Sub
End Class
Class Test
Private Sub M1(ByVal param As String, ByVal param2 As String)
Dim str As String = """"
Dim str2 As String = param2
If param = str OrElse param <> str2 Then
Dim c As Command = New Command1(param, param)
If param = param2 Then
Dim c2 As Command = New Command2(param2, param2)
End If
End If
If param = str Then
Else
If str <> param2 OrElse param2 = str Then
Dim c As Command = New Command3(param2, param2)
Else
End If
Dim c2 As Command = New Command4(param, param)
End If
End Sub
End Class",
// Test0.vb(154,32): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(154, 32, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(156,37): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(156, 37, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(163,36): warning CA2100: Review if the query string passed to 'Sub Command3.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(163, 36, "Sub Command3.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(166,33): warning CA2100: Review if the query string passed to 'Sub Command4.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(166, 33, "Sub Command4.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_Loops()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
Command c = null;
string str = """";
while (param == str)
{{
c = new Command1(param, param); // param == str here
}}
c = new Command2(param, param); // param is unknown here
}}
void M2(string param)
{{
Command c = null;
string str = """";
do
{{
c = new Command2(param, param); // param is unknown here.
}}
while (param != str);
c = new Command1(param, param); // param == str here
}}
void M3(string param, string param2)
{{
Command c = null;
string str = """";
for (param = str; param2 != str;)
{{
c = new Command1(param, param); // param == str here
c = new Command2(param2, param2); // param2 != str here
}}
c = new Command1(param2, param2); // param2 == str here
c = new Command1(param, param); // param == str here
}}
}}
",
// Test0.cs(111,13): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(111, 13, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(120,17): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M2', accepts any user input.
GetCSharpResultAt(120, 17, "Command2.Command2(string cmd, string parameter2)", "M2"),
// Test0.cs(134,17): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M3', accepts any user input.
GetCSharpResultAt(134, 17, "Command2.Command2(string cmd, string parameter2)", "M3"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
' While loop
Private Sub M1(ByVal param As String)
Dim c As Command = Nothing
Dim str As String = """"
While param = str
c = New Command1(param, param) ' param == str here
End While
c = New Command2(param, param) ' param is unknown here
End Sub
' Do-While top loop
Private Sub M2(ByVal param As String)
Dim c As Command = Nothing
Dim str As String = """"
Do While param <> str
c = New Command2(param, param) ' param is unknown here
Loop
c = New Command1(param, param) ' param = str here
End Sub
' Do-Until top loop
Private Sub M3(ByVal param As String)
Dim c As Command = Nothing
Dim str As String = """"
Do Until param <> str
c = New Command1(param, param) ' param = str here
Loop
c = New Command2(param, param) ' param is unknown here
End Sub
' Do-While bottom loop
Private Sub M4(ByVal param As String)
Dim c As Command = Nothing
Dim str As String = """"
Do
c = New Command2(param, param) ' param is unknown here
Loop While param <> str
c = New Command1(param, param) ' param = str here
End Sub
' Do-Until bottom loop
Private Sub M5(ByVal param As String)
Dim c As Command = Nothing
Dim str As String = """"
Do
c = New Command2(param, param) ' param is unknown here
Loop Until param = str
c = New Command1(param, param) ' param = str here
End Sub
End Module",
// Test0.vb(147,13): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(147, 13, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(155,17): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M2', accepts any user input.
GetBasicResultAt(155, 17, "Sub Command2.New(cmd As String, parameter2 As String)", "M2"),
// Test0.vb(169,13): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M3', accepts any user input.
GetBasicResultAt(169, 13, "Sub Command2.New(cmd As String, parameter2 As String)", "M3"),
// Test0.vb(177,17): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M4', accepts any user input.
GetBasicResultAt(177, 17, "Sub Command2.New(cmd As String, parameter2 As String)", "M4"),
// Test0.vb(188,17): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M5', accepts any user input.
GetBasicResultAt(188, 17, "Sub Command2.New(cmd As String, parameter2 As String)", "M5"));
}
[Fact]
public async Task FlowAnalysis_SwitchStatement()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
// Const in all switch cases.
void M1(string param, string param2, int i)
{{
string str = """";
switch (i)
{{
case 0:
param = str;
break;
case 1 :
param = str;
break;
default:
param2 = str;
param = param2;
break;
}}
Command c = new Command1(param, param); // param = str here
}}
// Const in all switch cases except one which has a return.
void M2(string param, string param2, int i)
{{
string str = """";
switch (i)
{{
case 0:
param = str;
break;
case 1 :
param = str + ""a"";
break;
default:
param = param2;
return;
}}
Command c = new Command1(param, param); // param is const here
}}
// Non-const in one of the intermediate switch case.
void M3(string param, string param2, int i)
{{
string str = """";
switch (i)
{{
case 0:
param = str;
break;
case 1 :
break;
default:
param = str;
break;
}}
Command c = new Command2(param, param); // param is unknown here for i = 1.
}}
// No default clause.
void M4(string param, string param2, int i)
{{
string str = """";
switch (i)
{{
case 0:
param = str;
break;
case 1 :
param = str;
break;
}}
Command c = new Command2(param, param); // param is unknown here for i != 0 or 1.
}}
// Switch case with multiple clauses.
void M5(string param, string param2, int i)
{{
string str = """";
switch (i)
{{
case 0:
case 1:
default:
param = str;
break;
}}
Command c = new Command1(param, param); // param is const here.
}}
}}
",
// Test0.cs(159,21): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M3', accepts any user input.
GetCSharpResultAt(159, 21, "Command2.Command2(string cmd, string parameter2)", "M3"),
// Test0.cs(176,21): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M4', accepts any user input.
GetCSharpResultAt(176, 21, "Command2.Command2(string cmd, string parameter2)", "M4"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
' Const in all switch cases.
Private Sub M1(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Select Case i
Case 0
param = str
Case 1
param = str
Case Else
param2 = str
param = param2
End Select
Dim c As Command = New Command1(param, param) ' param = str here
End Sub
' Const in all switch cases except one which has a return.
Private Sub M2(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Select Case i
Case 0
param = str
Case 1
param = str & ""a""
Case Else
param = param2
Return
End Select
Dim c As Command = New Command1(param, param) ' param is const here
End Sub
' Non-const in one of the intermediate switch case.
Private Sub M3(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Select Case i
Case 0
param = str
Case 1
Exit Select
Case Else
param = str
End Select
Dim c As Command = New Command2(param, param) ' param is unknown here for i = 1.
End Sub
' No Case Else
Private Sub M4(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Select Case i
Case 0
param = str
Case 1
param = str
End Select
Dim c As Command = New Command2(param, param) ' param is unknown here for i != 0 or 1.
End Sub
' Switch case with multiple clauses.
Private Sub M5(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Select Case i
Case 0, 1
param = str
Case Else
param = str
End Select
Dim c As Command = New Command1(param, param) ' param = str here.
End Sub
End Module",
// Test0.vb(183,28): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M3', accepts any user input.
GetBasicResultAt(183, 28, "Sub Command2.New(cmd As String, parameter2 As String)", "M3"),
// Test0.vb(196,28): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M4', accepts any user input.
GetBasicResultAt(196, 28, "Sub Command2.New(cmd As String, parameter2 As String)", "M4"));
}
[Fact]
public async Task FlowAnalysis_TryCatch()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, int i)
{{
string str = """";
if (param != str)
{{
throw new System.ArgumentException();
}}
Command c = new Command1(param, param); // param = str here
}}
void M2(string param, string param2, int i)
{{
string str = """";
try
{{
param = param2;
}}
finally
{{
param = str;
}}
Command c = new Command1(param, param); // param is str here
}}
void M3(string param, string param2, int i)
{{
string str = """";
try
{{
param = str;
}}
catch (System.Exception ex)
{{
param = param2;
}}
Command c = new Command2(param, param); // param is unknown here for catch.
}}
void M4(string param, string param2, int i)
{{
string str = """";
try
{{
param = str;
}}
catch (System.IO.IOException ex)
{{
param = param2;
}}
catch (System.Exception ex)
{{
param = str;
}}
Command c = new Command2(param, param); // param is unknown here for IOException.
}}
void M5(string param, string param2, int i)
{{
string str = """";
try
{{
}}
catch (System.Exception ex)
{{
param = param2;
}}
finally
{{
param = str;
}}
Command c = new Command1(param, param); // param is str here from finally.
}}
void M6(string param, string param2, int i)
{{
string str = """";
try
{{
if (i == 0)
{{
throw new System.ArgumentException();
}}
param = str;
}}
catch (System.ArgumentException ex)
{{
param = param2;
}}
catch (System.Exception ex)
{{
param = str;
}}
Command c = new Command2(param, param); // param is unknown here for ArgumentException.
}}
}}
",
// Test0.cs(140,21): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M3', accepts any user input.
GetCSharpResultAt(140, 21, "Command2.Command2(string cmd, string parameter2)", "M3"),
// Test0.cs(159,21): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M4', accepts any user input.
GetCSharpResultAt(159, 21, "Command2.Command2(string cmd, string parameter2)", "M4"),
// Test0.cs(200,21): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M6', accepts any user input.
GetCSharpResultAt(200, 21, "Command2.Command2(string cmd, string parameter2)", "M6"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Private Sub M1(ByVal param As String, ByVal i As Integer)
Dim str As String = """"
If param <> str Then
Throw New System.ArgumentException()
End If
Dim c As Command = New Command1(param, param) ' param = str here
End Sub
Private Sub M2(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Try
param = param2
Finally
param = str
End Try
Dim c As Command = New Command1(param, param) ' param = str here
End Sub
Private Sub M3(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Try
param = str
Catch ex As System.Exception
param = param2
End Try
Dim c As Command = New Command2(param, param) ' param is unknown here for catch.
End Sub
Private Sub M4(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Try
param = str
Catch ex As System.IO.IOException
param = param2
Catch ex As System.Exception
param = str
End Try
Dim c As Command = New Command2(param, param) ' param is unknown here for IOException.
End Sub
Private Sub M5(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Try
Catch ex As System.Exception
param = param2
Finally
param = str
End Try
Dim c As Command = New Command1(param, param) ' param is str here from finally.
End Sub
Private Sub M6(ByVal param As String, ByVal param2 As String, ByVal i As Integer)
Dim str As String = """"
Try
If i = 0 Then
Throw New System.ArgumentException()
End If
param = str
Catch ex As System.ArgumentException
param = param2
Catch ex As System.Exception
param = str
End Try
Dim c As Command = New Command2(param, param) ' param is unknown here for ArgumentException.
End Sub
End Module",
// Test0.vb(167,28): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M3', accepts any user input.
GetBasicResultAt(167, 28, "Sub Command2.New(cmd As String, parameter2 As String)", "M3"),
// Test0.vb(180,28): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M4', accepts any user input.
GetBasicResultAt(180, 28, "Sub Command2.New(cmd As String, parameter2 As String)", "M4"),
// Test0.vb(209,28): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M6', accepts any user input.
GetBasicResultAt(209, 28, "Sub Command2.New(cmd As String, parameter2 As String)", "M6"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_CatchFilter()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
string str = """";
try
{{
}}
catch (System.Exception ex) when (param == str)
{{
var c = new Command1(param, param); // param == str here from filter.
}}
}}
void M2(string param)
{{
string str = """";
try
{{
param = str;
}}
catch (System.Exception ex) when (param == str)
{{
}}
var c = new Command1(param, param); // param == str here from try and filter.
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Private Sub M1(ByVal param As String)
Dim str As String = """"
Try
Catch ex As System.Exception When param = str
Dim c = New Command1(param, param) ' param = str here from filter.
End Try
End Sub
Private Sub M2(ByVal param As String)
Dim str As String = """"
Try
param = str
Catch ex As System.Exception When param = str
End Try
Dim c = New Command1(param, param) ' param = str here from try and filter.
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.CopyAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_CopyAnalysis_NoDiagnostic()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, string param3)
{{
string str = ""a"";
if (param == str && param == param2)
{{
Command c = new Command1(param2, param2);
}}
param = param2;
if (param == str)
{{
Command c = new Command1(param2, param2);
}}
if (param == str && param2 == str)
{{
Command c = new Command1(param, param);
c = new Command1(param2, param2);
}}
string str2 = ""b"";
if (param2 != str2)
{{
}}
else
{{
param2 = param3;
Command c = new Command1(param, param);
}}
}}
}}
"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") }
}
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, param3 As String)
Dim str = ""a""
If param = str AndAlso param = param2 Then
Dim c As Command = New Command1(param2, param2)
End If
param = param2
If param = str Then
Dim c As Command = New Command1(param2, param2)
End If
If param = str AndAlso param2 = str Then
Dim c As Command = New Command1(param, param)
c = New Command1(param2, param2)
End If
Dim str2 = ""b""
If str2 <> param2 Then
Else
param2 = param3
Dim c As Command = New Command1(param, param)
End If
End Sub
End Module"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") }
}
}.RunAsync();
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.CopyAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_CopyAnalysis_Diagnostic()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Command3 : Command
{{
public Command3(string cmd, string parameter2)
{{
}}
}}
class Command4 : Command
{{
public Command4(string cmd, string parameter2)
{{
}}
}}
class Command5 : Command
{{
public Command5(string cmd, string parameter2)
{{
}}
}}
class Command6 : Command
{{
public Command6(string cmd, string parameter2)
{{
}}
}}
class Command7 : Command
{{
public Command7(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, string param3)
{{
string str = param3;
if (param == str && param == param2)
{{
Command c = new Command1(param2, param2);
}}
str = ""a"";
param = param2;
// Always false, we set the copy values of the involved variables to invalid to prevent unnecessary diagnostics.
if (param2 == str && param != str)
{{
Command c = new Command2(param2, param2);
}}
// Always true, but does not tell anything about value of param2 in either if or else.
// Else branch can never be entered, hence we set the copy values of the involved variables to invalid.
if (param2 == str || param != str)
{{
Command c = new Command3(param2, param2);
}}
else
{{
Command c = new Command4(param2, param2);
}}
if (param == str && param2 == str)
{{
}}
else
{{
Command c = new Command5(param, param);
c = new Command6(param2, param2);
}}
string str2 = ""b"";
if (param2 != str2)
{{
param2 = ""a"";
Command c = new Command7(param, param);
}}
}}
}}
"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") },
ExpectedDiagnostics =
{
// Test0.cs(142,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(142, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(157,25): warning CA2100: Review if the query string passed to 'Command3.Command3(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(157, 25, "Command3.Command3(string cmd, string parameter2)", "M1"),
// Test0.cs(169,25): warning CA2100: Review if the query string passed to 'Command5.Command5(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(169, 25, "Command5.Command5(string cmd, string parameter2)", "M1"),
// Test0.cs(170,17): warning CA2100: Review if the query string passed to 'Command6.Command6(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(170, 17, "Command6.Command6(string cmd, string parameter2)", "M1"),
// Test0.cs(177,25): warning CA2100: Review if the query string passed to 'Command7.Command7(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(177, 25, "Command7.Command7(string cmd, string parameter2)", "M1"),
}
}
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command3
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command4
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command5
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command6
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command7
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Private Sub M1(ByVal param As String, ByVal param2 As String, ByVal param3 As String)
Dim str As String = param3
If param = str AndAlso param = param2 Then
Dim c As Command = New Command1(param2, param2)
End If
str = ""a""
param = param2
' Always false, we set the copy values of the involved variables to invalid to prevent unnecessary diagnostics.
If param2 = str AndAlso param <> str Then
Dim c As Command = New Command2(param2, param2)
End If
' Always true, but does not tell anything about value of param2 in either if or else.
' Else branch can never be entered, hence we set the copy values of the involved variables to invalid.
If param2 = str OrElse param <> str Then
Dim c As Command = New Command3(param2, param2)
Else
Dim c As Command = New Command4(param2, param2)
End If
If param = str AndAlso param2 = str Then
Else
Dim c As Command = New Command5(param, param)
c = New Command6(param2, param2)
End If
Dim str2 As String = ""b""
If param2 <> str2 Then
param2 = ""a""
Dim c As Command = New Command7(param, param)
End If
End Sub
End Module"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") },
ExpectedDiagnostics =
{
// Test0.vb(177,32): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(177, 32, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(190,32): warning CA2100: Review if the query string passed to 'Sub Command3.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(190, 32, "Sub Command3.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(197,32): warning CA2100: Review if the query string passed to 'Sub Command5.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(197, 32, "Sub Command5.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(198,17): warning CA2100: Review if the query string passed to 'Sub Command6.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(198, 17, "Sub Command6.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(204,32): warning CA2100: Review if the query string passed to 'Sub Command7.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(204, 32, "Sub Command7.New(cmd As String, parameter2 As String)", "M1"),
}
}
}.RunAsync();
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalOr_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str || param == str2)
{{
Command c = new Command1(param, param);
}}
// 2. Creation in else: negation of non-const in left, maybe-const in right.
if (str2 != param || param == strMayBeConst)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 3. Creation in else: maybe-const in left, negation of non-const in right.
if (param == strMayBeConst || str2 != param)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str OrElse param = str2 Then
Dim c As New Command1(param, param)
End If
' 2. Creation in else: negation of non-const in left, maybe-const in right.
If str2 <> param OrElse param = strMayBeConst Then
Else
Dim c As New Command1(param, param)
End If
' 3. Creation in else: maybe-const in left, negation of non-const in right.
If param = strMayBeConst OrElse str2 <> param Then
Else
Dim c As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalOr_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str || param == str2)
{{
Command c = new Command1(param, param); // No diagnostic
}}
// 2. Creation in if and else: negation of non-const in left, maybe-const in right.
if (str2 != param || param == strMayBeConst)
{{
Command c = new Command2(param, param); // Diagnostic
}}
else
{{
Command c = new Command1(param, param);
}}
// 3. Creation in if and else: maybe-const in left, negation of non-const in right.
if (param == strMayBeConst || str2 != param)
{{
Command c = new Command2(param, param); // Diagnostic
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(117,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(117, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(127,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(127, 25, "Command2.Command2(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str OrElse param = str2 Then
Dim c As New Command1(param, param) ' No diagnostic
End If
' 2. Creation in if and else: negation of non-const in left, maybe-const in right.
If str2 <> param OrElse param = strMayBeConst Then
Dim c As New Command2(param, param)
Else
Dim c As New Command1(param, param)
End If
' 3. Creation in if and else: maybe-const in left, negation of non-const in right.
If param = strMayBeConst OrElse str2 <> param Then
Dim c As New Command2(param, param)
Else
Dim c As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(151,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(151, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(158,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(158, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalOr_02_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str || param == str2)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 2. const in left, maybe-const in right.
if (param == str || str2 != param)
{{
Command c = new Command1(param, param);
}}
// 3. const in left, maybe-const in right, creation in else.
if (param == str || strMayBeConst != param)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 4. maybe-const in left, const in right.
if (param == strMayBeConst || str2 != param)
{{
Command c = new Command1(param, param);
}}
// 5. maybe-const in left and right.
if (param == strMayBeConst || param == strMayBeConst + ""c"")
{{
Command c = new Command1(param, param);
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(107,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(107, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(113,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(113, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(122,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(122, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(128,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(128, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(134,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(134, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(138,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(138, 25, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str OrElse param = str2 Then
Else
Dim c As New Command1(param, param)
End If
' 2. const in left, maybe-const in right.
If str = param OrElse strMayBeConst <> param Then
Dim c As New Command1(param, param)
End If
' 3. maybe-const in left, const in right.
If param = strMayBeConst OrElse param <> str2 Then
Dim c As New Command1(param, param)
End If
' 4. maybe-const in left, const in right.
If param = strMayBeConst OrElse str2 <> param Then
Dim c As New Command1(param, param)
End If
' 5. maybe-const in left and right.
If param = strMayBeConst OrElse param = strMayBeConst + ""c"" Then
Dim c As New Command1(param, param)
Else
Dim c As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(140,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(140, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(145,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(145, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(150,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(150, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(155,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(155, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(160,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(160, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(162,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(162, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalAnd_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str && param2 == str2)
{{
Command c = new Command1(param, param);
}}
// 2. maybe-const in left, const in right.
if (param == strMayBeConst && str2 == param)
{{
Command c = new Command1(param, param);
}}
// 3. Creation in else: non-const in left, non-const in right.
if (param != str && param != str2)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str AndAlso param2 = str2 Then
Dim c As New Command1(param, param)
End If
' 2. maybe-const in left, const in right.
If param = strMayBeConst AndAlso str2 = param Then
Dim c As New Command1(param, param)
End If
' 3. Creation in else: non-const in left, non-const in right.
If str2 <> param AndAlso param <> str Then
Else
Dim c As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalAnd_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str && param2 == str2)
{{
Command c = new Command1(param, param); // No diagnostic
}}
// 2. Creation in if and else: negation of non-const in left, maybe-const in right.
if (str2 != param && param == strMayBeConst)
{{
Command c = new Command2(param, param); // Diagnostic
}}
else
{{
Command c = new Command2(param, param); // Diagnostic where left of '&&' is true and right of '&&' is false.
}}
// 3. Creation in if and else: maybe-const in left, negation of non-const in right.
if (param == strMayBeConst && str2 != param)
{{
Command c = new Command2(param, param); // Diagnostic (if both are true, param maybe non-const)
}}
else
{{
Command c = new Command2(param, param); // Diagnostic (if left is false, param maybe non-const)
}}
// 4. Creation in else: non-const in left, non-const different variable in right.
if (param != str && param2 != str2)
{{
}}
else
{{
Command c = new Command2(param, param); // Diagnostic (if left is true and right is false, param maybe non-const)
}}
// 5. Creation in else: negation of non-const in left, maybe-const in right.
if (str2 != param && param == strMayBeConst)
{{
}}
else
{{
Command c = new Command2(param, param); // Diagnostic (if left is true and right is false, param maybe non-const)
}}
}}
}}
",
// Test0.cs(117,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(117, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(121,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(121, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(127,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(127, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(131,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(131, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(140, 25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(140, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(149,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(149, 25, "Command2.Command2(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str AndAlso param2 = str2 Then
Dim c As New Command1(param, param) ' No diagnostic
End If
' 2. Creation in if and else: negation of non-const in left, maybe-const in right.
If str2 <> param AndAlso param = strMayBeConst Then
Dim c As New Command2(param, param) ' Diagnostic
Else
Dim c As New Command2(param, param) ' Diagnostic where left of 'AndAlso' is true and right of 'AndAlso' is false.
End If
' 3. Creation in if and else: maybe-const in left, negation of non-const in right.
If param = strMayBeConst AndAlso str2 <> param Then
Dim c As New Command2(param, param) ' Diagnostic (if both are true, param maybe non-const)
Else
Dim c As New Command2(param, param) ' Diagnostic (if left is false, param maybe non-const)
End If
' 4. Creation in else: non-const in left, non-const differen variable in right.
If str2 <> param AndAlso param2 <> str Then
Else
Dim c As New Command2(param, param) ' Diagnostic (if left is true and right is false, param maybe non-const)
End If
' 5. Creation in else: negation of non-const in left, maybe-const in right.
If str2 <> param AndAlso param = strMayBeConst Then
Else
Dim c As New Command2(param, param) ' Diagnostic (if left is true and right is false, param maybe non-const)
End If
End Sub
End Module",
// Test0.vb(151,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(151, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(153,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(153, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(158,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(158, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(160,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(160, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(166,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(166, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(172,22): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(172, 22, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalAnd_02_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, string param2, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
string strMayBeConst = param2;
// 1. const in left, const in right.
if (param == str && param == str2)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 2. const in left, maybe-const in right, creation in else.
if (param == str && str2 != param)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 3. const in left, maybe-const in right, creation in else.
if (param == str && strMayBeConst != param)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
// 4. maybe-const in left, non-const in right.
if (param == strMayBeConst && str2 != param)
{{
Command c = new Command1(param, param);
}}
// 5. maybe-const in left and right.
if (param == strMayBeConst && param == strMayBeConst + ""c"")
{{
Command c = new Command1(param, param);
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
",
// Test0.cs(107,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(107, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(116,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(116, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(125,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(125, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(131,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(131, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(137,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(137, 25, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(141,25): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(141, 25, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
Dim strMayBeConst = param2
' 1. const in left, const in right.
If param = str AndAlso param = str2 Then
Else
Dim c As New Command1(param, param)
End If
' 2. const in left, maybe-const in right.
If str = param AndAlso str2 <> param Then
Else
Dim c As New Command1(param, param)
End If
' 3. maybe-const in left, const in right, creation in else.
If param = str AndAlso strMayBeConst <> param Then
Else
Dim c As New Command1(param, param)
End If
' 4. maybe-const in left, non-const in right.
If param = strMayBeConst AndAlso str2 <> param Then
Dim c As New Command1(param, param)
End If
' 5. maybe-const in left and right.
If param = strMayBeConst AndAlso param = strMayBeConst + ""c"" Then
Dim c As New Command1(param, param)
Else
Dim c As New Command1(param, param)
End If
End Sub
End Module",
// Test0.vb(140,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(140, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(146,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(146, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(152,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(152, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(157,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(157, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(162,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(162, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(164,22): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(164, 22, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_Conditional_WithNegation_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, bool flag)
{{
string str = """";
string str2 = flag ? ""a"" : ""b"";
if (param == str || !(param != str2))
{{
Command c = new Command1(param, param);
}}
if (!(param != str) || str2 == param)
{{
Command c = new Command1(param, param);
}}
if (!(param == str || param == str2))
{{
}}
else
{{
Command c = new Command1(param, param);
}}
if (!(!(str != param) && !!(param != str2)))
{{
}}
else
{{
Command c = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, flag As Boolean)
Dim str = """"
Dim str2 = If(flag, ""a"", ""b"")
If param = str OrElse Not (param <> str2) Then
Dim c As New Command1(param, param)
End If
If Not (str <> param) OrElse str2 = param Then
Dim c2 As New Command1(param, param)
End If
If Not (param = str OrElse param = str2) Then
Else
Dim c3 As New Command1(param, param)
End If
If Not (Not (str <> param) AndAlso Not Not (param <> str2)) Then
Else
Dim c4 As New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalAndOrNegation_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, bool flag, string param2)
{{
string strConst = """";
string strConst2 = flag ? ""a"" : """";
string strMayBeNonConst = flag ? ""c"" : param2;
if (param == strConst || !(strConst2 != param) && param != strMayBeNonConst)
{{
Command c = new Command1(param, param);
}}
if (!(strConst2 == param && !(param != strConst)) || param == strMayBeNonConst)
{{
}}
else
{{
Command c = new Command1(param, param);
}}
if (param != strConst && !(strConst2 != param || param != strMayBeNonConst))
{{
Command c = new Command1(param, param);
}}
}}
}}
");
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim strConst As String = """"
Dim strConst2 As String = If(flag, ""a"", """")
Dim strMayBeNonConst As String = If(flag, ""c"", param2)
If param = strConst OrElse Not(strConst2 <> param) AndAlso param <> strMayBeNonConst Then
Dim c As Command = New Command1(param, param)
End If
If Not(strConst2 = param AndAlso Not (param <> strConst)) OrElse param <> strMayBeNonConst Then
Else
Dim c As Command = New Command1(param, param)
End If
If param <> strConst AndAlso Not(strConst2 <> param OrElse param <> strMayBeNonConst) Then
Dim c As Command = New Command1(param, param)
End If
End Sub
End Module");
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ConditionalAndOrNegation_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Command3 : Command
{{
public Command3(string cmd, string parameter2)
{{
}}
}}
class Command4 : Command
{{
public Command4(string cmd, string parameter2)
{{
}}
}}
class Command5 : Command
{{
public Command5(string cmd, string parameter2)
{{
}}
}}
class Command6 : Command
{{
public Command6(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param, bool flag, string param2)
{{
string strConst = """";
string strConst2 = flag ? ""a"" : """";
string strMayBeNonConst = flag ? ""c"" : param2;
if (param != strConst && !(strConst2 != param || param != strConst)) // First and last conditions are opposites, so infeasible.
{{
Command c = new Command1(param, param);
}}
else
{{
Command c = new Command2(param, param);
}}
if (param == strConst && !(strConst2 == param || param == strMayBeNonConst))
{{
Command c = new Command3(param, param); // No diagnostic here as first condition ensures param == strConst.
}}
else
{{
Command c = new Command4(param, param);
}}
if (param != strConst && !(strConst2 != param || param != strMayBeNonConst))
{{
Command c = new Command5(param, param); // No diagnostic expected here
}}
else
{{
Command c = new Command6(param, param);
}}
}}
}}
",
// Test0.cs(142,25): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(142, 25, "Command2.Command2(string cmd, string parameter2)", "M1"),
// Test0.cs(151,25): warning CA2100: Review if the query string passed to 'Command4.Command4(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(151, 25, "Command4.Command4(string cmd, string parameter2)", "M1"),
// Test0.cs(160,25): warning CA2100: Review if the query string passed to 'Command6.Command6(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(160, 25, "Command6.Command6(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command3
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command4
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command5
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command6
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String, param2 As String, flag As Boolean)
Dim strConst As String = """"
Dim strConst2 As String = If(flag, ""a"", """")
Dim strMayBeNonConst As String = If(flag, ""c"", param2)
If param <> strConst AndAlso Not(strConst2 <> param OrElse param <> strConst) Then ' First and last conditions are opposites, so infeasible.
Dim c As Command = New Command1(param, param)
Else
Dim c As Command = New Command2(param, param)
End If
If param = strConst AndAlso Not(strConst2 = param OrElse param = strMayBeNonConst) Then
Dim c As Command = New Command3(param, param) ' No diagnostic here as first condition ensures param = strConst.
Else
Dim c As Command = New Command4(param, param)
End If
If param <> strConst AndAlso Not(strConst2 <> param OrElse param <> strMayBeNonConst) Then
Dim c As Command = New Command5(param, param) ' No diagnostic expected here
Else
Dim c As Command = New Command6(param, param)
End If
End Sub
End Module",
// Test0.vb(175,32): warning CA2100: Review if the query string passed to 'Sub Command2.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(175, 32, "Sub Command2.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(181,32): warning CA2100: Review if the query string passed to 'Sub Command4.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(181, 32, "Sub Command4.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(187,32): warning CA2100: Review if the query string passed to 'Sub Command6.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(187, 32, "Sub Command6.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ComparisonInNonCondition_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
var x = param == """"; // This predicate should not affect subsequent code.
Command c = new Command1(param, param);
}}
}}
",
// Test0.cs(98,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(98, 21, "Command1.Command1(string cmd, string parameter2)", "M1"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Sub M1(param As String)
Dim x = param = """" ' This predicate should not affect subsequent code.
Dim c As New Command1(param, param)
End Sub
End Module",
// Test0.vb(134,18): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(134, 18, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ComparisonInNonCondition_02_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
Command c = null;
var x = param == """" && ((c = new Command1(param, param)) != null); // Left operand of && ensures no diagnostic for Command1 instantiation.
c = new Command2(param, param); // This code should fire as 'param == """"' does not apply here.
}}
}}
",
// Test0.cs(106,13): warning CA2100: Review if the query string passed to 'Command2.Command2(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(106, 13, "Command2.Command2(string cmd, string parameter2)", "M1"));
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ContractCheck_NoDiagnostic()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
System.Diagnostics.Contracts.Contract.Requires(param == """");
Command c = new Command1(param, param);
}}
void M2(string param, string param2)
{{
System.Diagnostics.Contracts.Contract.Requires(param == """" && param2 == param);
Command c = new Command1(param, param);
c = new Command1(param2, param2);
}}
void M3(string param, string param2)
{{
System.Diagnostics.Contracts.Contract.Requires(param == param2 && !(param2 != """"));
Command c = new Command1(param, param);
c = new Command1(param2, param2);
}}
void M4_Assume(string param)
{{
System.Diagnostics.Contracts.Contract.Assume(param == """");
Command c = new Command1(param, param);
}}
void M5_Assert(string param)
{{
System.Diagnostics.Contracts.Contract.Assert(param == """");
Command c = new Command1(param, param);
}}
}}
"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") }
}
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
$@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Private Sub M1(ByVal param As String)
System.Diagnostics.Contracts.Contract.Requires(param = """")
Dim c As Command = New Command1(param, param)
End Sub
Private Sub M2(ByVal param As String, ByVal param2 As String)
System.Diagnostics.Contracts.Contract.Requires(param = """" AndAlso param2 = param)
Dim c As Command = New Command1(param, param)
c = New Command1(param2, param2)
End Sub
Private Sub M3(ByVal param As String, ByVal param2 As String)
System.Diagnostics.Contracts.Contract.Requires(param = param2 AndAlso Not(param2 <> """"))
Dim c As Command = New Command1(param, param)
c = New Command1(param2, param2)
End Sub
Private Sub M4_Assume(ByVal param As String)
System.Diagnostics.Contracts.Contract.Assume(param = """")
Dim c As Command = New Command1(param, param)
End Sub
Private Sub M5_Assert(ByVal param As String)
System.Diagnostics.Contracts.Contract.Assert(param = """")
Dim c As Command = New Command1(param, param)
End Sub
End Module"
},
AdditionalFiles = { (".editorconfig", "dotnet_code_quality.copy_analysis = true") }
}
}.RunAsync();
}
[Trait(Traits.DataflowAnalysis, Traits.Dataflow.PredicateAnalysis)]
[Fact]
public async Task FlowAnalysis_PredicateAnalysis_ContractCheck_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync($@"
{SetupCodeCSharp}
class Command1 : Command
{{
public Command1(string cmd, string parameter2)
{{
}}
}}
class Command2 : Command
{{
public Command2(string cmd, string parameter2)
{{
}}
}}
class Test
{{
void M1(string param)
{{
System.Diagnostics.Contracts.Contract.Requires(param != """");
Command c = new Command1(param, param);
}}
void M2(string param, string param2)
{{
param2 = """";
System.Diagnostics.Contracts.Contract.Requires(param == """" || param2 != param);
Command c = new Command1(param, param);
c = new Command2(param2, param2); // No diagnostic.
}}
void M3(string param, string param2, string param3)
{{
System.Diagnostics.Contracts.Contract.Requires(param == param2 && !(param2 != """") || param2 == param3);
Command c = new Command1(param, param);
c = new Command1(param2, param2);
}}
}}
",
// Test0.cs(105,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M1', accepts any user input.
GetCSharpResultAt(105, 21, "Command1.Command1(string cmd, string parameter2)", "M1"),
// Test0.cs(112,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M2', accepts any user input.
GetCSharpResultAt(112, 21, "Command1.Command1(string cmd, string parameter2)", "M2"),
// Test0.cs(119,21): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M3', accepts any user input.
GetCSharpResultAt(119, 21, "Command1.Command1(string cmd, string parameter2)", "M3"),
// Test0.cs(120,13): warning CA2100: Review if the query string passed to 'Command1.Command1(string cmd, string parameter2)' in 'M3', accepts any user input.
GetCSharpResultAt(120, 13, "Command1.Command1(string cmd, string parameter2)", "M3"));
await VerifyVB.VerifyAnalyzerAsync($@"
{SetupCodeBasic}
Class Command1
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Class Command2
Inherits Command
Sub New(cmd As String, parameter2 As String)
End Sub
End Class
Module Test
Private Sub M1(ByVal param As String)
System.Diagnostics.Contracts.Contract.Requires(param <> """")
Dim c As Command = New Command1(param, param)
End Sub
Private Sub M2(ByVal param As String, ByVal param2 As String)
param2 = """"
System.Diagnostics.Contracts.Contract.Requires(param = """" OrElse param2 <> param)
Dim c As Command = New Command1(param, param)
c = New Command2(param2, param2) ' No diagnostic
End Sub
Private Sub M3(ByVal param As String, ByVal param2 As String, param3 As String)
System.Diagnostics.Contracts.Contract.Requires(param = param2 AndAlso Not(param2 <> """") OrElse param2 = param3)
Dim c As Command = New Command1(param, param)
c = New Command1(param2, param2)
End Sub
End Module",
// Test0.vb(139,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M1', accepts any user input.
GetBasicResultAt(139, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M1"),
// Test0.vb(145,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M2', accepts any user input.
GetBasicResultAt(145, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M2"),
// Test0.vb(151,28): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M3', accepts any user input.
GetBasicResultAt(151, 28, "Sub Command1.New(cmd As String, parameter2 As String)", "M3"),
// Test0.vb(152,13): warning CA2100: Review if the query string passed to 'Sub Command1.New(cmd As String, parameter2 As String)' in 'M3', accepts any user input.
GetBasicResultAt(152, 13, "Sub Command1.New(cmd As String, parameter2 As String)", "M3"));
}
}
}
|
pakdev/roslyn-analyzers
|
src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Data/ReviewSQLQueriesForSecurityVulnerabilitiesTests_FlowAnalysis.cs
|
C#
|
apache-2.0
| 238,067
|
<?php
namespace Google\AdsApi\AdManager\v202111;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class ActivityError extends \Google\AdsApi\AdManager\v202111\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\AdManager\v202111\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\AdManager\v202111\ActivityError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
|
googleads/googleads-php-lib
|
src/Google/AdsApi/AdManager/v202111/ActivityError.php
|
PHP
|
apache-2.0
| 1,072
|
package org.ebayopensource.turmeric.tools.codegen;
import static org.junit.Assert.*;
import junit.framework.TestCase;
/**
* @author svaddi
*
*/
public class InterfaceTest1 extends TestCase {
/**
* @param name
*/
public InterfaceTest1(String name) {
super(name);
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public static void testInterface() {
}
}
|
ebayopensource/turmeric-runtime
|
codegen/codegen-tools/src/test/java/org/ebayopensource/turmeric/tools/codegen/InterfaceTest1.java
|
Java
|
apache-2.0
| 593
|
gohadoop
========
gohadoop is native go clients for Apache Hadoop YARN.
It includes an early version of Hadoop IPC client and requisite YARN client libraries to implement YARN applications completely in go (both YARN application-client and application-master).
### Notes:
* Set HADOOP_CONF_DIR environment variable, and ensure the conf directory contains both *-default.xml and *-site.xml files.
* hadoop_yarn/examples/dist_shell is an example go YARN application: client.go is the submission client and applicationmaster.go is the application-master.
To run:
### Run regular dist-shell with AM in-cluster
$ HADOOP_CONF_DIR=conf go run hadoop_yarn/examples/dist_shell/client.go
### Run dist-shell with unmanaged AM
$ HADOOP_CONF_DIR=conf go run hadoop_yarn/examples/dist_shell/unmanaged.go
|
hortonworks/gohadoop
|
README.md
|
Markdown
|
apache-2.0
| 804
|
/**
* 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.web;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.DelegationTokenRenewer;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSelector;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.hdfs.web.resources.AccessTimeParam;
import org.apache.hadoop.hdfs.web.resources.BlockSizeParam;
import org.apache.hadoop.hdfs.web.resources.BufferSizeParam;
import org.apache.hadoop.hdfs.web.resources.ConcatSourcesParam;
import org.apache.hadoop.hdfs.web.resources.CreateParentParam;
import org.apache.hadoop.hdfs.web.resources.DelegationParam;
import org.apache.hadoop.hdfs.web.resources.DeleteOpParam;
import org.apache.hadoop.hdfs.web.resources.DestinationParam;
import org.apache.hadoop.hdfs.web.resources.DoAsParam;
import org.apache.hadoop.hdfs.web.resources.GetOpParam;
import org.apache.hadoop.hdfs.web.resources.GroupParam;
import org.apache.hadoop.hdfs.web.resources.HttpOpParam;
import org.apache.hadoop.hdfs.web.resources.LengthParam;
import org.apache.hadoop.hdfs.web.resources.ModificationTimeParam;
import org.apache.hadoop.hdfs.web.resources.OffsetParam;
import org.apache.hadoop.hdfs.web.resources.OverwriteParam;
import org.apache.hadoop.hdfs.web.resources.OwnerParam;
import org.apache.hadoop.hdfs.web.resources.Param;
import org.apache.hadoop.hdfs.web.resources.PermissionParam;
import org.apache.hadoop.hdfs.web.resources.PostOpParam;
import org.apache.hadoop.hdfs.web.resources.PutOpParam;
import org.apache.hadoop.hdfs.web.resources.RecursiveParam;
import org.apache.hadoop.hdfs.web.resources.RenameOptionSetParam;
import org.apache.hadoop.hdfs.web.resources.RenewerParam;
import org.apache.hadoop.hdfs.web.resources.ReplicationParam;
import org.apache.hadoop.hdfs.web.resources.TokenArgumentParam;
import org.apache.hadoop.hdfs.web.resources.UserParam;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.io.retry.RetryUtils;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authorize.AuthorizationException;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenRenewer;
import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSelector;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
import org.mortbay.util.ajax.JSON;
import javax.ws.rs.core.MediaType;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* A FileSystem for HDFS over the web.
*/
public class WebHdfsFileSystem extends FileSystem
implements DelegationTokenRenewer.Renewable {
public static final Log LOG = LogFactory.getLog(WebHdfsFileSystem.class);
/**
* File System URI: {SCHEME}://namenode:port/path/to/file
*/
public static final String SCHEME = "webhdfs";
/**
* WebHdfs version.
*/
public static final int VERSION = 1;
/**
* Http URI: http://namenode:port/{PATH_PREFIX}/path/to/file
*/
public static final String PATH_PREFIX = "/" + SCHEME + "/v" + VERSION;
/**
* SPNEGO authenticator
*/
private static final KerberosUgiAuthenticator AUTH =
new KerberosUgiAuthenticator();
/**
* Delegation token kind
*/
public static final Text TOKEN_KIND = new Text("WEBHDFS delegation");
/**
* Token selector
*/
public static final WebHdfsDelegationTokenSelector DT_SELECTOR =
new WebHdfsDelegationTokenSelector();
private DelegationTokenRenewer dtRenewer = null;
private synchronized void addRenewAction(final WebHdfsFileSystem webhdfs) {
if (dtRenewer == null) {
dtRenewer = DelegationTokenRenewer.getInstance();
}
dtRenewer.addRenewAction(webhdfs);
}
/**
* Is WebHDFS enabled in conf?
*/
public static boolean isEnabled(final Configuration conf, final Log log) {
final boolean b = conf.getBoolean(DFSConfigKeys.DFS_WEBHDFS_ENABLED_KEY,
DFSConfigKeys.DFS_WEBHDFS_ENABLED_DEFAULT);
log.info(DFSConfigKeys.DFS_WEBHDFS_ENABLED_KEY + " = " + b);
return b;
}
private UserGroupInformation ugi;
private InetSocketAddress nnAddr;
private URI uri;
private Token<?> delegationToken;
private final AuthenticatedURL.Token authToken = new AuthenticatedURL.Token();
private RetryPolicy retryPolicy = null;
private Path workingDir;
/**
* Return the protocol scheme for the FileSystem.
* <p/>
*
* @return <code>webhdfs</code>
*/
@Override
public String getScheme() {
return "webhdfs";
}
@Override
public synchronized void initialize(URI uri, Configuration conf)
throws IOException {
super.initialize(uri, conf);
setConf(conf);
ugi = UserGroupInformation.getCurrentUser();
try {
this.uri = new URI(uri.getScheme(), uri.getAuthority(), null, null, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
this.nnAddr =
NetUtils.createSocketAddr(uri.getAuthority(), getDefaultPort());
this.retryPolicy = RetryUtils.getDefaultRetryPolicy(conf,
DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_ENABLED_KEY,
DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_ENABLED_DEFAULT,
DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_SPEC_KEY,
DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_SPEC_DEFAULT,
SafeModeException.class);
this.workingDir = getHomeDirectory();
if (UserGroupInformation.isSecurityEnabled()) {
initDelegationToken();
}
}
protected void initDelegationToken() throws IOException {
// look for webhdfs token, then try hdfs
Token<?> token = selectDelegationToken(ugi);
//since we don't already have a token, go get one
boolean createdToken = false;
if (token == null) {
token = getDelegationToken(null);
createdToken = (token != null);
}
// security might be disabled
if (token != null) {
setDelegationToken(token);
if (createdToken) {
addRenewAction(this);
LOG.debug("Created new DT for " + token.getService());
} else {
LOG.debug("Found existing DT for " + token.getService());
}
}
}
protected Token<DelegationTokenIdentifier> selectDelegationToken(
UserGroupInformation ugi) {
return DT_SELECTOR
.selectToken(getCanonicalUri(), ugi.getTokens(), getConf());
}
@Override
protected int getDefaultPort() {
return getConf().getInt(DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_KEY,
DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_DEFAULT);
}
@Override
public URI getUri() {
return this.uri;
}
/**
* @return the home directory.
*/
public static String getHomeDirectoryString(final UserGroupInformation ugi) {
return "/user/" + ugi.getShortUserName();
}
@Override
public Path getHomeDirectory() {
return makeQualified(new Path(getHomeDirectoryString(ugi)));
}
@Override
public synchronized Path getWorkingDirectory() {
return workingDir;
}
@Override
public synchronized void setWorkingDirectory(final Path dir) {
String result = makeAbsolute(dir).toUri().getPath();
if (!DFSUtil.isValidName(result)) {
throw new IllegalArgumentException(
"Invalid DFS directory name " + result);
}
workingDir = makeAbsolute(dir);
}
private Path makeAbsolute(Path f) {
return f.isAbsolute() ? f : new Path(workingDir, f);
}
static Map<?, ?> jsonParse(final HttpURLConnection c,
final boolean useErrorStream) throws IOException {
if (c.getContentLength() == 0) {
return null;
}
final InputStream in =
useErrorStream ? c.getErrorStream() : c.getInputStream();
if (in == null) {
throw new IOException(
"The " + (useErrorStream ? "error" : "input") + " stream is null.");
}
final String contentType = c.getContentType();
if (contentType != null) {
final MediaType parsed = MediaType.valueOf(contentType);
if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
throw new IOException(
"Content-Type \"" + contentType + "\" is incompatible with \"" +
MediaType.APPLICATION_JSON + "\" (parsed=\"" + parsed + "\")");
}
}
return (Map<?, ?>) JSON.parse(new InputStreamReader(in, Charsets.UTF_8));
}
private static Map<?, ?> validateResponse(final HttpOpParam.Op op,
final HttpURLConnection conn, boolean unwrapException)
throws IOException {
final int code = conn.getResponseCode();
if (code != op.getExpectedHttpResponseCode()) {
final Map<?, ?> m;
try {
m = jsonParse(conn, true);
} catch (Exception e) {
throw new IOException(
"Unexpected HTTP response: code=" + code + " != " +
op.getExpectedHttpResponseCode() + ", " + op.toQueryString() +
", message=" + conn.getResponseMessage(), e);
}
if (m == null) {
throw new IOException(
"Unexpected HTTP response: code=" + code + " != " +
op.getExpectedHttpResponseCode() + ", " + op.toQueryString() +
", message=" + conn.getResponseMessage());
} else if (m.get(RemoteException.class.getSimpleName()) == null) {
return m;
}
final RemoteException re = JsonUtil.toRemoteException(m);
throw unwrapException ? toIOException(re) : re;
}
return null;
}
/**
* Covert an exception to an IOException.
* <p/>
* For a non-IOException, wrap it with IOException.
* For a RemoteException, unwrap it.
* For an IOException which is not a RemoteException, return it.
*/
private static IOException toIOException(Exception e) {
if (!(e instanceof IOException)) {
return new IOException(e);
}
final IOException ioe = (IOException) e;
if (!(ioe instanceof RemoteException)) {
return ioe;
}
final RemoteException re = (RemoteException) ioe;
return re
.unwrapRemoteException(AccessControlException.class, InvalidToken.class,
AuthenticationException.class, AuthorizationException.class,
FileAlreadyExistsException.class, FileNotFoundException.class,
ParentNotDirectoryException.class, UnresolvedPathException.class,
SafeModeException.class, DSQuotaExceededException.class,
NSQuotaExceededException.class);
}
/**
* Return a URL pointing to given path on the namenode.
*
* @param path
* to obtain the URL for
* @param query
* string to append to the path
* @return namenode URL referring to the given path
* @throws IOException
* on error constructing the URL
*/
private URL getNamenodeURL(String path, String query) throws IOException {
final URL url = new URL("http", nnAddr.getHostName(), nnAddr.getPort(),
path + '?' + query);
if (LOG.isTraceEnabled()) {
LOG.trace("url=" + url);
}
return url;
}
Param<?, ?>[] getAuthParameters(final HttpOpParam.Op op) throws IOException {
List<Param<?, ?>> authParams = Lists.newArrayList();
// Skip adding delegation token for token operations because these
// operations require authentication.
boolean hasToken = false;
if (UserGroupInformation.isSecurityEnabled() &&
op != GetOpParam.Op.GETDELEGATIONTOKEN &&
op != PutOpParam.Op.RENEWDELEGATIONTOKEN) {
synchronized (this) {
hasToken = (delegationToken != null);
if (hasToken) {
final String encoded = delegationToken.encodeToUrlString();
authParams.add(new DelegationParam(encoded));
} // else we are talking to an insecure cluster
}
}
UserGroupInformation userUgi = ugi;
if (!hasToken) {
UserGroupInformation realUgi = userUgi.getRealUser();
if (realUgi != null) { // proxy user
authParams.add(new DoAsParam(userUgi.getShortUserName()));
userUgi = realUgi;
}
}
authParams.add(new UserParam(userUgi.getShortUserName()));
return authParams.toArray(new Param<?, ?>[0]);
}
URL toUrl(final HttpOpParam.Op op, final Path fspath,
final Param<?, ?>... parameters) throws IOException {
//initialize URI path and query
final String path = PATH_PREFIX +
(fspath == null ? "/" : makeQualified(fspath).toUri().getPath());
final String query =
op.toQueryString() + Param.toSortedString("&", getAuthParameters(op)) +
Param.toSortedString("&", parameters);
final URL url = getNamenodeURL(path, query);
if (LOG.isTraceEnabled()) {
LOG.trace("url=" + url);
}
return url;
}
private HttpURLConnection getHttpUrlConnection(URL url)
throws IOException, AuthenticationException {
final HttpURLConnection conn;
if (ugi.hasKerberosCredentials()) {
conn = new AuthenticatedURL(AUTH).openConnection(url, authToken);
} else {
conn = (HttpURLConnection) url.openConnection();
}
return conn;
}
/**
* Run a http operation.
* Connect to the http server, validate response, and obtain the JSON output.
*
* @param op
* http operation
* @param fspath
* file system path
* @param parameters
* parameters for the operation
* @return a JSON object, e.g. Object[], Map<?, ?>, etc.
* @throws IOException
*/
private Map<?, ?> run(final HttpOpParam.Op op, final Path fspath,
final Param<?, ?>... parameters) throws IOException {
return new Runner(op, fspath, parameters).run().json;
}
/**
* This class is for initialing a HTTP connection, connecting to server,
* obtaining a response, and also handling retry on failures.
*/
class Runner {
private final HttpOpParam.Op op;
private final URL url;
private final boolean redirected;
private boolean checkRetry;
private HttpURLConnection conn = null;
private Map<?, ?> json = null;
Runner(final HttpOpParam.Op op, final URL url, final boolean redirected) {
this.op = op;
this.url = url;
this.redirected = redirected;
}
Runner(final HttpOpParam.Op op, final Path fspath,
final Param<?, ?>... parameters) throws IOException {
this(op, toUrl(op, fspath, parameters), false);
}
Runner(final HttpOpParam.Op op, final HttpURLConnection conn) {
this(op, null, false);
this.conn = conn;
}
private void init() throws IOException {
checkRetry = !redirected;
try {
conn = getHttpUrlConnection(url);
} catch (AuthenticationException ae) {
checkRetry = false;
throw new IOException("Authentication failed, url=" + url, ae);
}
}
private void connect() throws IOException {
connect(op.getDoOutput());
}
private void connect(boolean doOutput) throws IOException {
conn.setRequestMethod(op.getType().toString());
conn.setDoOutput(doOutput);
conn.setInstanceFollowRedirects(false);
conn.connect();
}
private void disconnect() {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
Runner run() throws IOException {
for (int retry = 0; ; retry++) {
try {
init();
if (op.getDoOutput()) {
twoStepWrite();
} else {
getResponse(op != GetOpParam.Op.OPEN);
}
return this;
} catch (IOException ioe) {
shouldRetry(ioe, retry);
}
}
}
private void shouldRetry(final IOException ioe, final int retry)
throws IOException {
if (checkRetry) {
try {
final RetryPolicy.RetryAction a =
retryPolicy.shouldRetry(ioe, retry, 0, true);
if (a.action == RetryPolicy.RetryAction.RetryDecision.RETRY) {
LOG.info(
"Retrying connect to namenode: " + nnAddr + ". Already tried " +
retry + " time(s); retry policy is " + retryPolicy +
", delay " + a.delayMillis + "ms.");
Thread.sleep(a.delayMillis);
return;
}
} catch (Exception e) {
LOG.warn("Original exception is ", ioe);
throw toIOException(e);
}
}
throw toIOException(ioe);
}
/**
* Two-step Create/Append:
* Step 1) Submit a Http request with neither auto-redirect nor data.
* Step 2) Submit another Http request with the URL from the Location header
* with data.
* <p/>
* The reason of having two-step create/append is for preventing clients to
* send out the data before the redirect. This issue is addressed by the
* "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
* Unfortunately, there are software library bugs (e.g. Jetty 6 http server
* and Java 6 http client), which do not correctly implement "Expect:
* 100-continue". The two-step create/append is a temporary workaround for
* the software library bugs.
*/
HttpURLConnection twoStepWrite() throws IOException {
//Step 1) Submit a Http request with neither auto-redirect nor data.
connect(false);
validateResponse(HttpOpParam.TemporaryRedirectOp.valueOf(op), conn,
false);
final String redirect = conn.getHeaderField("Location");
disconnect();
checkRetry = false;
//Step 2) Submit another Http request with the URL from the Location header with data.
conn = (HttpURLConnection) new URL(redirect).openConnection();
conn.setRequestProperty("Content-Type",
MediaType.APPLICATION_OCTET_STREAM);
conn.setChunkedStreamingMode(32 << 10); //32kB-chunk
connect();
return conn;
}
FSDataOutputStream write(final int bufferSize) throws IOException {
return WebHdfsFileSystem.this.write(op, conn, bufferSize);
}
void getResponse(boolean getJsonAndDisconnect) throws IOException {
try {
connect();
final int code = conn.getResponseCode();
if (!redirected && op.getRedirect() &&
code != op.getExpectedHttpResponseCode()) {
final String redirect = conn.getHeaderField("Location");
json = validateResponse(HttpOpParam.TemporaryRedirectOp.valueOf(op),
conn, false);
disconnect();
checkRetry = false;
conn = (HttpURLConnection) new URL(redirect).openConnection();
connect();
}
json = validateResponse(op, conn, false);
if (json == null && getJsonAndDisconnect) {
json = jsonParse(conn, false);
}
} finally {
if (getJsonAndDisconnect) {
disconnect();
}
}
}
}
private FsPermission applyUMask(FsPermission permission) {
if (permission == null) {
permission = FsPermission.getDefault();
}
return permission.applyUMask(FsPermission.getUMask(getConf()));
}
private HdfsFileStatus getHdfsFileStatus(Path f) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
final Map<?, ?> json = run(op, f);
final HdfsFileStatus status = JsonUtil.toFileStatus(json, true);
if (status == null) {
throw new FileNotFoundException("File does not exist: " + f);
}
return status;
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
statistics.incrementReadOps(1);
return makeQualified(getHdfsFileStatus(f), f);
}
private FileStatus makeQualified(HdfsFileStatus f, Path parent) {
return new FileStatus(f.getLen(), f.isDir(), f.getReplication(),
f.getBlockSize(), f.getModificationTime(), f.getAccessTime(),
f.getPermission(), f.getOwner(), f.getGroup(),
f.isSymlink() ? new Path(f.getSymlink()) : null,
f.getFullPath(parent).makeQualified(getUri(), getWorkingDirectory()));
}
@Override
public boolean mkdirs(Path f, FsPermission permission) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.MKDIRS;
final Map<?, ?> json =
run(op, f, new PermissionParam(applyUMask(permission)));
return (Boolean) json.get("boolean");
}
/**
* Create a symlink pointing to the destination path.
*
* @see org.apache.hadoop.fs.Hdfs#createSymlink(Path, Path, boolean)
*/
public void createSymlink(Path destination, Path f, boolean createParent)
throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.CREATESYMLINK;
run(op, f,
new DestinationParam(makeQualified(destination).toUri().getPath()),
new CreateParentParam(createParent));
}
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
final Map<?, ?> json = run(op, src,
new DestinationParam(makeQualified(dst).toUri().getPath()));
return (Boolean) json.get("boolean");
}
@SuppressWarnings("deprecation")
@Override
public void rename(final Path src, final Path dst,
final Options.Rename... options) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
run(op, src, new DestinationParam(makeQualified(dst).toUri().getPath()),
new RenameOptionSetParam(options));
}
@Override
public void setOwner(final Path p, final String owner, final String group)
throws IOException {
if (owner == null && group == null) {
throw new IOException("owner == null && group == null");
}
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.SETOWNER;
run(op, p, new OwnerParam(owner), new GroupParam(group));
}
@Override
public void setPermission(final Path p, final FsPermission permission)
throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.SETPERMISSION;
run(op, p, new PermissionParam(permission));
}
@Override
public boolean setReplication(final Path p, final short replication)
throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.SETREPLICATION;
final Map<?, ?> json = run(op, p, new ReplicationParam(replication));
return (Boolean) json.get("boolean");
}
@Override
public void setTimes(final Path p, final long mtime, final long atime)
throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.SETTIMES;
run(op, p, new ModificationTimeParam(mtime), new AccessTimeParam(atime));
}
@Override
public long getDefaultBlockSize() {
return getConf().getLongBytes(DFSConfigKeys.DFS_BLOCK_SIZE_KEY,
DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
}
@Override
public short getDefaultReplication() {
return (short) getConf().getInt(DFSConfigKeys.DFS_REPLICATION_KEY,
DFSConfigKeys.DFS_REPLICATION_DEFAULT);
}
FSDataOutputStream write(final HttpOpParam.Op op,
final HttpURLConnection conn, final int bufferSize) throws IOException {
return new FSDataOutputStream(
new BufferedOutputStream(conn.getOutputStream(), bufferSize),
statistics) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
try {
validateResponse(op, conn, true);
} finally {
conn.disconnect();
}
}
}
};
}
@Override
public void concat(final Path trg, final Path[] psrcs) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PostOpParam.Op.CONCAT;
List<String> strPaths = new ArrayList<String>(psrcs.length);
for (Path psrc : psrcs) {
strPaths.add(psrc.toUri().getPath());
}
String srcs = StringUtils.join(",", strPaths);
ConcatSourcesParam param = new ConcatSourcesParam(srcs);
run(op, trg, param);
}
@Override
public FSDataOutputStream create(final Path f, final FsPermission permission,
final boolean overwrite, final int bufferSize, final short replication,
final long blockSize, final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PutOpParam.Op.CREATE;
return new Runner(op, f, new PermissionParam(applyUMask(permission)),
new OverwriteParam(overwrite), new BufferSizeParam(bufferSize),
new ReplicationParam(replication), new BlockSizeParam(blockSize)).run()
.write(bufferSize);
}
@Override
public FSDataOutputStream append(final Path f, final int bufferSize,
final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
final HttpOpParam.Op op = PostOpParam.Op.APPEND;
return new Runner(op, f, new BufferSizeParam(bufferSize)).run()
.write(bufferSize);
}
@SuppressWarnings("deprecation")
@Override
public boolean delete(final Path f) throws IOException {
return delete(f, true);
}
@Override
public boolean delete(Path f, boolean recursive) throws IOException {
final HttpOpParam.Op op = DeleteOpParam.Op.DELETE;
final Map<?, ?> json = run(op, f, new RecursiveParam(recursive));
return (Boolean) json.get("boolean");
}
@Override
public FSDataInputStream open(final Path f, final int buffersize)
throws IOException {
statistics.incrementReadOps(1);
final HttpOpParam.Op op = GetOpParam.Op.OPEN;
final URL url = toUrl(op, f, new BufferSizeParam(buffersize));
return new FSDataInputStream(
new OffsetUrlInputStream(new OffsetUrlOpener(url),
new OffsetUrlOpener(null)));
}
@Override
public void close() throws IOException {
super.close();
if (dtRenewer != null) {
dtRenewer.removeRenewAction(this); // blocks
}
}
class OffsetUrlOpener extends ByteRangeInputStream.URLOpener {
OffsetUrlOpener(final URL url) {
super(url);
}
/**
* Setup offset url and connect.
*/
@Override
protected HttpURLConnection connect(final long offset,
final boolean resolved) throws IOException {
final URL offsetUrl =
offset == 0L ? url : new URL(url + "&" + new OffsetParam(offset));
return new Runner(GetOpParam.Op.OPEN, offsetUrl, resolved).run().conn;
}
}
private static final String OFFSET_PARAM_PREFIX = OffsetParam.NAME + "=";
/**
* Remove offset parameter, if there is any, from the url
*/
static URL removeOffsetParam(final URL url) throws MalformedURLException {
String query = url.getQuery();
if (query == null) {
return url;
}
final String lower = query.toLowerCase();
if (!lower.startsWith(OFFSET_PARAM_PREFIX) &&
!lower.contains("&" + OFFSET_PARAM_PREFIX)) {
return url;
}
//rebuild query
StringBuilder b = null;
for (final StringTokenizer st = new StringTokenizer(query, "&");
st.hasMoreTokens(); ) {
final String token = st.nextToken();
if (!token.toLowerCase().startsWith(OFFSET_PARAM_PREFIX)) {
if (b == null) {
b = new StringBuilder("?").append(token);
} else {
b.append('&').append(token);
}
}
}
query = b == null ? "" : b.toString();
final String urlStr = url.toString();
return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
}
static class OffsetUrlInputStream extends ByteRangeInputStream {
OffsetUrlInputStream(OffsetUrlOpener o, OffsetUrlOpener r) {
super(o, r);
}
/**
* Remove offset parameter before returning the resolved url.
*/
@Override
protected URL getResolvedUrl(final HttpURLConnection connection)
throws MalformedURLException {
return removeOffsetParam(connection.getURL());
}
}
@Override
public FileStatus[] listStatus(final Path f) throws IOException {
statistics.incrementReadOps(1);
final HttpOpParam.Op op = GetOpParam.Op.LISTSTATUS;
final Map<?, ?> json = run(op, f);
final Map<?, ?> rootmap =
(Map<?, ?>) json.get(FileStatus.class.getSimpleName() + "es");
final Object[] array =
(Object[]) rootmap.get(FileStatus.class.getSimpleName());
//convert FileStatus
final FileStatus[] statuses = new FileStatus[array.length];
for (int i = 0; i < array.length; i++) {
final Map<?, ?> m = (Map<?, ?>) array[i];
statuses[i] = makeQualified(JsonUtil.toFileStatus(m, false), f);
}
return statuses;
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(
final String renewer) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETDELEGATIONTOKEN;
final Map<?, ?> m = run(op, null, new RenewerParam(renewer));
final Token<DelegationTokenIdentifier> token =
JsonUtil.toDelegationToken(m);
SecurityUtil.setTokenService(token, nnAddr);
return token;
}
@Override
public Token<?> getRenewToken() {
return delegationToken;
}
@Override
public <T extends TokenIdentifier> void setDelegationToken(
final Token<T> token) {
synchronized (this) {
delegationToken = token;
}
}
private synchronized long renewDelegationToken(final Token<?> token)
throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.RENEWDELEGATIONTOKEN;
TokenArgumentParam dtargParam =
new TokenArgumentParam(token.encodeToUrlString());
final Map<?, ?> m = run(op, null, dtargParam);
return (Long) m.get("long");
}
private synchronized void cancelDelegationToken(final Token<?> token)
throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.CANCELDELEGATIONTOKEN;
TokenArgumentParam dtargParam =
new TokenArgumentParam(token.encodeToUrlString());
run(op, null, dtargParam);
}
@Override
public BlockLocation[] getFileBlockLocations(final FileStatus status,
final long offset, final long length) throws IOException {
if (status == null) {
return null;
}
return getFileBlockLocations(status.getPath(), offset, length);
}
@Override
public BlockLocation[] getFileBlockLocations(final Path p, final long offset,
final long length) throws IOException {
statistics.incrementReadOps(1);
final HttpOpParam.Op op = GetOpParam.Op.GET_BLOCK_LOCATIONS;
final Map<?, ?> m =
run(op, p, new OffsetParam(offset), new LengthParam(length));
return DFSUtil.locatedBlocks2Locations(JsonUtil.toLocatedBlocks(m));
}
@Override
public ContentSummary getContentSummary(final Path p) throws IOException {
statistics.incrementReadOps(1);
final HttpOpParam.Op op = GetOpParam.Op.GETCONTENTSUMMARY;
final Map<?, ?> m = run(op, p);
return JsonUtil.toContentSummary(m);
}
@Override
public MD5MD5CRC32FileChecksum getFileChecksum(final Path p)
throws IOException {
statistics.incrementReadOps(1);
final HttpOpParam.Op op = GetOpParam.Op.GETFILECHECKSUM;
final Map<?, ?> m = run(op, p);
return JsonUtil.toMD5MD5CRC32FileChecksum(m);
}
/**
* Delegation token renewer.
*/
public static class DtRenewer extends TokenRenewer {
@Override
public boolean handleKind(Text kind) {
return kind.equals(TOKEN_KIND);
}
@Override
public boolean isManaged(Token<?> token) throws IOException {
return true;
}
private static WebHdfsFileSystem getWebHdfs(final Token<?> token,
final Configuration conf) throws IOException {
final InetSocketAddress nnAddr = SecurityUtil.getTokenServiceAddr(token);
final URI uri = DFSUtil.createUri(WebHdfsFileSystem.SCHEME, nnAddr);
return (WebHdfsFileSystem) FileSystem.get(uri, conf);
}
@Override
public long renew(final Token<?> token, final Configuration conf)
throws IOException, InterruptedException {
final UserGroupInformation ugi = UserGroupInformation.getLoginUser();
// update the kerberos credentials, if they are coming from a keytab
ugi.reloginFromKeytab();
return getWebHdfs(token, conf).renewDelegationToken(token);
}
@Override
public void cancel(final Token<?> token, final Configuration conf)
throws IOException, InterruptedException {
final UserGroupInformation ugi = UserGroupInformation.getLoginUser();
// update the kerberos credentials, if they are coming from a keytab
ugi.checkTGTAndReloginFromKeytab();
getWebHdfs(token, conf).cancelDelegationToken(token);
}
}
private static class WebHdfsDelegationTokenSelector
extends AbstractDelegationTokenSelector<DelegationTokenIdentifier> {
private static final DelegationTokenSelector hdfsTokenSelector =
new DelegationTokenSelector();
public WebHdfsDelegationTokenSelector() {
super(TOKEN_KIND);
}
Token<DelegationTokenIdentifier> selectToken(URI nnUri,
Collection<Token<?>> tokens, Configuration conf) {
Token<DelegationTokenIdentifier> token =
selectToken(SecurityUtil.buildTokenService(nnUri), tokens);
if (token == null) {
token = hdfsTokenSelector.selectToken(nnUri, tokens, conf);
}
return token;
}
}
}
|
gigaroby/hops
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
|
Java
|
apache-2.0
| 36,109
|
<html>
<head>
<title>JPA Mapping | Ebean</title>
<meta name="layout" content="_layout2/base-mapping-jpa.html"/>
</head>
<body>
<h2>JPA mapping</h2>
<div class="grid g3">
<div>
<h5><a href="id">@Id</a></h5>
<h5><a href="version">@Version</a></h5>
<h5><a href="mapped-superclass">@MappedSuperclass</a></h5>
<h5><a href="enumerated">@Enumerated</a></h5>
</div>
<div>
<h5><a href="one-to-many">@OneToMany</a></h5>
<h5><a href="many-to-one">@ManyToOne</a></h5>
<h5><a href="one-to-one">@OneToOne</a></h5>
<h5><a href="many-to-many">@ManyToMany</a></h5>
</div>
<div>
<h5><a href="lob">@Lob</a></h5>
</div>
</div>
<@next_edit "Naming convention" "naming-convention" "/docs/mapping/jpa/index.html"/>
</body>
</html>
|
ebean-orm/avaje-ebeanorm-website
|
docs/mapping/jpa/index.html
|
HTML
|
apache-2.0
| 763
|
//#include "stdafx.h"
#ifndef __DXTRILIST_INCLUDED__
#define __DXTRILIST_INCLUDED__
#include "ode/include/ode/common.h"
struct dcVector3 {
float x, y, z;
dcVector3() {}
dcVector3(dReal x, dReal y, dReal z) {
this->x = (float)x;
this->y = (float)y;
this->z = (float)z;
}
dcVector3(const dReal* v) {
x = (float)v[0];
y = (float)v[1];
z = (float)v[2];
}
~dcVector3() {}
operator float*() { //&slipch
return reinterpret_cast<float*>(this);
}
/* Add */
dcVector3 operator+(const dcVector3& v) const {
dcVector3 Out;
Out.x = x + v.x;
Out.y = y + v.y;
Out.z = z + v.z;
return Out;
}
dcVector3& operator+=(const dcVector3& v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
/* Sub */
dcVector3 operator-(const dcVector3& v) const {
dcVector3 Out;
Out.x = x - v.x;
Out.y = y - v.y;
Out.z = z - v.z;
return Out;
}
dcVector3& operator-=(const dcVector3& v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
/* Mul */
dcVector3 operator*(const dcVector3& v) const {
dcVector3 Out;
Out.x = x * v.x;
Out.y = y * v.y;
Out.z = z * v.z;
return Out;
}
dcVector3 operator*(float Scalar) const {
dcVector3 Out;
Out.x = x * Scalar;
Out.y = y * Scalar;
Out.z = z * Scalar;
return Out;
}
dcVector3& operator*=(const dcVector3& v) {
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
dcVector3& operator*=(float Scalar) {
x *= Scalar;
y *= Scalar;
z *= Scalar;
return *this;
}
/* Div */
dcVector3 operator/(const dcVector3& v) const {
dcVector3 Out;
Out.x = x / v.x;
Out.y = y / v.y;
Out.z = z / v.z;
return Out;
}
dcVector3 operator/(float Scalar) const {
dcVector3 Out;
Out.x = x / Scalar;
Out.y = y / Scalar;
Out.z = z / Scalar;
return Out;
}
dcVector3& operator/=(const dcVector3& v) {
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
dcVector3& operator/=(float Scalar) {
x /= Scalar;
y /= Scalar;
z /= Scalar;
return *this;
}
/* Negative */
dcVector3& operator-() {
x = -x;
y = -y;
z = -z;
return *this;
}
/* Comparison */
bool operator==(const dcVector3& v) const { return x == v.x && y == v.y && z == v.z; }
bool operator!=(const dcVector3& v) const { return v.x != x || v.y != y || v.z != z; }
float DotProduct(const dcVector3& v) const { return x * v.x + y * v.y + z * v.z; }
dcVector3 CrossProduct(const dcVector3& v) const {
dcVector3 Out;
Out.x = y * v.z - z * v.y;
Out.y = z * v.x - x * v.z;
Out.z = x * v.y - y * v.x;
return Out;
}
float MagnitudeSq() const { return DotProduct(*this); }
float Magnitude() const { return std::sqrt(MagnitudeSq()); }
void Normalize() { operator/=(Magnitude()); }
/* Member access */
float& operator[](int Index) { return *(&x + Index); }
float operator[](int Index) const { return *(&x + Index); }
};
/* Class ID */
extern int dTriListClass;
/* Per triangle callback */
typedef int dTriCallback(dGeomID TriList, dGeomID RefObject, int TriangleIndex);
void dGeomTriListSetCallback(dGeomID g, dTriCallback* Callback);
dTriCallback* dGeomTriListGetCallback(dGeomID g);
/* Per object callback */
typedef void dTriArrayCallback(dGeomID TriList, dGeomID RefObject, const int* TriIndices,
int TriCount);
void dGeomTriListSetArrayCallback(dGeomID g, dTriArrayCallback* ArrayCallback);
dTriArrayCallback* dGeomTriListGetArrayCallback(dGeomID g);
/* Construction */
dxGeom* dCreateTriList(dSpaceID space, dTriCallback* Callback, dTriArrayCallback* ArrayCallback);
/* Setting data */
void dGeomTriListBuild(dGeomID g, const dcVector3* Vertices, int VertexCount, const int* Indices,
int IndexCount);
/* Getting data */
void dGeomTriListGetTriangle(dGeomID g, int Index, dVector3* v0, dVector3* v1, dVector3* v2);
/* Internal types */
class dcTriListCollider;
struct dxTriList {
dReal p[4]; // dxPlane
dTriCallback* Callback;
dTriArrayCallback* ArrayCallback;
dcTriListCollider* Collider;
};
struct dcPlane {
dcVector3 Normal;
float Distance;
dcPlane() {}
dcPlane(const dcVector3& v0, const dcVector3& v1, const dcVector3& v2) {
dcVector3 u = v1 - v0;
dcVector3 v = v2 - v0;
Normal = u.CrossProduct(v);
Distance = v0.DotProduct(Normal);
Normalize();
}
void Normalize() {
float Factor = 1.0f / Normal.Magnitude();
Normal *= Factor;
Distance *= Factor;
}
bool Contains(const dcVector3& RefObject, float Epsilon = 0.0f) const {
return Normal.DotProduct(RefObject) - Distance >= -Epsilon; //@slipch ">=" instead ">"
}
};
template <class T>
const T& dcMAX(const T& x, const T& y) {
return x > y ? x : y;
}
template <class T>
const T& dcMIN(const T& x, const T& y) {
return x < y ? x : y;
}
#endif //__DXTRILIST_INCLUDED__
|
Im-dex/xray-162
|
code/engine/xrPhysics/tri-colliderknoopc/dxTriList.h
|
C
|
apache-2.0
| 5,521
|
require 'rails_helper'
RSpec.describe ActivityMember, type: :model do
it{should belong_to :activity}
it{should belong_to :member}
end
|
Eptikar-IT-Solutions/openngo
|
spec/models/activity_member_spec.rb
|
Ruby
|
apache-2.0
| 139
|
#!/usr/bin/env python3
#
# This file is open source software, licensed to you under the terms
# of the Apache License, Version 2.0 (the "License"). See the NOTICE file
# distributed with this work for additional information regarding copyright
# ownership. 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 os
import sys
import argparse
import subprocess
import signal
import re
boost_tests = [
'futures_test',
'memcached/test_ascii_parser',
'sstring_test',
'output_stream_test',
'httpd',
]
other_tests = [
'smp_test',
]
last_len = 0
def print_status_short(msg):
global last_len
print('\r' + ' '*last_len, end='')
last_len = len(msg)
print('\r' + msg, end='')
print_status_verbose = print
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
if __name__ == "__main__":
all_modes = ['debug', 'release']
parser = argparse.ArgumentParser(description="Seastar test runner")
parser.add_argument('--fast', action="store_true", help="Run only fast tests")
parser.add_argument('--name', action="store", help="Run only test whose name contains given string")
parser.add_argument('--mode', choices=all_modes, help="Run only tests for given build mode")
parser.add_argument('--timeout', action="store",default="300",type=int, help="timeout value for test execution")
parser.add_argument('--jenkins', action="store",help="jenkins output file prefix")
parser.add_argument('--verbose', '-v', action = 'store_true', default = False,
help = 'Verbose reporting')
args = parser.parse_args()
black_hole = open('/dev/null', 'w')
print_status = print_status_verbose if args.verbose else print_status_short
test_to_run = []
modes_to_run = all_modes if not args.mode else [args.mode]
for mode in modes_to_run:
prefix = os.path.join('build', mode, 'tests')
for test in other_tests:
test_to_run.append((os.path.join(prefix, test),'other'))
for test in boost_tests:
test_to_run.append((os.path.join(prefix, test),'boost'))
test_to_run.append(('tests/memcached/test.py --mode ' + mode + (' --fast' if args.fast else ''),'other'))
test_to_run.append((os.path.join(prefix, 'distributed_test') + ' -c 2','other'))
allocator_test_path = os.path.join(prefix, 'allocator_test')
if args.fast:
if mode == 'debug':
test_to_run.append((allocator_test_path + ' --iterations 5','other'))
else:
test_to_run.append((allocator_test_path + ' --time 0.1','other'))
else:
test_to_run.append((allocator_test_path,'other'))
if args.name:
test_to_run = [t for t in test_to_run if args.name in t[0]]
if args.jenkins:
jenkins_boost_log = open(args.jenkins+".boost.xml",'wb')
jenkins_boost_log.write(b'<TestLog><TestSuite name="all">')
all_ok = True
n_total = len(test_to_run)
env = os.environ
# disable false positive due to new (with_alignment(...)) ...
env['ASAN_OPTIONS'] = 'alloc_dealloc_mismatch=0'
for n, test in enumerate(test_to_run):
path = test[0]
prefix = '[%d/%d]' % (n + 1, n_total)
print_status('%s RUNNING %s' % (prefix, path))
signal.signal(signal.SIGALRM, alarm_handler)
if args.jenkins and test[1] == 'boost':
path = path + " --output_format=XML --log_level=all --report_level=no"
proc = subprocess.Popen(path.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,preexec_fn=os.setsid)
signal.alarm(args.timeout)
out = None
err = None
try:
out, err = proc.communicate()
signal.alarm(0)
except:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
proc.kill()
proc.returncode = -1
finally:
if proc.returncode:
print_status('FAILED: %s\n' % (path))
if proc.returncode == -1:
print_status('TIMED OUT\n')
if out:
print('=== stdout START ===')
print(out.decode())
print('=== stdout END ===')
if err:
print('=== stderr START ===')
print(err.decode())
print('=== stderr END ===')
all_ok = False
else:
print_status('%s PASSED %s' % (prefix, path))
if args.jenkins and test[1] == 'boost':
# remove the <TestLog> and </TestLog>
jenkins_boost_log.write(out[9:-10])
if args.jenkins:
jenkins_boost_log.write(b'</TestSuite></TestLog>')
if all_ok:
print('\nOK.')
else:
print_status('')
sys.exit(1)
|
ducthangho/imdb
|
test.py
|
Python
|
apache-2.0
| 5,282
|
{extend name='public/base' /}
{block name="head"}
<title>登陆</title>
{css href="__Css/style.css" /}
{/block}
{block name="body"}
<div class="login-ad fl">
<a href=""><img style="width: 800px;height: 400px;" src="http://pub.chinaunix.net/uploadfile/201204/20120422043659419.jpg"></a>
</div>
<div class="login fr">
<div class="loginHhead">
<h2>用户登录</h2>
<p><span><span class="pull-left"><span>还没有账号? <a href="{:url('User/register')}">立即注册</a></span> </span></p>
</div>
<div class="loginBox">
<form class="login-form" action="__SELF" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">用户名</label>
<div class="controls">
<input type="text" id="inputEmail" class="span3" placeholder="请输入用户名" ajaxurl="/member/checkUserNameUnique.html" errormsg="请填写1-16位用户名" nullmsg="请填写用户名" datatype="*1-16" value="" name="username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">密码</label>
<div class="controls">
<input type="password" id="inputPassword" class="span3" placeholder="请输入密码" errormsg="密码为6-20位" nullmsg="请填写密码" datatype="*6-20" name="password">
</div>
</div>
<!-- <div class="control-group">
<label class="control-label" for="inputPassword">验证码</label>
<div class="controls">
<input type="text" id="inputPassword" class="span3" placeholder="请输入验证码" errormsg="请填写5位验证码" nullmsg="请填写验证码" datatype="*5-5" name="verify">
</div>
</div>
<div class="control-group">
<label class="control-label"></label>
<div class="controls">
<img class="verifyimg reloadverify" alt="点击切换" src="{:url('verify')}" style="cursor:pointer;">
</div>
<div class="controls Validform_checktip text-warning"></div>
</div>-->
<div class="control-group">
<div class="controls" id='btn'>
<!-- <label class="checkbox">
<input type="checkbox"> 自动登陆
</label>-->
<button type="submit" class="btn" >登 陆</button>
</div>
</div>
</form>
</div>
</div>
{/block}
|
mikexie2015/rc
|
view/admin/login/index.html
|
HTML
|
apache-2.0
| 2,923
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.cordovastudio.editors.designer.propertyTable.actions;
/**
* @author Alexander Lobas
*/
public interface IPropertyTableAction {
void update();
}
|
chrimm/cordovastudio
|
src/org/cordovastudio/editors/designer/propertyTable/actions/IPropertyTableAction.java
|
Java
|
apache-2.0
| 761
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.yahoo.container.jdisc.HttpResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A JSON response using Jackson for serialization.
*
* @author bjorncs
*/
public class JacksonJsonResponse<T> extends HttpResponse {
private static final Logger log = Logger.getLogger(JacksonJsonResponse.class.getName());
private final ObjectMapper jsonMapper;
private final boolean prettyPrint;
private final T entity;
public JacksonJsonResponse(int statusCode, T entity) {
this(statusCode, entity, false);
}
public JacksonJsonResponse(int statusCode, T entity, boolean prettyPrint) {
this(statusCode, entity, JacksonJsonMapper.instance, prettyPrint);
}
public JacksonJsonResponse(int statusCode, T entity, ObjectMapper jsonMapper) {
this(statusCode, entity, jsonMapper, false);
}
public JacksonJsonResponse(int statusCode, T entity, ObjectMapper jsonMapper, boolean prettyPrint) {
super(statusCode);
this.entity = entity;
this.jsonMapper = jsonMapper;
this.prettyPrint = prettyPrint;
}
@Override
public void render(OutputStream outputStream) throws IOException {
ObjectWriter writer = prettyPrint ? jsonMapper.writerWithDefaultPrettyPrinter() : jsonMapper.writer();
if (log.isLoggable(Level.FINE)) {
String json = writer.writeValueAsString(entity);
log.log(Level.FINE, "Writing the following JSON to response output stream:\n" + json);
outputStream.write(json.getBytes());
} else {
writer.writeValue(outputStream, entity);
}
}
@Override public String getContentType() { return "application/json"; }
public T getEntity() { return entity; }
}
|
vespa-engine/vespa
|
container-core/src/main/java/com/yahoo/restapi/JacksonJsonResponse.java
|
Java
|
apache-2.0
| 2,072
|
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('resume');
this.route('wip');
});
export default Router;
|
vipul261/vipul261.github.io
|
app/router.js
|
JavaScript
|
apache-2.0
| 245
|
package dataflow
import (
"context"
"strconv"
"time"
"go-common/app/interface/main/app-interface/conf"
"go-common/library/log"
"go-common/library/log/infoc"
)
// Service is search service
type Service struct {
c *conf.Config
infoc *infoc.Infoc
}
// New is search service initial func
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
infoc: infoc.New(c.Infoc),
}
return
}
func (s *Service) Report(c context.Context, eventID, eventType, buvid, fts, messageInfo string, now time.Time) (err error) {
if err = s.infoc.Info(strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo); err != nil {
log.Error("s.infoc2.Info(%v,%v,%v,%v,%v,%v) error(%v)", strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo, err)
}
return
}
|
LQJJ/demo
|
126-go-common-master/app/interface/main/app-interface/service/dataflow/service.go
|
GO
|
apache-2.0
| 808
|
/*
* Copyright (c) Facebook, Inc. and 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 com.facebook.buck.cxx.toolchain;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.core.toolchain.toolprovider.ToolProvider;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.lang.ref.WeakReference;
import java.util.function.Function;
/**
* Custom cache to use with {@link CxxToolProvider} and similar classes that need to cache build
* rules for a given build rule resolver and target configuration.
*
* <p>This is basically two level cache to allow to use build rule resolver as a key in a cache with
* weak keys and target configuration as the key at second level (without weak keys).
*/
public class BuildRuleResolverCacheByTargetConfiguration<T> {
private final LoadingCache<TargetConfiguration, T> cache =
CacheBuilder.newBuilder()
.build(
new CacheLoader<TargetConfiguration, T>() {
@Override
public T load(TargetConfiguration targetConfiguration) {
return delegateBuilder.apply(
toolProvider.resolve(
Preconditions.checkNotNull(buildRuleResolver.get()),
targetConfiguration));
}
});
// BuildRuleResolverCacheByTargetConfiguration instances are values in a cache keyed by a
// weak reference to a BuildRuleResolver. We must also make this a WeakReference, otherwise
// the GC will never free entries in the cache.
private final WeakReference<BuildRuleResolver> buildRuleResolver;
private final ToolProvider toolProvider;
private final Function<Tool, T> delegateBuilder;
public BuildRuleResolverCacheByTargetConfiguration(
BuildRuleResolver buildRuleResolver,
ToolProvider toolProvider,
Function<Tool, T> delegateBuilder) {
this.buildRuleResolver = new WeakReference<>(buildRuleResolver);
this.toolProvider = toolProvider;
this.delegateBuilder = delegateBuilder;
}
public T get(TargetConfiguration targetConfiguration) {
return cache.getUnchecked(targetConfiguration);
}
}
|
JoelMarcey/buck
|
src/com/facebook/buck/cxx/toolchain/BuildRuleResolverCacheByTargetConfiguration.java
|
Java
|
apache-2.0
| 2,935
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# 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.
"""
Manages information about the guest.
This class encapsulates libvirt domain provides certain
higher level APIs around the raw libvirt API. These APIs are
then used by all the other libvirt related classes
"""
from lxml import etree
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import importutils
from nova.i18n import _LE
from nova import utils
from nova.virt.libvirt import config as vconfig
libvirt = None
LOG = logging.getLogger(__name__)
class Guest(object):
def __init__(self, domain):
global libvirt
if libvirt is None:
libvirt = importutils.import_module('libvirt')
self._domain = domain
def __repr__(self):
return "<Guest %(id)d %(name)s %(uuid)s>" % {
'id': self.id,
'name': self.name,
'uuid': self.uuid
}
@property
def id(self):
return self._domain.ID()
@property
def uuid(self):
return self._domain.UUIDString()
@property
def name(self):
return self._domain.name()
@property
def _encoded_xml(self):
return encodeutils.safe_decode(self._domain.XMLDesc(0))
@classmethod
def create(cls, xml, host):
"""Create a new Guest
:param xml: XML definition of the domain to create
:param host: host.Host connection to define the guest on
:returns guest.Guest: Guest ready to be launched
"""
try:
# TODO(sahid): Host.write_instance_config should return
# an instance of Guest
domain = host.write_instance_config(xml)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error defining a domain with XML: %s') %
encodeutils.safe_decode(xml))
return cls(domain)
def launch(self, pause=False):
"""Starts a created guest.
:param pause: Indicates whether to start and pause the guest
"""
flags = pause and libvirt.VIR_DOMAIN_START_PAUSED or 0
try:
return self._domain.createWithFlags(flags)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error launching a defined domain '
'with XML: %s') %
self._encoded_xml, errors='ignore')
def poweroff(self):
"""Stops a running guest."""
self._domain.destroy()
def resume(self):
"""Resumes a suspended guest."""
self._domain.resume()
def enable_hairpin(self):
"""Enables hairpin mode for this guest."""
interfaces = self.get_interfaces()
try:
for interface in interfaces:
utils.execute(
'tee',
'/sys/class/net/%s/brport/hairpin_mode' % interface,
process_input='1',
run_as_root=True,
check_exit_code=[0, 1])
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error enabling hairpin mode with XML: %s') %
self._encoded_xml, errors='ignore')
def get_interfaces(self):
"""Returns a list of all network interfaces for this domain."""
doc = None
try:
doc = etree.fromstring(self._encoded_xml)
except Exception:
return []
interfaces = []
nodes = doc.findall('./devices/interface/target')
for target in nodes:
interfaces.append(target.get('dev'))
return interfaces
def get_vcpus_info(self):
"""Returns virtual cpus information of guest.
:returns: guest.VCPUInfo
"""
vcpus = self._domain.vcpus()
if vcpus is not None:
for vcpu in vcpus[0]:
yield VCPUInfo(
id=vcpu[0], cpu=vcpu[3], state=vcpu[1], time=vcpu[2])
def delete_configuration(self):
"""Undefines a domain from hypervisor."""
try:
self._domain.undefineFlags(
libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE)
except libvirt.libvirtError:
LOG.debug("Error from libvirt during undefineFlags. %d"
"Retrying with undefine", self.id)
self._domain.undefine()
except AttributeError:
# Older versions of libvirt don't support undefine flags,
# trying to remove managed image
try:
if self._domain.hasManagedSaveImage(0):
self._domain.managedSaveRemove(0)
except AttributeError:
pass
self._domain.undefine()
def has_persistent_configuration(self):
"""Whether domain config is persistently stored on the host."""
return self._domain.isPersistent()
def attach_device(self, conf, persistent=False, live=False):
"""Attaches device to the guest.
:param conf: A LibvirtConfigObject of the device to attach
:param persistent: A bool to indicate whether the change is
persistent or not
:param live: A bool to indicate whether it affect the guest
in running state
"""
flags = persistent and libvirt.VIR_DOMAIN_AFFECT_CONFIG or 0
flags |= live and libvirt.VIR_DOMAIN_AFFECT_LIVE or 0
self._domain.attachDeviceFlags(conf.to_xml(), flags=flags)
def get_disk(self, device):
"""Returns the disk mounted at device
:returns LivirtConfigGuestDisk: mounted at device or None
"""
try:
doc = etree.fromstring(self._domain.XMLDesc(0))
except Exception:
return None
node = doc.find("./devices/disk/target[@dev='%s'].." % device)
if node is not None:
conf = vconfig.LibvirtConfigGuestDisk()
conf.parse_dom(node)
return conf
def detach_device(self, conf, persistent=False, live=False):
"""Detaches device to the guest.
:param conf: A LibvirtConfigObject of the device to detach
:param persistent: A bool to indicate whether the change is
persistent or not
:param live: A bool to indicate whether it affect the guest
in running state
"""
flags = persistent and libvirt.VIR_DOMAIN_AFFECT_CONFIG or 0
flags |= live and libvirt.VIR_DOMAIN_AFFECT_LIVE or 0
self._domain.detachDeviceFlags(conf.to_xml(), flags=flags)
def get_xml_desc(self, dump_inactive=False, dump_sensitive=False,
dump_migratable=False):
"""Returns xml description of guest.
:param dump_inactive: Dump inactive domain information
:param dump_sensitive: Dump security sensitive information
:param dump_migratable: Dump XML suitable for migration
:returns string: XML description of the guest
"""
flags = dump_inactive and libvirt.VIR_DOMAIN_XML_INACTIVE or 0
flags |= dump_sensitive and libvirt.VIR_DOMAIN_XML_SECURE or 0
flags |= dump_migratable and libvirt.VIR_DOMAIN_XML_MIGRATABLE or 0
return self._domain.XMLDesc(flags=flags)
def save_memory_state(self):
"""Saves the domain's memory state. Requires running domain.
raises: raises libvirtError on error
"""
self._domain.managedSave(0)
class VCPUInfo(object):
def __init__(self, id, cpu, state, time):
"""Structure for information about guest vcpus.
:param id: The virtual cpu number
:param cpu: The host cpu currently associated
:param state: The running state of the vcpu (0 offline, 1 running, 2
blocked on resource)
:param time: The cpu time used in nanoseconds
"""
self.id = id
self.cpu = cpu
self.state = state
self.time = time
|
CloudServer/nova
|
nova/virt/libvirt/guest.py
|
Python
|
apache-2.0
| 9,019
|
/*
* Joystick.hpp
*
* Created on: Dec 12, 2013
* Author: tgil
*/
#ifndef JOYSTICK_HPP_
#define JOYSTICK_HPP_
#include "IO.hpp"
class Joystick {
public:
Joystick();
static int init();
static bool left(){ return (value() & (1<<Input::JOY_LEFT)) != 0; };
static bool right(){ return (value() & (1<<Input::JOY_RIGHT)) != 0; };
static bool up(){ return (value() & (1<<Input::JOY_UP)) != 0; };
static bool down(){ return (value() & (1<<Input::JOY_DOWN)) != 0; };
static bool center(){ return (value() & (1<<Input::JOY_CENTER)) != 0; };
private:
static pio_sample_t value(){
Pio p(Input::JOY_PORT);
return p.value();
}
};
#endif /* JOYSTICK_HPP_ */
|
CoActionOS/CoActionOS-Apps
|
xively/src/Joystick.hpp
|
C++
|
apache-2.0
| 671
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_92) on Thu Feb 23 15:20:25 CET 2017 -->
<title>nl.esciencecenter.xenon.util Class Hierarchy (Xenon-release 1.2.0 API)</title>
<meta name="date" content="2017-02-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="nl.esciencecenter.xenon.util Class Hierarchy (Xenon-release 1.2.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../nl/esciencecenter/xenon/jobs/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?nl/esciencecenter/xenon/util/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package nl.esciencecenter.xenon.util</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/AdaptorDocGenerator.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">AdaptorDocGenerator</span></a></li>
<li type="circle">nl.esciencecenter.xenon.jobs.<a href="../../../../nl/esciencecenter/xenon/jobs/JobDescription.html" title="class in nl.esciencecenter.xenon.jobs"><span class="typeNameLink">JobDescription</span></a>
<ul>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/JavaJobDescription.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">JavaJobDescription</span></a></li>
</ul>
</li>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/Sandbox.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">Sandbox</span></a></li>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/Sandbox.Pair.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">Sandbox.Pair</span></a></li>
<li type="circle">java.lang.Thread (implements java.lang.Runnable)
<ul>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/InputWriter.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">InputWriter</span></a></li>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/OutputReader.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">OutputReader</span></a></li>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/StreamForwarder.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">StreamForwarder</span></a></li>
</ul>
</li>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/Utils.html" title="class in nl.esciencecenter.xenon.util"><span class="typeNameLink">Utils</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/FileVisitor.html" title="interface in nl.esciencecenter.xenon.util"><span class="typeNameLink">FileVisitor</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
<ul>
<li type="circle">nl.esciencecenter.xenon.util.<a href="../../../../nl/esciencecenter/xenon/util/FileVisitResult.html" title="enum in nl.esciencecenter.xenon.util"><span class="typeNameLink">FileVisitResult</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../nl/esciencecenter/xenon/jobs/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?nl/esciencecenter/xenon/util/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
NLeSC/Xenon
|
docs/versions/1.2.0/javadoc/nl/esciencecenter/xenon/util/package-tree.html
|
HTML
|
apache-2.0
| 7,140
|
package org.edx.indonesiax.model.api;
import android.text.Html;
import java.io.Serializable;
@SuppressWarnings("serial")
public class ResetPasswordResponse implements Serializable {
public String value;
public boolean success;
public boolean isSuccess() {
return success;
}
public String getPrimaryReason() {
if (value == null)
return null;
return Html.fromHtml(value).toString();
}
}
|
ariestiyansyah/indonesiax-android
|
VideoLocker/src/main/java/org/edx/indonesiax/model/api/ResetPasswordResponse.java
|
Java
|
apache-2.0
| 452
|
package playlists.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
/*
* PBKDF2 salted password hashing.
* Author: havoc AT defuse.ca
* www: http://crackstation.net/hashing-security.htm
*/
public class PasswordHash
{
private static final Logger LOGGER = LoggerFactory.getLogger(PasswordHash.class);
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// The following constants may be changed without breaking existing hashes.
public static final int SALT_BYTE_SIZE = 24;
public static final int HASH_BYTE_SIZE = 24;
public static final int PBKDF2_ITERATIONS = 1000;
public static final int ITERATION_INDEX = 0;
public static final int SALT_INDEX = 1;
public static final int PBKDF2_INDEX = 2;
/**
* Returns a salted PBKDF2 hash of the password.
*
* @param password the password to hash
* @return a salted PBKDF2 hash of the password
*/
public static String createHash(String password)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return createHash(password.toCharArray());
}
/**
* Returns a salted PBKDF2 hash of the password.
*
* @param password the password to hash
* @return a salted PBKDF2 hash of the password
*/
public static String createHash(char[] password)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
// Generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt);
// Hash the password
byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
// format iterations:salt:hash
return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
}
/**
* Validates a password using a hash.
*
* @param password the password to check
* @param correctHash the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(String password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return validatePassword(password.toCharArray(), correctHash);
}
/**
* Validates a password using a hash.
*
* @param password the password to check
* @param correctHash the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(char[] password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
// Decode the hash into its parameters
String[] params = correctHash.split(":");
int iterations = Integer.parseInt(params[ITERATION_INDEX]);
byte[] salt = fromHex(params[SALT_INDEX]);
byte[] hash = fromHex(params[PBKDF2_INDEX]);
// Compute the hash of the provided password, using the same salt,
// iteration count, and hash length
byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
// Compare the hashes in constant time. The password is correct if
// both hashes match.
return slowEquals(hash, testHash);
}
/**
* Compares two byte arrays in length-constant time. This comparison method
* is used so that password hashes cannot be extracted from an on-line
* system using a timing attack and then attacked off-line.
*
* @param a the first byte array
* @param b the second byte array
* @return true if both byte arrays are the same, false if not
*/
private static boolean slowEquals(byte[] a, byte[] b)
{
int diff = a.length ^ b.length;
for(int i = 0; i < a.length && i < b.length; i++)
diff |= a[i] ^ b[i];
return diff == 0;
}
/**
* Computes the PBKDF2 hash of a password.
*
* @param password the password to hash.
* @param salt the salt
* @param iterations the iteration count (slowness factor)
* @param bytes the length of the hash to compute in bytes
* @return the PBDKF2 hash of the password
*/
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded();
}
/**
* Converts a string of hexadecimal characters into a byte array.
*
* @param hex the hex string
* @return the hex string decoded into a byte array
*/
private static byte[] fromHex(String hex)
{
byte[] binary = new byte[hex.length() / 2];
for(int i = 0; i < binary.length; i++)
{
binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
}
return binary;
}
/**
* Converts a byte array into a hexadecimal string.
*
* @param array the byte array to convert
* @return a length*2 character string encoding the byte array
*/
private static String toHex(byte[] array)
{
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if(paddingLength > 0)
return String.format("%0" + paddingLength + "d", 0) + hex;
else
return hex;
}
/**
* Tests the basic functionality of the PasswordHash class
*
* @param args ignored
*/
public static void main(String[] args)
{
try
{
// Print out 10 hashes
for(int i = 0; i < 10; i++)
LOGGER.debug(PasswordHash.createHash("p\r\nassw0Rd!"));
// Test password validation
boolean failure = false;
LOGGER.debug("Running tests...");
for(int i = 0; i < 100; i++)
{
String password = ""+i;
String hash = createHash(password);
String secondHash = createHash(password);
if(hash.equals(secondHash)) {
LOGGER.debug("FAILURE: TWO HASHES ARE EQUAL!");
failure = true;
}
String wrongPassword = ""+(i+1);
if(validatePassword(wrongPassword, hash)) {
LOGGER.debug("FAILURE: WRONG PASSWORD ACCEPTED!");
failure = true;
}
if(!validatePassword(password, hash)) {
LOGGER.debug("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
failure = true;
}
}
if(failure)
LOGGER.debug("TESTS FAILED!");
else
LOGGER.debug("TESTS PASSED!");
}
catch(Exception ex)
{
LOGGER.debug("ERROR: " + ex);
}
}
}
|
sornygit/playlists
|
src/main/java/playlists/util/PasswordHash.java
|
Java
|
apache-2.0
| 7,558
|
package com.github.ckwen.je.spring.mvc.web.controller;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.Template;
/**
* <p>
* Title: MainController
* </p>
* <p>
* Description:
* </p>
*
* @author Wen
* @created 2016年12月28日 下午2:15:13
* @modified [who date description]
* @check [who date description]
*/
@Controller
@RequestMapping("email")
public class EmailController {
private static final String UTF_8 = "utf-8";
private static final String REDIRECT_EMAIL = "redirect:/email/";
private static final String ACTION_STATE = "actionState";
private static final String SUCCESS = "success";
private static final String ERROR = "error";
@Value("${mail.username}")
private String mailFrom;
@Autowired
private JavaMailSender sender;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private VelocityEngine velocityEngine;
@RequestMapping()
public String index() {
return "email_send";
}
/**
* 最简单的文本邮件
*
* @param redirectAttributes
* @param email
* @param subject
* @param content
* @return
*/
@RequestMapping("send/1")
public String send1(RedirectAttributes redirectAttributes, String email, String subject, String content) {
try {
Assert.isTrue(StringUtils.isNotBlank(email));
Assert.isTrue(StringUtils.isNotBlank(subject));
Assert.isTrue(StringUtils.isNotBlank(content));
System.out.printf("email:%s, subject:%s, content:%s\n", email, subject, content);
SimpleMailMessage smm = new SimpleMailMessage();
smm.setFrom(mailFrom);
smm.setTo(email);
smm.setSubject(subject);
smm.setText(content);
sender.send(smm);
redirectAttributes.addFlashAttribute(ACTION_STATE, SUCCESS);
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute(ACTION_STATE, ERROR);
}
return REDIRECT_EMAIL;
}
/**
* 发送html格式的邮件
*
* @param redirectAttributes
* @param email
* @param subject
* @param content
* @return
*/
@RequestMapping("send/2")
public String send2(RedirectAttributes redirectAttributes, String email, String subject, String content) {
try {
Assert.isTrue(StringUtils.isNotBlank(email));
Assert.isTrue(StringUtils.isNotBlank(subject));
Assert.isTrue(StringUtils.isNotBlank(content));
System.out.printf("email:%s, subject:%s, content:%s\n", email, subject, content);
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setFrom(mailFrom);
messageHelper.setTo(email);
messageHelper.setSubject(subject);
messageHelper.setText(content, true);
sender.send(mimeMessage);
redirectAttributes.addFlashAttribute(ACTION_STATE, SUCCESS);
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute(ACTION_STATE, ERROR);
}
return REDIRECT_EMAIL;
}
/**
* Velocity
*
* @param redirectAttributes
* @param email
* @param subject
* @return
*/
@RequestMapping("send/3")
public String send3(RedirectAttributes redirectAttributes, String email, String subject) {
try {
Assert.isTrue(StringUtils.isNotBlank(email));
Assert.isTrue(StringUtils.isNotBlank(subject));
System.out.printf("email:%s, subject:%s\n", email, subject);
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, UTF_8);
messageHelper.setFrom(mailFrom);
messageHelper.setTo(email);
messageHelper.setSubject(subject);
//
Map<String, Object> map = new HashMap<>();
map.put("email", email);
map.put("subject", subject);
String templateLocation = "template_velocity/test3.vm";
String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, UTF_8, map);
messageHelper.setText(content, true);
sender.send(mimeMessage);
redirectAttributes.addFlashAttribute(ACTION_STATE, SUCCESS);
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute(ACTION_STATE, ERROR);
}
return REDIRECT_EMAIL;
}
/**
* FreeMarker
*
* @param redirectAttributes
* @param email
* @param subject
* @return
*/
@RequestMapping("send/4")
public String send4(RedirectAttributes redirectAttributes, String email, String subject) {
try {
Assert.isTrue(StringUtils.isNotBlank(email));
Assert.isTrue(StringUtils.isNotBlank(subject));
System.out.printf("email:%s, subject:%s\n", email, subject);
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, UTF_8);
messageHelper.setFrom(mailFrom);
messageHelper.setTo(email);
messageHelper.setSubject(subject);
//
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("test3.vtl");
Map<String, Object> map = new HashMap<>();
map.put("email", email);
map.put("subject", subject);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
messageHelper.setText(content, true);
sender.send(mimeMessage);
redirectAttributes.addFlashAttribute(ACTION_STATE, SUCCESS);
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute(ACTION_STATE, ERROR);
}
return REDIRECT_EMAIL;
}
}
|
ckwen/je
|
je-spring-mvc/src/main/java/com/github/ckwen/je/spring/mvc/web/controller/EmailController.java
|
Java
|
apache-2.0
| 7,329
|
// .po file like language pack
plupload.addI18n({
'Select files' : 'Vyberte soubory',
'Add files to the upload queue and click the start button.' : 'Přidejte soubory do fronty a pak spusťte nahrávání.',
'Filename' : 'Název souboru',
'Status' : 'Status',
'Size' : 'Velikost',
'Add Files' : 'Přidat soubory',
'Stop current upload' : 'Zastavit nahrávání',
'Start uploading queue' : 'Spustit frontu nahrávání',
'Drag files here.' : 'Sem přetáhněte soubory.',
'Start Upload': 'Spustit nahrávání',
'Uploaded %d/%d files': 'Nahráno %d/%d souborů'
});
|
cunhafernando/antoniofarias
|
afadmin/includes/plupload/i18n/cs.js
|
JavaScript
|
apache-2.0
| 590
|
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout}">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title th:utext="#{screen.saml.idp.discovery}">SAML2 Identity Provider Discovery</title>
<link href="../../static/css/cas.css" rel="stylesheet" th:remove="tag" />
<link rel="stylesheet"
type="text/css"
href="../static/css/samlidp/idpselect.css"
th:href="@{/css/samlidp/idpselect.css}" />
</head>
<body>
<main role="main" class="container mt-3 mb-3">
<div layout:fragment="content" class="mdc-card card p-4 m-auto w-lg-66">
<h2 th:utext="#{screen.saml.idp.discovery}">SAML Identity Provider Discovery</h2>
<div id="errorDiv" class="banner banner-danger alert alert-danger" role="alert" style="display:none;"></div>
<div id="idpSelect"></div>
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
function IdPSelectUIParametersForCAS(obj) {
obj.myEntityID = /*[[${entityIds}]]*/;
var defaultReturn = location.href;
if (!defaultReturn.endsWith("/")) {
defaultReturn += "/";
}
defaultReturn += "redirect";
obj.defaultReturn = defaultReturn;
var dataSource = /*[[${casServerPrefix}]]*/ ;
if (!dataSource.endsWith("/")) {
dataSource += "/";
}
dataSource += "idp/discovery/feed";
obj.dataSource = dataSource;
obj.returnWhiteList = '^' + /*[[${entityId}]]*/ + '.*$';
obj.defaultLogo = /*[[@{/images/shield.png}]]*/ ;
}
/*]]>*/
</script>
<script th:src="@{/js/samlidp/idpselect_config.js}"></script>
<script th:src="@{/js/samlidp/idpselect.js}"></script>
</div>
</main>
</body>
</html>
|
apereo/cas
|
support/cas-server-support-thymeleaf/src/main/resources/templates/saml2-discovery/casSamlIdPDiscoveryView.html
|
HTML
|
apache-2.0
| 2,059
|
package com.thinkgem.jeesite.common.test;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* Spring 单元测试基类
* @author ThinkGem
* @version 2013-05-15
*/
@ActiveProfiles("production")
@WebAppConfiguration
@ContextConfiguration(locations = {"/spring-context.xml"})
public class SpringTransactionalContextTests extends AbstractTransactionalJUnit4SpringContextTests {
protected DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
this.dataSource = dataSource;
}
}
|
wangning82/FTC
|
src/main/java/com/thinkgem/jeesite/common/test/SpringTransactionalContextTests.java
|
Java
|
apache-2.0
| 879
|
/**
* 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.camel.component.cxf.converter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.apache.camel.component.cxf.CxfPayload;
import org.apache.camel.test.junit4.ExchangeTestSupport;
import org.junit.Before;
import org.junit.Test;
public class CxfPayloadConverterTest extends ExchangeTestSupport {
private Document document;
private CxfPayload<String[]> payload;
private FileInputStream inputStream;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
File file = new File("src/test/resources/org/apache/camel/component/cxf/converter/test.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(file);
document.getDocumentElement().normalize();
List<Element> body = new ArrayList<Element>();
body.add(document.getDocumentElement());
payload = new CxfPayload<String[]>(new ArrayList<String[]>(), body);
inputStream = new FileInputStream(file);
}
@Test
public void testDocumentToCxfPayload() {
CxfPayload<String[]> payload = CxfPayloadConverter.documentToCxfPayload(document, exchange);
assertNotNull(payload);
assertEquals("Get a wrong size of body", 1, payload.getBody().size());
}
@Test
public void testNodeListToCxfPayload() {
NodeList nodeList = document.getChildNodes();
CxfPayload<String[]> payload = CxfPayloadConverter.nodeListToCxfPayload(nodeList, exchange);
assertNotNull(payload);
assertEquals("Get a wrong size of body", 1, payload.getBody().size());
}
@Test
public void testCxfPayloadToNodeList() {
NodeList nodeList = CxfPayloadConverter.cxfPayloadToNodeList(payload, exchange);
assertNotNull(nodeList);
assertEquals("Get a worng size of nodeList", 1, nodeList.getLength());
}
@Test
public void testToCxfPayload() {
// use default type converter
exchange.getIn().setBody(inputStream);
CxfPayload payload = exchange.getIn().getBody(CxfPayload.class);
assertTrue(payload instanceof CxfPayload);
assertEquals("Get a wrong size of body", 1, payload.getBody().size());
}
@Test
public void testFromCxfPayload() {
exchange.getIn().setBody(payload);
InputStream inputStream = exchange.getIn().getBody(InputStream.class);
assertTrue(inputStream instanceof InputStream);
}
}
|
everttigchelaar/camel-svn
|
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterTest.java
|
Java
|
apache-2.0
| 3,773
|
#pragma once
#include <BaseGL.hpp>
#include <OpenGL.hpp>
namespace kepler {
namespace gl {
// Generic OpenGL buffer.
// Target is the target parameter from glBindBuffer.
template<GLenum Target>
class Buffer {
public:
Buffer() : _handle(0) {}
Buffer(GLsizeiptr size, const GLvoid* data, GLenum usage) {
glGenBuffers(1, &_handle);
glBindBuffer(Target, _handle);
glBufferData(Target, size, data, usage);
}
~Buffer() noexcept {
if (_handle) {
glDeleteBuffers(1, &_handle);
}
}
// Not copyable
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
// Movable
Buffer(Buffer&& other) : _handle(other._handle) {
other._handle = 0;
}
Buffer& operator=(Buffer&& other) {
if (this != &other) {
std::swap(_handle, other._handle);
other.destroy();
}
return *this;
}
/// Binds this buffer.
void bind() const {
glBindBuffer(Target, _handle);
}
void destroy() {
if (_handle) {
glDeleteBuffers(1, &_handle);
_handle = 0;
}
}
// Allows Buffer to be used in an if statement
explicit operator bool() const noexcept {
return _handle != 0;
}
private:
BufferHandle _handle;
};
} // namespace gl
} // namespace kepler
|
dgough/kepler3d
|
kepler-gl/src/Buffer.hpp
|
C++
|
apache-2.0
| 1,380
|
#!/bin/bash
set -e # Exit with nonzero exit code if anything fails
curlretry() {
curl --retry 2 "$@"
}
curlbikeshed() {
INPUT_FILE=$(find . -maxdepth 1 -name "*.bs" -print -quit)
# The Accept: header ensures we get the error output even when warnings are produced, per
# https://github.com/whatwg/whatwg.org/issues/227#issuecomment-419969339.
HTTP_STATUS=$(curlretry https://api.csswg.org/bikeshed/ \
--output "$1" \
--write-out "%{http_code}" \
--header "Accept: text/plain, text/html" \
-F die-on=error \
-F file=@"$INPUT_FILE" \
"${@:2}")
if [[ "$HTTP_STATUS" != "200" ]]; then
cat "$1"
rm -f "$1"
exit 22
fi
}
cd docs && curlbikeshed "index.html"
if [ -d out ]; then
echo Copy the generated spec into out/index.html
cp index.html out/index.html
fi
|
slightlyoff/ServiceWorker
|
compile.sh
|
Shell
|
apache-2.0
| 982
|
# FrostPortal
## A lightweight, simple, and beautiful Minecraft portal website.

Frost is a very easy-to-use web portal built for Minecraft servers, with quick installation, easy configuration, and a beautiful, minimalist design. This web portal will make your server instantly look more professional with very little work. Developed entirely with HTML, CSS, and PHP, it is lightning-fast and highly-compatible.
This software is released under the Apache 2.0 license, and is developed in its entirety by myself, in addition to usage of [Julian Spravil's PHP Minecraft Server Query classes](https://github.com/FunnyItsElmo/PHP-Minecraft-Server-Status-Query/).
[Working Demo](https://tudedude.me/demos/frostPortal/)
SHA1 Checksum: 43D086939805ACF4E7B35956EA35A444
#### Default Image Credits:
* [missing.png](https://cdn.pixabay.com/photo/2016/10/18/18/19/question-mark-1750942_960_720.png)
* [default link images](http://minecraft.gamepedia.com)
* [background](http://static.fjcdn.com/pictures/Aeries+minecraft+server+spawn+built+on+the+aeries+minecraft+server+mcmcaeriescom_11f117_4527838.png)
* [forums.png](http://minecraftenchantmentcalculator.com/shared/logo.png)
### Installation
To install, simply follow these steps.
#### Requirements:
Web server with PHP
Access to server
#### Instructions
Un-zip the file. You will see the file structure (4 files and 2 folders).
Upload the files to server's web root (generally "public_html" or "www" with shared hosting)
Replace the default images with your own in the "assets" folder, or use the defaults. Filenames should be kept the same, or any changes reflected in the config.ini.
Configure website following built-in instructions or the tutorial below.
Configuration
This portal stores its settings in the config.ini stored in the main project folder. This configuration file is meant to be easy to work with, however the link structure may be confusing to some. A quick tutorial is provided below the default configuration.
### Default Configuration File
```
<?php
; <?php
; die();
; /*
;-----------------------------------------------------------------;
; Frost Portal by Tudedude ;
; Configuration ;
;-----------------------------------------------------------------;
; ;
; Copyright 2017 Carson Faatz/Tudedude ;
; ;
; 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 ;
; ;
;-----------------------------------------------------------------;
; This configuration can be used to alter file paths, link paths, ;
; and any text string used on the page. ;
;-----------------------------------------------------------------;
;---------------------------;
; DEFAULT TEXT PLACEHOLDERS ;
;---------------------------;
; %name% - the value of the ;
; servername variable; the ;
; name of the server ;
; ;
; %year% - the current year ;
;---------------------------;
; Whether or not to show the panel with the server IP
ippanel = true
; Whether or not to show the player count of the server
; Will not show if ippanel is set to false.
pingserver = true
; The name of the server.
servername = "Tudedude's Frost Portal"
; The IP or domain of the server.
serverip = "mc.hypixel.net"
; The port of the server
; This value must still be set if it is 25565.
serverport = 25565
; This section defines what links should appear on the page.
; These should be defined in the following format:
; links[NAME] = "LINK"
; where NAME is the title for the link, and LINK is the link
; to visit.
links[Store] = "https://tudedude.me"
links[Vote] = "https://tudedude.me"
links[Forums] = "https://tudedude.me"
links[Staff] = "https://tudedude.me"
; This section defines the images that should be associated
; with the links on the page. The name _must_ be the same
; as the name specified in the links entry.
images[Store] = "./assets/store.png"
images[Vote] = "./assets/vote.png"
images[Forums] = "./assets/forums.png"
images[Staff] = "./assets/staff.png"
; This is the path to be used if an image is not defined
; (or not defined correctly) for a link.
missing = "./assets/missing.png"
; This defines the title of the website
title = "%name% | Home"
; This is the path to the background that should be used
background = "./assets/background.png"
; This is the path to the logo that should be used
logo = "./assets/logo.png"
; This setting controls whether or not CSS should be minified
; Minification will result in reduced CSS filesize by removing
; unnecessary characters such as spaces and comments. This will
; not affect the original file, just how it is served to the
; browser.
minifycss = "true"
; */
; ?>
```
### Creating Links
The links section holds all the destinations for the links that should appear on the main page. To define a new link, use the format as follows:
links[name] = "https://example.com"
The name will appear under the link's on the portal, and must be the same name used when defining images. To define an image, use the format as follows:
images[name] = "./assets/image.png"
If the name is not the same between the link and image definition, the image will not show up, and be replaced by the image specified by the missing option. All image links should either be relative paths or direct links.
|
Tudedude/FrostPortal
|
README.md
|
Markdown
|
apache-2.0
| 5,993
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cd_subscription', '0004_auto_20161125_1901'),
]
operations = [
migrations.AlterField(
model_name='cdsubscription',
name='badgelength',
field=models.IntegerField(blank=True, default=0, verbose_name='Length badge image'),
),
migrations.AlterField(
model_name='cdsubscription',
name='emailparent',
field=models.EmailField(blank=True, max_length=40, default='', verbose_name='Email parent'),
),
migrations.AlterField(
model_name='cdsubscription',
name='emailplayer',
field=models.EmailField(blank=True, max_length=40, default='', verbose_name='Email player'),
),
migrations.AlterField(
model_name='cdsubscription',
name='fullnameattendant',
field=models.CharField(blank=True, max_length=50, default='', verbose_name='Full name responsible on site'),
),
migrations.AlterField(
model_name='cdsubscription',
name='fullnameparent',
field=models.CharField(blank=True, max_length=50, default='', verbose_name='Full name parent'),
),
migrations.AlterField(
model_name='cdsubscription',
name='mobileattendant',
field=models.CharField(blank=True, max_length=15, default='', verbose_name='GSM number responsible on site'),
),
migrations.AlterField(
model_name='cdsubscription',
name='mobileparent',
field=models.CharField(blank=True, max_length=15, default='', verbose_name='GSM parent'),
),
migrations.AlterField(
model_name='cdsubscription',
name='mobileplayer',
field=models.CharField(blank=True, max_length=15, default='', verbose_name='GSM player'),
),
migrations.AlterField(
model_name='cdsubscription',
name='payamount',
field=models.IntegerField(blank=True, default=0, verbose_name='Amount to pay'),
),
migrations.AlterField(
model_name='cdsubscription',
name='paydate',
field=models.DateField(null=True, verbose_name='Payment date'),
),
]
|
cropr/bjk2017
|
cd_subscription/migrations/0005_auto_20161125_1908.py
|
Python
|
apache-2.0
| 2,446
|
package com.apps.howard.vicissitude.activities.fragments;
//region Imports
/*
Android imports.
*/
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.apps.howard.vicissitude.R;
import com.apps.howard.vicissitude.activities.LogActivity;
import com.apps.howard.vicissitude.activities.SmsEditActivity;
import com.apps.howard.vicissitude.classes.SmsAlarm;
import com.apps.howard.vicissitude.classes.Utilities;
import com.apps.howard.vicissitude.classes.adapters.SmsAdapter;
import com.apps.howard.vicissitude.classes.tasks.FetchAlarmDataTask;
import java.io.File;
/*
Application imports.
*/
/*
Java imports.
*/
//endregion
public class SmsFragment extends Fragment {
//region Fields
/*
SmsAlarmAdapter for the MainActivity ListView
*/
public SmsAdapter mSmsAdapter;
/*
Used as the title for the New Alarm dialog.
*/
private String dialog_text = "";
//endregion
//region Android Lifecyle
/*
Android lifecycle.
*/
@Override
public void onStart() {
super.onStart();
loadAlarms();
}
@Override
public void onResume() {
super.onResume();
loadAlarms();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//endregion
//region Menu Code
/*
Inflate the SMS Menu fragment
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sms_fragment, menu);
}
/*
Logic for actionbar items
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add_alarm) {
addAlarm();
}
if (id == R.id.action_activate_all) {
boolean ACTIVATE_ALL = true;
switchAll(true);
}
if (id == R.id.action_deactivate_all) {
boolean DEACTIVATE_ALL = false;
switchAll(false);
}
if (id == R.id.action_view_logs) {
Intent viewLogs = new Intent(this.getActivity(), LogActivity.class);
startActivity(viewLogs);
return true;
}
if (id == R.id.action_help) {
Utilities.makeToast(this.getActivity(), getString(R.string.spartan_easter_egg));
}
return super.onOptionsItemSelected(item);
}
/*
Create main activity
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sms, container, false);
ListView l = (ListView) rootView.findViewById(R.id.listview_sms_alarms);
l.setOnItemClickListener(listViewClick());
return rootView;
}
/*
ListView context menu
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listview_sms_alarms) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_list_actions, menu);
}
}
/*
Action Bar Buttons
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editAlarm(info.position);
return true;
case R.id.delete:
deleteAlarm(info.position);
return true;
default:
return super.onContextItemSelected(item);
}
}
//endregion
//region Internal Methods
private void loadAlarms() {
File[] files = Utilities.getAllJsonFiles(getActivity());
if (files != null)
new FetchAlarmDataTask(this).execute(files);
}
private void addAlarm() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.sms_fragment_new_alarm_dialog_title);
builder.setPositiveButton("OK", positiveDialogButton(builder));
builder.setNegativeButton("Cancel", negativeDialogButton());
builder.show();
}
private void editAlarm(int position) {
SmsAlarm alarm = mSmsAdapter.getItem(position);
Intent smsAlertEditIntent = new Intent(getActivity(), SmsEditActivity.class)
.putExtra("alarm-class", alarm);
startActivity(smsAlertEditIntent);
}
private void deleteAlarm(int position) {
SmsAlarm alarm = mSmsAdapter.getItem(position);
File json = new File(alarm.location);
if (json.delete())
mSmsAdapter.remove(alarm);
}
private void switchAll(boolean Switch) {
ListView l = (ListView) this.getActivity().findViewById(R.id.listview_sms_alarms);
for (int i = 0; i < l.getCount(); i++) {
SmsAlarm alarm = (SmsAlarm) l.getItemAtPosition(i);
SmsAlarm.Save(new SmsAlarm(alarm.name, alarm.summary, alarm.body_test,
alarm.triggeredSenders, alarm.triggeredExpressions,
alarm.fromHour, alarm.fromMinute, alarm.toHour,
alarm.toMinute, alarm.location, Switch,
this.getActivity()), this.getActivity());
}
mSmsAdapter.clear();
loadAlarms();
}
//region Listeners
private AdapterView.OnItemClickListener listViewClick() {
return new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
editAlarm(position);
}
};
}
private DialogInterface.OnClickListener positiveDialogButton(AlertDialog.Builder builder) {
/*
Create the text box
*/
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
/*
Create positive button
*/
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog_text = input.getText().toString().trim();
if (dialog_text.isEmpty()) {
Utilities.makeToast(getActivity(), getString(R.string.create_sms_blank_name));
dialog.cancel();
return;
}
SmsAlarm newAlarm = new SmsAlarm(dialog_text, getActivity());
Intent smsAlertEditIntent = new Intent(getActivity(), SmsEditActivity.class)
.putExtra("alarm-class", newAlarm)
.putExtra("is-new", true);
startActivity(smsAlertEditIntent);
}
};
}
private DialogInterface.OnClickListener negativeDialogButton() {
/*
Create negative button
*/
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
};
}
//endregion
//endregion
}
|
hazardfn/Vicissitude
|
app/src/main/java/com/apps/howard/vicissitude/activities/fragments/SmsFragment.java
|
Java
|
apache-2.0
| 7,934
|
/*
* Copyright 2021 HM Revenue & Customs
*
* 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 uk.gov.hmrc.ct.ct600.v2
import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtInteger}
import uk.gov.hmrc.ct.ct600.v2.retriever.CT600BoxRetriever
case class B15(value: Int) extends CtBoxIdentifier(name = "Income within Sch D Case VI") with CtInteger
//TODO
object B15 extends Calculated[B15, CT600BoxRetriever] {
override def calculate(fieldValueRetriever: CT600BoxRetriever): B15 = {
// B15(fieldValueRetriever.b12() + fieldValueRetriever.b13() + fieldValueRetriever.b14())
???
}
}
|
hmrc/ct-calculations
|
src/main/scala/uk/gov/hmrc/ct/ct600/v2/B15.scala
|
Scala
|
apache-2.0
| 1,115
|
export const template = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><script>//inject_title</script></title>
<base target="_self">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<script>//inject_meta</script>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui">
<meta name="format-detection" content="telephone=no,email=no,address=no">
<meta name="format-detection" content="email=no">
<meta name="format-detection" content="address=no">
<meta name="format-detection" content="telephone=no">
<meta name="HandheldFriendly" content="true">
<meta name="mobile-web-app-capable" content="yes">
<!-- IE/Edge -->
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- for Facebook -->
<meta property="og:title" content="xxx">
<meta property="og:type" content="website">
<meta property="og:description" content="xxx">
<meta property="og:image" content="xxx">
<meta name="copyright" content="Copyright (c) xxx">
<meta name="theme-color" content="#371273" />
<link href="//cdn.bootcss.com/meyer-reset/2.0/reset.min.css" rel="stylesheet">
<script>//inject_component_styles</script>
</head>
<body>
<div id="root">
<div><script>//inject_html</script></div>
</div>
<script>//inject_redux_state</script>
<script>//inject_js</script>
</body>
</html>
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?e76ecaf50bab944f2c62edf3f6588a9d";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
`
|
dongwenxiao/websage.cn
|
src/html.js
|
JavaScript
|
apache-2.0
| 2,223
|
var EPG = {
pressLeft : function() {
},
pressRight : function() {
},
pressUp : function() {
var element = document.getElementsByClassName("selected")[0];
var previousSiblingElement = element.previousElementSibling;
if (null != previousSiblingElement) {
classList(element).remove("selected");
classList(previousSiblingElement).add("selected");
}
},
pressDown : function() {
var element = document.getElementsByClassName("selected")[0];
var nextSiblingElement = element.nextElementSibling;
if (null != nextSiblingElement) {
classList(element).remove("selected");
classList(nextSiblingElement).add("selected");
}
},
pressEnter : function() {
var gameId = document.getElementsByClassName("selected")[0].id;
window.location.href = "http://39.98.243.254:8080/lobby/game.jsp?gamename="
+ gameId;
}
};
|
dyzhxsl3897/goliveiptv
|
lobby/src/main/webapp/resources/js/mylib.js
|
JavaScript
|
apache-2.0
| 840
|
#!/usr/bin/env bash
for i in {1..50};
do gcloud compute instances create perf-$i --image-family=ubuntu-1804-lts --image-project=gce-uefi-images --preemptible --machine-type=n1-standard-2 --zone=us-central1-a --metadata startup-script='#! /bin/bash
ulimit -n 65535
wget https://storage.googleapis.com/hey-release/hey_linux_amd64
mv hey_linux_amd64 hey
chmod +x hey
export PROXY_ENDPOINT=amer-cs-hybrid-demo13-test.hybrid-apigee.net
export API_KEY=5DiNM3MoV8FnpiJ7iJEQVKQMx4bxTQrm
while ((1)); do ./hey -n 20000 -c 500 https://${PROXY_ENDPOINT}/httpbin/anything?apikey=${API_KEY}; sleep 1; done
EOF'
sleep 10;
done
|
apigee/ansible-opdk-accelerator
|
infrastructure/gce-management/performance-testing/perf-test.sh
|
Shell
|
apache-2.0
| 623
|
/*
* 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.syncope.core.connid;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.syncope.common.types.PasswordPolicySpec;
import org.apache.syncope.core.persistence.beans.ExternalResource;
import org.apache.syncope.core.persistence.beans.PasswordPolicy;
import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
import org.apache.syncope.core.persistence.dao.PolicyDAO;
import org.apache.syncope.core.policy.PolicyPattern;
import org.apache.syncope.core.util.InvalidPasswordPolicySpecException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Generate random passwords according to given policies.
*
* @see PasswordPolicy
*/
@Component
public class PasswordGenerator {
private static final String[] SPECIAL_CHARS = {"", "!", "£", "%", "&", "(", ")", "?", "#", "_", "$"};
@Autowired
private PolicyDAO policyDAO;
public String generate(final List<PasswordPolicySpec> ppSpecs)
throws InvalidPasswordPolicySpecException {
PasswordPolicySpec policySpec = merge(ppSpecs);
check(policySpec);
return generate(policySpec);
}
public String generate(final SyncopeUser user)
throws InvalidPasswordPolicySpecException {
List<PasswordPolicySpec> ppSpecs = new ArrayList<PasswordPolicySpec>();
PasswordPolicy globalPP = policyDAO.getGlobalPasswordPolicy();
if (globalPP != null && globalPP.getSpecification() != null) {
ppSpecs.add(globalPP.<PasswordPolicySpec>getSpecification());
}
for (SyncopeRole role : user.getRoles()) {
if (role.getPasswordPolicy() != null && role.getPasswordPolicy().getSpecification() != null) {
ppSpecs.add(role.getPasswordPolicy().<PasswordPolicySpec>getSpecification());
}
}
for (ExternalResource resource : user.getResources()) {
if (resource.getPasswordPolicy() != null && resource.getPasswordPolicy().getSpecification() != null) {
ppSpecs.add(resource.getPasswordPolicy().<PasswordPolicySpec>getSpecification());
}
}
PasswordPolicySpec policySpec = merge(ppSpecs);
check(policySpec);
return generate(policySpec);
}
private PasswordPolicySpec merge(final List<PasswordPolicySpec> ppSpecs) {
PasswordPolicySpec fpps = new PasswordPolicySpec();
fpps.setMinLength(0);
fpps.setMaxLength(1000);
for (PasswordPolicySpec policySpec : ppSpecs) {
if (policySpec.getMinLength() > fpps.getMinLength()) {
fpps.setMinLength(policySpec.getMinLength());
}
if ((policySpec.getMaxLength() != 0) && ((policySpec.getMaxLength() < fpps.getMaxLength()))) {
fpps.setMaxLength(policySpec.getMaxLength());
}
fpps.setPrefixesNotPermitted(policySpec.getPrefixesNotPermitted());
fpps.setSuffixesNotPermitted(policySpec.getSuffixesNotPermitted());
if (!fpps.isNonAlphanumericRequired()) {
fpps.setNonAlphanumericRequired(policySpec.isNonAlphanumericRequired());
}
if (!fpps.isAlphanumericRequired()) {
fpps.setAlphanumericRequired(policySpec.isAlphanumericRequired());
}
if (!fpps.isDigitRequired()) {
fpps.setDigitRequired(policySpec.isDigitRequired());
}
if (!fpps.isLowercaseRequired()) {
fpps.setLowercaseRequired(policySpec.isLowercaseRequired());
}
if (!fpps.isUppercaseRequired()) {
fpps.setUppercaseRequired(policySpec.isUppercaseRequired());
}
if (!fpps.isMustStartWithDigit()) {
fpps.setMustStartWithDigit(policySpec.isMustStartWithDigit());
}
if (!fpps.isMustntStartWithDigit()) {
fpps.setMustntStartWithDigit(policySpec.isMustntStartWithDigit());
}
if (!fpps.isMustEndWithDigit()) {
fpps.setMustEndWithDigit(policySpec.isMustEndWithDigit());
}
if (fpps.isMustntEndWithDigit()) {
fpps.setMustntEndWithDigit(policySpec.isMustntEndWithDigit());
}
if (!fpps.isMustStartWithAlpha()) {
fpps.setMustStartWithAlpha(policySpec.isMustStartWithAlpha());
}
if (!fpps.isMustntStartWithAlpha()) {
fpps.setMustntStartWithAlpha(policySpec.isMustntStartWithAlpha());
}
if (!fpps.isMustStartWithNonAlpha()) {
fpps.setMustStartWithNonAlpha(policySpec.isMustStartWithNonAlpha());
}
if (!fpps.isMustntStartWithNonAlpha()) {
fpps.setMustntStartWithNonAlpha(policySpec.isMustntStartWithNonAlpha());
}
if (!fpps.isMustEndWithNonAlpha()) {
fpps.setMustEndWithNonAlpha(policySpec.isMustEndWithNonAlpha());
}
if (!fpps.isMustntEndWithNonAlpha()) {
fpps.setMustntEndWithNonAlpha(policySpec.isMustntEndWithNonAlpha());
}
if (!fpps.isMustEndWithAlpha()) {
fpps.setMustEndWithAlpha(policySpec.isMustEndWithAlpha());
}
if (!fpps.isMustntEndWithAlpha()) {
fpps.setMustntEndWithAlpha(policySpec.isMustntEndWithAlpha());
}
}
return fpps;
}
private void check(final PasswordPolicySpec policySpec)
throws InvalidPasswordPolicySpecException {
if (policySpec.getMinLength() == 0) {
throw new InvalidPasswordPolicySpecException("Minimum length is zero");
}
if (policySpec.isMustEndWithAlpha() && policySpec.isMustntEndWithAlpha()) {
throw new InvalidPasswordPolicySpecException(
"mustEndWithAlpha and mustntEndWithAlpha are both true");
}
if (policySpec.isMustEndWithAlpha() && policySpec.isMustEndWithDigit()) {
throw new InvalidPasswordPolicySpecException(
"mustEndWithAlpha and mustEndWithDigit are both true");
}
if (policySpec.isMustEndWithDigit() && policySpec.isMustntEndWithDigit()) {
throw new InvalidPasswordPolicySpecException(
"mustEndWithDigit and mustntEndWithDigit are both true");
}
if (policySpec.isMustEndWithNonAlpha() && policySpec.isMustntEndWithNonAlpha()) {
throw new InvalidPasswordPolicySpecException(
"mustEndWithNonAlpha and mustntEndWithNonAlpha are both true");
}
if (policySpec.isMustStartWithAlpha() && policySpec.isMustntStartWithAlpha()) {
throw new InvalidPasswordPolicySpecException(
"mustStartWithAlpha and mustntStartWithAlpha are both true");
}
if (policySpec.isMustStartWithAlpha() && policySpec.isMustStartWithDigit()) {
throw new InvalidPasswordPolicySpecException(
"mustStartWithAlpha and mustStartWithDigit are both true");
}
if (policySpec.isMustStartWithDigit() && policySpec.isMustntStartWithDigit()) {
throw new InvalidPasswordPolicySpecException(
"mustStartWithDigit and mustntStartWithDigit are both true");
}
if (policySpec.isMustStartWithNonAlpha() && policySpec.isMustntStartWithNonAlpha()) {
throw new InvalidPasswordPolicySpecException(
"mustStartWithNonAlpha and mustntStartWithNonAlpha are both true");
}
if (policySpec.getMinLength() > policySpec.getMaxLength()) {
throw new InvalidPasswordPolicySpecException("Minimun length (" + policySpec.getMinLength() + ")"
+ "is greater than maximum length (" + policySpec.getMaxLength() + ")");
}
}
private String generate(final PasswordPolicySpec policySpec) {
String[] generatedPassword = new String[policySpec.getMinLength()];
for (int i = 0; i < generatedPassword.length; i++) {
generatedPassword[i] = "";
}
checkStartChar(generatedPassword, policySpec);
checkEndChar(generatedPassword, policySpec);
checkRequired(generatedPassword, policySpec);
//filled empty chars
for (int firstEmptyChar = firstEmptyChar(generatedPassword);
firstEmptyChar < generatedPassword.length - 1; firstEmptyChar++) {
generatedPassword[firstEmptyChar] = RandomStringUtils.randomAlphabetic(1);
}
checkPrefixAndSuffix(generatedPassword, policySpec);
return StringUtils.join(generatedPassword);
}
private int randomNumber(final int range) {
int randomNumber = (int) (Math.random() * (range - 1));
return randomNumber == 0 ? 1 : randomNumber;
}
private void checkStartChar(final String[] generatedPassword, final PasswordPolicySpec policySpec) {
if (policySpec.isMustStartWithAlpha()) {
generatedPassword[0] = RandomStringUtils.randomAlphabetic(1);
}
if (policySpec.isMustStartWithNonAlpha() || policySpec.isMustStartWithDigit()) {
generatedPassword[0] = RandomStringUtils.randomNumeric(1);
}
if (policySpec.isMustntStartWithAlpha()) {
generatedPassword[0] = RandomStringUtils.randomNumeric(1);
}
if (policySpec.isMustntStartWithDigit()) {
generatedPassword[0] = RandomStringUtils.randomAlphabetic(1);
}
if (policySpec.isMustntStartWithNonAlpha()) {
generatedPassword[0] = RandomStringUtils.randomAlphabetic(1);
}
}
private void checkEndChar(final String[] generatedPassword, final PasswordPolicySpec policySpec) {
if (policySpec.isMustEndWithAlpha()) {
generatedPassword[policySpec.getMinLength() - 1] = RandomStringUtils.randomAlphabetic(1);
}
if (policySpec.isMustEndWithNonAlpha() || policySpec.isMustEndWithDigit()) {
generatedPassword[policySpec.getMinLength() - 1] = RandomStringUtils.randomNumeric(1);
}
if (policySpec.isMustntEndWithAlpha()) {
generatedPassword[policySpec.getMinLength() - 1] = RandomStringUtils.randomNumeric(1);
}
if (policySpec.isMustntEndWithDigit()) {
generatedPassword[policySpec.getMinLength() - 1] = RandomStringUtils.randomAlphabetic(1);
}
if (policySpec.isMustntEndWithNonAlpha()) {
generatedPassword[policySpec.getMinLength() - 1] = RandomStringUtils.randomAlphabetic(1);
}
}
private int firstEmptyChar(final String[] generatedPStrings) {
int index = 0;
while (!generatedPStrings[index].isEmpty()) {
index++;
}
return index;
}
private void checkRequired(final String[] generatedPassword, final PasswordPolicySpec policySpec) {
if (policySpec.isDigitRequired()
&& !PolicyPattern.DIGIT.matcher(StringUtils.join(generatedPassword)).matches()) {
generatedPassword[firstEmptyChar(generatedPassword)] = RandomStringUtils.randomNumeric(1);
}
if (policySpec.isUppercaseRequired()
&& !PolicyPattern.ALPHA_UPPERCASE.matcher(StringUtils.join(generatedPassword)).matches()) {
generatedPassword[firstEmptyChar(generatedPassword)] = RandomStringUtils.randomAlphabetic(1).toUpperCase();
}
if (policySpec.isLowercaseRequired()
&& !PolicyPattern.ALPHA_LOWERCASE.matcher(StringUtils.join(generatedPassword)).matches()) {
generatedPassword[firstEmptyChar(generatedPassword)] = RandomStringUtils.randomAlphabetic(1).toLowerCase();
}
if (policySpec.isNonAlphanumericRequired()
&& !PolicyPattern.NON_ALPHANUMERIC.matcher(StringUtils.join(generatedPassword)).matches()) {
generatedPassword[firstEmptyChar(generatedPassword)] =
SPECIAL_CHARS[randomNumber(SPECIAL_CHARS.length - 1)];
}
}
private void checkPrefixAndSuffix(final String[] generatedPassword, final PasswordPolicySpec policySpec) {
for (String prefix : policySpec.getPrefixesNotPermitted()) {
if (StringUtils.join(generatedPassword).startsWith(prefix)) {
checkStartChar(generatedPassword, policySpec);
}
}
for (String suffix : policySpec.getSuffixesNotPermitted()) {
if (StringUtils.join(generatedPassword).endsWith(suffix)) {
checkEndChar(generatedPassword, policySpec);
}
}
}
}
|
brianchen2012/syncope
|
core/src/main/java/org/apache/syncope/core/connid/PasswordGenerator.java
|
Java
|
apache-2.0
| 13,728
|
/*
* 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.managedgrafana.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.managedgrafana.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* AssertionAttributesMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AssertionAttributesMarshaller {
private static final MarshallingInfo<String> EMAIL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("email").build();
private static final MarshallingInfo<String> GROUPS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("groups").build();
private static final MarshallingInfo<String> LOGIN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("login").build();
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("name").build();
private static final MarshallingInfo<String> ORG_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("org").build();
private static final MarshallingInfo<String> ROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("role").build();
private static final AssertionAttributesMarshaller instance = new AssertionAttributesMarshaller();
public static AssertionAttributesMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(AssertionAttributes assertionAttributes, ProtocolMarshaller protocolMarshaller) {
if (assertionAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(assertionAttributes.getEmail(), EMAIL_BINDING);
protocolMarshaller.marshall(assertionAttributes.getGroups(), GROUPS_BINDING);
protocolMarshaller.marshall(assertionAttributes.getLogin(), LOGIN_BINDING);
protocolMarshaller.marshall(assertionAttributes.getName(), NAME_BINDING);
protocolMarshaller.marshall(assertionAttributes.getOrg(), ORG_BINDING);
protocolMarshaller.marshall(assertionAttributes.getRole(), ROLE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-managedgrafana/src/main/java/com/amazonaws/services/managedgrafana/model/transform/AssertionAttributesMarshaller.java
|
Java
|
apache-2.0
| 3,458
|
# Description
**mmdu** - Mysql Manager of Databases and Users.
This service will ensure, that only users and databases defined in config file will exist. Everything which is not in there will be dropped, everything which is missing - added.
Default behavior is to keep data untouched but report about differences.
Config file can be generated via puppet, chef, salt, ansible or any other config management system.
Inspired by puppet mysql module, but without known architectural problems.
Effect on freshly-installed mysql-host with **mmdu** config from this repository will look like this:
```
$ mmdu # Run to check
DROP DATABASE test
CREATE DATABASE oleg_test
CREATE DATABASE qwerty
DROP USER 'root'@'127.0.0.1'
DROP USER 'root'@'::1'
DROP USER ''@'aw-db01.oleg'
DROP USER 'root'@'aw-db01.oleg'
DROP USER ''@'localhost'
DROP USER 'debian-sys-maint'@'localhost'
DROP USER 'root'@'localhost'
GRANT SELECT, UPDATE ON `oleg%`.* TO 'oleg'@'10.%' IDENTIFIED BY PASSWORD '*F41E614E894A46E0FB7317B1C8CB6CEA97415C7B'
GRANT SELECT ON qwerty.* TO 'oleg'@'10.%' IDENTIFIED BY PASSWORD '*F41E614E894A46E0FB7317B1C8CB6CEA97415C7B'
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' WITH GRANT OPTION
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' WITH GRANT OPTION
$ mmdu -e # Run to execute
$ mmdu # Run to check
$
```
All actions happen in single transaction. If something went wrong - changes will not be applied.
This is also make possible to change root-user password and not being disconnected.
Second run will give us:
```
$ mmdu # Same will be with mmdu -e in this case
Nothing to do
```
# Options
- **-e** - execute/apply all changes
- **-c** - custom location of config file (default is */etc/mmdu/mmdu.toml*)
# Configuration
You need to update settings and add your own data into configuration file */etc/mmdu/mmdu.toml*:
- **[general]** -general configuration section
- autoExecute - behaves like `-e` parameter. If true - executes statements. Good for staging servers to automatically execute things. Default `false`
- **[access]** - this section contains data to connect to mysql server
You can specify *username*, *password*, *initPass*, *host*, *port*. If you do not - it has default values (root without password to localhost 3306)
- username - users which has permissions to grant (WITH GRANT OPTION) privileges, drop and create databases and users
- password - password for this user
- initPass - if your mysql was managed before by something else and has password, you can provide initial data to login and make changes. Default is no password authentication
- host - host where mmdu should connect. Default is "localhost"
- port - port where mmdu should connect. Default is 3306
- socket - preferred. If you have this parameter set up, mmdu will try to connect via socket. This is prefered, because in 5.7 this is the only way to connect with root to freshly installed DB
- **[[database]]** - Databases which need to be in mysql.
- name - name of database to manage
- **[[user]]** - Users which need to be in mysql.
You can specify *username*, *network*, *password*, *hashedPassword*, *database*, *table*, *privileges*, *grantOption*
- username - username
- network - address, from which mysql allows to connect this user. e.g. *8.8.%*
- password - plain-text password. I would not recommend to have it. Better use *hashedPassword*. If specifyed - *hashedPassword* will be ignored
- hashedPassword - hashed password (sha1 encrypted). You can get it via ```mysql> select password('oleg')``` e.g. **\*F41E614E894A46E0FB7317B1C8CB6CEA97415C7B**
- grantOption - true or false flag for users "WITH GRANT OPTION". Default *false*
- **[[user.permissions]]**
- database - database to which user has an access. **mmdu** will ensure this database exist **[[database]]**. e.g. *oleg%* or **\***
- table - table to which user has an access. e.g. "*"
- privileges - list of privileges for user. e.g. ["SELECT", "INSERT"]
# Installation
- Install go https://golang.org/doc/install
- Make a proper structure of directories: ```mkdir -p /opt/go/src /opt/go/bin /opt/go/pkg```
- Setup g GOPATH variable: ```export GOPATH=/opt/go```
- Clone this project to src: ```go get github.com/leoleovich/mmdu```
- Fetch dependencies: ```cd /opt/go/github.com/leoleovich/mmdu && go get ./...```
- Compile project: ```go install github.com/leoleovich/mmdu```
- Copy config file: ```mkdir /etc/mmdu && cp /opt/go/src/github.com/leoleovich/mmdu/mmdu.toml /etc/mmdu/```
- Adjust your settings
- Run it ```/opt/go/bin/mmdu```
|
leoleovich/mmdu
|
README.md
|
Markdown
|
apache-2.0
| 4,786
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
'use strict';
// MODULES //
var pow = require( '@stdlib/math/base/special/pow' );
// MAIN //
/**
* Computes an exponential delay.
*
* @private
* @param {NonNegativeInteger} retries - number of retries
* @param {number} max - maximum delay
* @returns {NonNegativeInteger} exponential delay
*/
function delay( retries, max ) {
var d = pow( 2, retries ) - 1;
if ( d > max ) {
d = max;
}
return d;
}
// EXPORTS //
module.exports = delay;
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/fs/read-file-list/lib/delay.js
|
JavaScript
|
apache-2.0
| 1,066
|
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="login.css" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
{% extends "security/base.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block content %}
{% include "security/_messages.html" %}
<form action="{{ url_for_security('forgot_password') }}" method="POST" name="forgot_password_form">
<div class="d-flex d-flex-column justify-content-center align-items-center">
<h1>{{ _('Reset CAIRIS password') }}</h1>
</div>
<div class="d-flex d-flex-column justify-content-center align-items-center">
{{ forgot_password_form.hidden_tag() }}
{{ render_field_with_errors(forgot_password_form.email) }}
{{ render_field(forgot_password_form.submit) }}
</div>
</form>
{% endblock %}
|
failys/CAIRIS
|
cairis/daemon/templates/security/forgot_password.html
|
HTML
|
apache-2.0
| 1,225
|
package gudusoft.gsqlparser.sql2xml.model;
public class window_frame_following
{
}
|
sqlparser/sql2xml
|
sql2xml/src/gudusoft/gsqlparser/sql2xml/model/window_frame_following.java
|
Java
|
apache-2.0
| 86
|
# Resource Creation Tests
These tests are specifically for testing functionality revolving around
the binding of vulkan resources.
# Tests
- [vkUpdateDescriptorSets_test](vkUpdateDescriptorSets_test/README.md)
|
google/vulkan_test_applications
|
gapid_tests/resource_binding_tests/README.md
|
Markdown
|
apache-2.0
| 213
|
package rs.ftn.pma.tourismobile.database.dao.wrapper;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.SelectArg;
import org.androidannotations.annotations.EBean;
import org.androidannotations.ormlite.annotations.OrmLiteDao;
import java.sql.SQLException;
import java.util.List;
import java.util.Observable;
import rs.ftn.pma.tourismobile.database.DatabaseHelper;
import rs.ftn.pma.tourismobile.database.dao.DestinationDAO;
import rs.ftn.pma.tourismobile.model.Destination;
/**
* Created by Daniel Kupčo on 04.06.2016.
*/
@EBean(scope = EBean.Scope.Singleton)
public class DestinationDAOWrapper extends Observable {
@OrmLiteDao(helper = DatabaseHelper.class)
DestinationDAO destinationDAO;
public List<Destination> findAll() {
return destinationDAO.queryForAll();
}
public Destination findById(int id) {
return destinationDAO.queryForId(id);
}
public boolean create(Destination destination) {
Destination existing = findByWikiPageID(destination.getWikiPageID());
if(existing == null) {
return destinationDAO.create(destination) == 1;
}
else {
if(!existing.isFavourite())
existing.setFavourite(destination.isFavourite());
update(existing);
return true;
}
}
public void update(Destination destination) {
destinationDAO.update(destination);
}
public void delete(Destination destination) {
destinationDAO.delete(destination);
}
public Destination findByWikiPageID(int wikiPageID) {
try {
return destinationDAO.queryBuilder().where().eq(Destination.WIKI_PAGE_ID_FIELD, wikiPageID).queryForFirst();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public List<Destination> findAllFavourites() {
try {
return destinationDAO.queryBuilder().where().eq(Destination.FAVOURITE_FIELD, true).query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public List<Destination> findAllForPage(int page, int limit) {
try {
return destinationDAO.queryBuilder().offset(Long.valueOf(page * limit)).limit(Long.valueOf(limit)).query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public List<Destination> findAllFavouritesForPage(int page, int limit) {
try {
return destinationDAO.queryBuilder().offset(Long.valueOf(page * limit)).limit(Long.valueOf(limit))
.where().eq(Destination.FAVOURITE_FIELD, true).query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public int delete(int destinationId) {
try {
DeleteBuilder<Destination, Integer> deleteBuilder = destinationDAO.deleteBuilder();
deleteBuilder.where().eq(Destination.ID_FIELD, destinationId);
setChanged();
notifyObservers();
return deleteBuilder.delete();
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
private PreparedDelete<Destination> preparedDeleteStatement;
public int delete(int[] destinationIds) {
try {
if (preparedDeleteStatement == null) {
final DeleteBuilder<Destination, Integer> deleteBuilder = destinationDAO.deleteBuilder();
final SelectArg destinationId = new SelectArg();
deleteBuilder.where().eq(Destination.ID_FIELD, destinationId);
preparedDeleteStatement = deleteBuilder.prepare();
}
for (int i = 0; i < destinationIds.length; i++) {
preparedDeleteStatement.setArgumentHolderValue(0, destinationIds[i]);
destinationDAO.delete(preparedDeleteStatement);
}
setChanged();
notifyObservers();
return destinationIds.length;
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
}
|
danielkupco/Tourismobile
|
app/src/main/java/rs/ftn/pma/tourismobile/database/dao/wrapper/DestinationDAOWrapper.java
|
Java
|
apache-2.0
| 4,229
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _createShareButton = require('./utils/createShareButton');
var _createShareButton2 = _interopRequireDefault(_createShareButton);
var _objectToGetParams = require('./utils/objectToGetParams');
var _objectToGetParams2 = _interopRequireDefault(_objectToGetParams);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function instapaperLink(url, _ref) {
var title = _ref.title,
description = _ref.description;
(0, _assert2.default)(url, 'instapaper.url');
return 'http://www.instapaper.com/hello2' + (0, _objectToGetParams2.default)({
url: url,
title: title,
description: description
});
}
var InstapaperShareButton = (0, _createShareButton2.default)('instapaper', instapaperLink, function (props) {
return {
title: props.title,
description: props.description
};
}, {
title: _propTypes2.default.string,
description: _propTypes2.default.string
}, {
windowWidth: 500,
windowHeight: 500
});
exports.default = InstapaperShareButton;
|
BigBoss424/portfolio
|
v7/development/node_modules/react-share/lib/InstapaperShareButton.js
|
JavaScript
|
apache-2.0
| 1,288
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use collections::HashMap;
use concurrency_manager::ConcurrencyManager;
use engine_traits::KvEngine;
use futures::compat::Future01CompatExt;
use grpcio::{ChannelBuilder, Environment};
use kvproto::kvrpcpb::{CheckLeaderRequest, LeaderInfo};
use kvproto::metapb::{Peer, PeerRole};
use kvproto::tikvpb::TikvClient;
use pd_client::PdClient;
use protobuf::Message;
use raftstore::store::fsm::StoreMeta;
use raftstore::store::util::RegionReadProgressRegistry;
use security::SecurityManager;
use tikv_util::timer::SteadyTimer;
use tikv_util::worker::Scheduler;
use tokio::runtime::{Builder, Runtime};
use txn_types::TimeStamp;
use crate::endpoint::Task;
use crate::errors::Result;
use crate::metrics::{CHECK_LEADER_REQ_ITEM_COUNT_HISTOGRAM, CHECK_LEADER_REQ_SIZE_HISTOGRAM};
const DEFAULT_CHECK_LEADER_TIMEOUT_MILLISECONDS: u64 = 5_000; // 5s
pub struct AdvanceTsWorker<E: KvEngine> {
store_meta: Arc<Mutex<StoreMeta>>,
region_read_progress: RegionReadProgressRegistry,
pd_client: Arc<dyn PdClient>,
timer: SteadyTimer,
worker: Runtime,
scheduler: Scheduler<Task<E::Snapshot>>,
/// The concurrency manager for transactions. It's needed for CDC to check locks when
/// calculating resolved_ts.
concurrency_manager: ConcurrencyManager,
// store_id -> client
tikv_clients: Arc<Mutex<HashMap<u64, TikvClient>>>,
env: Arc<Environment>,
security_mgr: Arc<SecurityManager>,
}
impl<E: KvEngine> AdvanceTsWorker<E> {
pub fn new(
pd_client: Arc<dyn PdClient>,
scheduler: Scheduler<Task<E::Snapshot>>,
store_meta: Arc<Mutex<StoreMeta>>,
region_read_progress: RegionReadProgressRegistry,
concurrency_manager: ConcurrencyManager,
env: Arc<Environment>,
security_mgr: Arc<SecurityManager>,
) -> Self {
let worker = Builder::new_multi_thread()
.thread_name("advance-ts")
.worker_threads(1)
.enable_time()
.build()
.unwrap();
Self {
env,
security_mgr,
scheduler,
pd_client,
worker,
timer: SteadyTimer::default(),
store_meta,
region_read_progress,
concurrency_manager,
tikv_clients: Arc::new(Mutex::new(HashMap::default())),
}
}
}
impl<E: KvEngine> AdvanceTsWorker<E> {
pub fn advance_ts_for_regions(&self, regions: Vec<u64>) {
let pd_client = self.pd_client.clone();
let scheduler = self.scheduler.clone();
let cm: ConcurrencyManager = self.concurrency_manager.clone();
let env = self.env.clone();
let security_mgr = self.security_mgr.clone();
let store_meta = self.store_meta.clone();
let tikv_clients = self.tikv_clients.clone();
let region_read_progress = self.region_read_progress.clone();
let fut = async move {
// Ignore get tso errors since we will retry every `advance_ts_interval`.
let mut min_ts = pd_client.get_tso().await.unwrap_or_default();
// Sync with concurrency manager so that it can work correctly when optimizations
// like async commit is enabled.
// Note: This step must be done before scheduling `Task::MinTS` task, and the
// resolver must be checked in or after `Task::MinTS`' execution.
cm.update_max_ts(min_ts);
if let Some(min_mem_lock_ts) = cm.global_min_lock_ts() {
if min_mem_lock_ts < min_ts {
min_ts = min_mem_lock_ts;
}
}
let regions = Self::region_resolved_ts_store(
regions,
store_meta,
region_read_progress,
pd_client,
security_mgr,
env,
tikv_clients,
min_ts,
)
.await;
if !regions.is_empty() {
if let Err(e) = scheduler.schedule(Task::AdvanceResolvedTs {
regions,
ts: min_ts,
}) {
info!("failed to schedule advance event"; "err" => ?e);
}
}
};
self.worker.spawn(fut);
}
pub fn register_next_event(&self, advance_ts_interval: Duration, cfg_version: usize) {
let scheduler = self.scheduler.clone();
let timeout = self.timer.delay(advance_ts_interval);
let fut = async move {
let _ = timeout.compat().await;
if let Err(e) = scheduler.schedule(Task::RegisterAdvanceEvent { cfg_version }) {
info!("failed to schedule register advance event"; "err" => ?e);
}
};
self.worker.spawn(fut);
}
// Confirms leadership of region peer before trying to advance resolved ts.
// This function broadcasts a special message to all stores, get the leader id of them to confirm whether
// current peer has a quorum which accept its leadership.
async fn region_resolved_ts_store(
regions: Vec<u64>,
store_meta: Arc<Mutex<StoreMeta>>,
region_read_progress: RegionReadProgressRegistry,
pd_client: Arc<dyn PdClient>,
security_mgr: Arc<SecurityManager>,
env: Arc<Environment>,
cdc_clients: Arc<Mutex<HashMap<u64, TikvClient>>>,
min_ts: TimeStamp,
) -> Vec<u64> {
#[cfg(feature = "failpoint")]
(|| fail_point!("before_sync_replica_read_state", |_| regions))();
let store_id = match store_meta.lock().unwrap().store_id {
Some(id) => id,
None => return vec![],
};
// store_id -> leaders info, record the request to each stores
let mut store_map: HashMap<u64, Vec<LeaderInfo>> = HashMap::default();
// region_id -> region, cache the information of regions
let mut region_map: HashMap<u64, Vec<Peer>> = HashMap::default();
// region_id -> peers id, record the responses
let mut resp_map: HashMap<u64, Vec<u64>> = HashMap::default();
// region_id -> `(Vec<Peer>, LeaderInfo)`
let info_map = region_read_progress.dump_leader_infos(®ions);
for (region_id, (peer_list, leader_info)) in info_map {
let leader_id = leader_info.get_peer_id();
// Check if the leader in this store
if find_store_id(&peer_list, leader_id) != Some(store_id) {
continue;
}
for peer in &peer_list {
if peer.store_id == store_id && peer.id == leader_id {
resp_map.entry(region_id).or_default().push(store_id);
continue;
}
store_map
.entry(peer.store_id)
.or_default()
.push(leader_info.clone());
}
region_map.insert(region_id, peer_list);
}
// Approximate `LeaderInfo` size
let leader_info_size = store_map
.values()
.next()
.map_or(0, |regions| regions[0].compute_size());
let stores = store_map.into_iter().map(|(store_id, regions)| {
let cdc_clients = cdc_clients.clone();
let env = env.clone();
let pd_client = pd_client.clone();
let security_mgr = security_mgr.clone();
let region_num = regions.len() as u32;
CHECK_LEADER_REQ_SIZE_HISTOGRAM.observe((leader_info_size * region_num) as f64);
CHECK_LEADER_REQ_ITEM_COUNT_HISTOGRAM.observe(region_num as f64);
async move {
if cdc_clients.lock().unwrap().get(&store_id).is_none() {
let store = box_try!(pd_client.get_store_async(store_id).await);
let cb = ChannelBuilder::new(env.clone());
let channel = security_mgr.connect(cb, &store.address);
cdc_clients
.lock()
.unwrap()
.insert(store_id, TikvClient::new(channel));
}
let client = cdc_clients.lock().unwrap().get(&store_id).unwrap().clone();
let mut req = CheckLeaderRequest::default();
req.set_regions(regions.into());
req.set_ts(min_ts.into_inner());
let res = box_try!(
tokio::time::timeout(
Duration::from_millis(DEFAULT_CHECK_LEADER_TIMEOUT_MILLISECONDS),
box_try!(client.check_leader_async(&req))
)
.await
);
let resp = box_try!(res);
Result::Ok((store_id, resp))
}
});
let resps = futures::future::join_all(stores).await;
resps
.into_iter()
.filter_map(|resp| match resp {
Ok(resp) => Some(resp),
Err(e) => {
debug!("resolved-ts check leader error"; "err" =>?e);
None
}
})
.map(|(store_id, resp)| {
resp.regions
.into_iter()
.map(move |region_id| (store_id, region_id))
})
.flatten()
.for_each(|(store_id, region_id)| {
resp_map.entry(region_id).or_default().push(store_id);
});
resp_map
.into_iter()
.filter_map(|(region_id, stores)| {
if region_has_quorum(®ion_map[®ion_id], &stores) {
Some(region_id)
} else {
debug!(
"resolved-ts cannot get quorum for resolved ts";
"region_id" => region_id,
"stores" => ?stores,
"region" => ?®ion_map[®ion_id]
);
None
}
})
.collect()
}
}
fn region_has_quorum(peers: &[Peer], stores: &[u64]) -> bool {
let mut voters = 0;
let mut incoming_voters = 0;
let mut demoting_voters = 0;
let mut resp_voters = 0;
let mut resp_incoming_voters = 0;
let mut resp_demoting_voters = 0;
peers.iter().for_each(|peer| {
let mut in_resp = false;
for store_id in stores {
if *store_id == peer.store_id {
in_resp = true;
break;
}
}
match peer.get_role() {
PeerRole::Voter => {
voters += 1;
if in_resp {
resp_voters += 1;
}
}
PeerRole::IncomingVoter => {
incoming_voters += 1;
if in_resp {
resp_incoming_voters += 1;
}
}
PeerRole::DemotingVoter => {
demoting_voters += 1;
if in_resp {
resp_demoting_voters += 1;
}
}
PeerRole::Learner => (),
}
});
let has_incoming_majority =
(resp_voters + resp_incoming_voters) >= ((voters + incoming_voters) / 2 + 1);
let has_demoting_majority =
(resp_voters + resp_demoting_voters) >= ((voters + demoting_voters) / 2 + 1);
has_incoming_majority && has_demoting_majority
}
fn find_store_id(peer_list: &[Peer], peer_id: u64) -> Option<u64> {
for peer in peer_list {
if peer.id == peer_id {
return Some(peer.store_id);
}
}
None
}
|
BusyJay/tikv
|
components/resolved_ts/src/advance.rs
|
Rust
|
apache-2.0
| 11,783
|
package com.project.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MongoDevConfig {
private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class);
@Bean
ABC mongoDbFactory() throws Exception {
logger.debug("Init...... MongoDbFactory() in production mode!");
logger.debug("RAMMM----------------------------------------------------------------------------------------");
//...
return new ABC(2, "db");
}
}
|
RamuIMC/AWSMavenGitProject
|
src/main/java/com/project/Dao/MongoDevConfig.java
|
Java
|
apache-2.0
| 620
|
/*
* Copyright (C) 2013 salesforce.com, 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 org.auraframework.integration.test.root.parser.handler.design;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.design.DesignDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.test.source.StringSourceLoader;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.auraframework.util.test.annotation.UnAdaptableTest;
@UnAdaptableTest("namespace start with c means something special in core")
public class DesignLayoutDefHandlerTest extends AuraImplTestCase {
private final static String LAYOUT = "<design:layout> </design:layout>";
private final static String LAYOUT_NAME = "<design:layout name=\"%s\"> </design:layout>";
public DesignLayoutDefHandlerTest(String name) {
super(name);
}
public void testNoLayout() throws Exception {
DesignDef def = setupDesignLayoutDef("", true);
assertNull(def.getDefaultDesignLayoutDef());
}
public void testLayoutDef() throws Exception {
DesignDef def = setupDesignLayoutDef(LAYOUT, true);
assertNotNull(def.getDefaultDesignLayoutDef());
}
public void testLayoutWithName() throws Exception {
final String name = "name";
DesignDef def = setupDesignLayoutDef(String.format(LAYOUT_NAME, name), true);
assertNotNull(def.getDesignLayoutDefs().get(name));
}
public void testMultipleDefWithSameName() throws Exception {
final String name = "name";
String layouts = String.format(LAYOUT_NAME, name) + String.format(LAYOUT_NAME, name);
try {
setupDesignLayoutDef(layouts, true);
fail("duplicate names should not be allowed.");
} catch (Exception e) {
assertExceptionMessageStartsWith(e, InvalidDefinitionException.class, String.format("Layout with name %s already defined", name));
}
}
public void testLayoutInNonInternalNS() throws Exception {
try {
setupDesignLayoutDef(LAYOUT, false);
fail("Non-Internal NS should not be allowed to add a layout component");
} catch (Exception e) {
assertExceptionType(e, InvalidDefinitionException.class);
assertTrue("Exception message was unexpected", e.getMessage().contains("<design:component> can not contain tag"));
}
}
private DesignDef setupDesignLayoutDef(String markup, boolean addToInternal) throws Exception {
DefDescriptor<ComponentDef> cmpDesc = getAuraTestingUtil().createStringSourceDescriptor(StringSourceLoader.DEFAULT_CUSTOM_NAMESPACE + ":",
ComponentDef.class, null);
getAuraTestingUtil().addSourceAutoCleanup(cmpDesc, String.format(baseComponentTag, "", ""), addToInternal);
DefDescriptor<DesignDef> designDesc = definitionService.getDefDescriptor(cmpDesc.getQualifiedName(),
DesignDef.class);
getAuraTestingUtil().addSourceAutoCleanup(designDesc,
String.format("<design:component>%s</design:component>", markup), addToInternal);
return designDesc.getDef();
}
}
|
badlogicmanpreet/aura
|
aura-integration-test/src/test/java/org/auraframework/integration/test/root/parser/handler/design/DesignLayoutDefHandlerTest.java
|
Java
|
apache-2.0
| 3,763
|
<!DOCTYPE html>
<html>
<head>
<!-- ------------------------------------------------------------------
***********************************************************************
开发人员书写规范:
1.所有缩进都用 TAB, 而不是空格。
2.非必要,禁止用行内样式例如 <div style="display:block">
浏览器兼容:
IE10+
FireFox
Webkit内核浏览器:
Chrome,
Opear(WebKit版),
360浏览器(7.0+),
360急速浏览器,
搜狗浏览器,
115浏览器,
UC桌面浏览器,
枫树浏览器,
Safari 5.1+
Safari 7+ (Mac OS)
注:由于国内IE6-7份额已经非常低,基本是测试人员跟一些非常旧的政府机构,所以不做兼容。
***********************************************************************
---------------------------------------------------------------------- -->
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8">
<title>EverySync</title>
<meta name="description" content="">
<meta name="author" content="JayChen">
<!-- 让IE浏览器用最高级内核渲染页面 还有用 Chrome 框架的页面用webkit 内核
================================================== -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="../js/modernizr.custom.js"></script>
<script>
!Modernizr.csstransitions?window.location.href="../np.html":'';
if (!Modernizr.svg) {alert("\u5bf9\u4e0d\u8d77\uff0c\u60a8\u7684\u6d4f\u89c8\u5668\u4e0d\u652f\u6301\u0053\u0056\u0047\u683c\u5f0f\u56fe\u50cf\uff0c\u8bf7\u5347\u7ea7\u7248\u672c\uff0c\u5982\u679c\u8fd8\u662f\u51fa\u73b0\u8fd9\u4e2a\u63d0\u793a\uff0c\u90a3\u4e48\u8bf7\u6362\u4e2a\u6d4f\u89c8\u5668\uff0c\u5bf9\u60a8\u9020\u6210\u4e0d\u4fbf\u8bf7\u8c05\u89e3\u3002")}
</script>
<!-- IOS6全屏 Chrome高版本全屏
================================================== -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<!-- 让360双核浏览器用webkit内核渲染页面
================================================== -->
<meta name="renderer" content="webkit">
<!-- Mobile Specific Metas
================================================== -->
<!-- !!!注意 minimal-ui 是IOS7.1的新属性,最小化浏览器UI,但是在iOS8.1突然被取消 -->
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
<!-- CSS
================================================== -->
<link href="../css/reset.css" rel="stylesheet" type="text/css">
<link href="../css/onepage-scroll.css" rel="stylesheet" type="text/css">
<link href="../css/style.css" rel="stylesheet" type="text/css">
<link href="../css/Bina.css" rel="stylesheet" type="text/css">
<link href="../css/EC.css" rel="stylesheet" type="text/css">
<!-- Favicons
================================================== -->
<link rel="shortcut icon" href="favicon.ico" >
<!-- Android 主屏图标
================================================== -->
<link rel="icon" sizes="196x196" href="touch-icon.png">
<!-- IOS 主屏图标
================================================== -->
<link rel="apple-touch-icon" href="touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
<script src="../js/prefixfree.min.js"></script>
<style>
html,body {
height: 100%;
}
</style>
</head>
<body class="pagebgc-2">
<div class="app_header">
<div class="sideBtn">
<div class="side_show_btn ficon-icon-6"></div>
<div class="side_hide_btn ficon-icon-7"></div>
</div>
<div class="ctrBtns">
<div class="ctr_1 ficon-icon-1"></div>
<div class="ctr_2 ficon-icon-2"></div>
<div class="ctr_3 ficon-icon-3"></div>
<div class="ctr_4 ficon-icon-4"></div>
<div class="ctr_5 ficon-icon-5"></div>
</div>
</div>
<!-- EC-PAGE fpy_oobBg -->
<div class="eachBlck">
<div class="EcScroll">
<div class="DateSearchTable">
<div class="dateRow">
<div class="dateCell-th">Date</div>
<div class="dateCell-td">2013-10-14——2014-10-14</div>
<div class="dateCell-th">ODM</div>
<div class="dateCell-td">All</div>
</div>
<div class="dateRow">
<div class="dateCell-th">Phrase</div>
<div class="dateCell-td">Mass Product</div>
<div class="dateCell-th">Product</div>
<div class="dateCell-td">All</div>
</div>
</div>
<div id="chart_qstop_result" class="fai_charts chartHalfH"><img src="../images/temp/charts05.png" ></div>
<div class="ecPageTab">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
<tr>
<th width="8%">Product</th>
<th>Phase</th>
<th>FPY Input</th>
<th>FPY Defect</th>
<th>FPY Category</th>
<th>OOB Input</th>
<th>OOB Defect</th>
<th>OOB Category</th>
<th>Operating</th>
</tr>
</thead>
<tbody>
<tr>
<td>G40-30</td>
<td>SVT</td>
<td>80</td>
<td>7</td>
<td> </td>
<td>80</td>
<td>0</td>
<td> </td>
<td><span class="showBox ficon-icon-eye"></span></td>
</tr>
<tr>
<td>G40-30</td>
<td>SVT</td>
<td>80</td>
<td>7</td>
<td> </td>
<td>80</td>
<td>0</td>
<td> </td>
<td><span class="showBox ficon-icon-eye"></span></td>
</tr>
<tr>
<td>G40-30</td>
<td>SVT</td>
<td>80</td>
<td>7</td>
<td> </td>
<td>80</td>
<td>0</td>
<td> </td>
<td><span class="showBox ficon-icon-eye"></span></td>
</tr>
<tr>
<td>G40-30</td>
<td>SVT</td>
<td>80</td>
<td>7</td>
<td> </td>
<td>80</td>
<td>0</td>
<td> </td>
<td><span class="showBox ficon-icon-eye"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="sidebar_wrap">
<div class="sidebar" id="sidebar">
<div class="sideItems">
<div class="silinks">
<span>HOME</span></div>
</div>
<div class="sideItems">
<div class="silinks">
<span>Q-STOP</span>
<div class="silinksSec"><span class="skInner">Create</span></div>
<div class="silinksSec"><span class="skInner">Managment</span></div>
<div class="silinksSec"><span class="skInner">ODM Status</span></div>
<div class="silinksSec"><span class="skInner">Search</span></div>
</div>
</div>
<div class="sideItems">
<div class="silinks">
<span>FPY/OOB</span>
<div class="silinksSec"><span class="skInner">Create</span></div>
<div class="silinksSec"><span class="skInner">Create2</span></div>
<div class="silinksSec"><span class="skInner">Create3</span></div>
</div>
</div>
<div class="sideItems">
<div class="silinks">
<span>AUDIT</span>
<div class="silinksSec"><span class="skInner">Create</span></div>
</div>
</div>
<div class="sideItems">
<div class="silinks">
<span>FAI</span>
<div class="silinksSec"><span class="skInner">Create</span></div>
</div>
</div>
<div class="sideItems">
<div class="silinks">
<span>EC</span>
<div class="silinksSec"><span class="skInner">Create</span></div>
</div>
</div>
</div>
</div>
<!-- Javascript with AMD
================================================== -->
<script src="../js/require.js" data-main="../js/main" ></script>
</body>
</html>
|
everysync/everysync.github.io
|
moduleHtml/FPY_OOBSearchResult-2.html
|
HTML
|
apache-2.0
| 7,809
|
package i5.las2peer.services.ocd.cooperation.simulation.dynamic;
/**
* Constructs {@link Dynamic} objects
*/
public class DynamicFactory {
public static DynamicFactory getInstance() {
return new DynamicFactory();
}
/**
* Creates a {@link Dynamic} matching the specified ConditionType and
* parameter values.
*
* @param dynamicType
* the dynamic type
* @param values
* parameters values
* @return Dynamic
*/
public Dynamic build(DynamicType dynamicType, double[] values) {
switch (dynamicType) {
case UNKNOWN:
throw new IllegalArgumentException("unknown dynamic");
case REPLICATOR:
if (values == null || values.length != 1)
throw new IllegalArgumentException("no dynamic parameters specified");
return (new Replicator(values[0]));
default:
try {
return dynamicType.getDynamicClass().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Creates a {@link Dynamic} matching the specified ConditionType with
* default parameters.
*
* @param dynamicType
* the dynamic type
* @return the matching
*/
public Dynamic build(DynamicType dynamicType) {
return build(dynamicType, new double[] { 1.5 });
}
/**
* Creates a {@link Dynamic} matching the specified ConditionType and
* the parameter value.
*
* @param dynamicType
* the dynamic type
* @param value
* parameter value
* @return dynamic
*/
public Dynamic build(DynamicType dynamicType, double value) {
return build(dynamicType, new double[] { value });
}
/**
* Creates a {@link Dynamic} matching the specified dynamic string and
* parameter values.
*
* @param dynamicString
* specifying dynamicType
* @param values
* dynamic parameter values
* @return Dynamic
*/
public Dynamic build(String dynamicString, double[] values) {
DynamicType dynamicType = DynamicType.fromString(dynamicString);
if (dynamicType == DynamicType.UNKNOWN)
throw new IllegalArgumentException("unknown dynamic");
return build(dynamicType, values);
}
}
|
rwth-acis/REST-OCD-Services
|
rest_ocd_services/src/main/java/i5/las2peer/services/ocd/cooperation/simulation/dynamic/DynamicFactory.java
|
Java
|
apache-2.0
| 2,161
|
# Candelariella glaucolivescens (Nyl.) Zahlbr. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Lecanora glaucolivescens Nyl.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Candelariales/Candelariaceae/Candelariella/Candelariella glaucolivescens/README.md
|
Markdown
|
apache-2.0
| 202
|
/**
* Implements a TranscriptionService for a Sphinx4 http server
*/
export default class SphinxService extends AbstractTranscriptionService {
url: string;
}
import AbstractTranscriptionService from "./AbstractTranscriptionService";
|
jitsi/lib-jitsi-meet
|
types/auto/modules/transcription/transcriptionServices/SphinxTranscriptionService.d.ts
|
TypeScript
|
apache-2.0
| 239
|
package com.adnroid.pigknight.example.ui;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import com.adnroid.pigknight.example.R;
import com.android.pigknight.UI;
public class CategoryNetwork extends UI {
private final static String TAG = CategoryNetwork.class.getSimpleName();
protected static CategoryNetwork mInstance = null;
protected CategoryNetwork(Context context, boolean isRoot) {
super(context, isRoot);
// TODO Auto-generated constructor stub
}
public static void initInstance(Context paramContext,boolean isRoot){
mInstance = new CategoryNetwork(paramContext, isRoot);
}
public static CategoryNetwork getInstance(){
if (mInstance == null)
throw new RuntimeException(TAG+": Must called the initInstance() before to call getInstance().");
return mInstance;
}
@Override
public ViewGroup onCreateContainer() {
// TODO Auto-generated method stub
return (ViewGroup)View.inflate(mContext, R.layout.category_network, null);
}
@Override
public ViewGroup onCreateChildUIContainer() {
// TODO Auto-generated method stub
return null;
}
@Override
public void onInitialize() {
// TODO Auto-generated method stub
mContainer.findViewById(R.id.btn_view_network_album).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Content.getInstance().switchChildUI(Content.CHILD_ID_ALBUM_LIST, false);
}
});
}
@Override
public void onFinalize() {
// TODO Auto-generated method stub
}
@Override
public void onShow() {
// TODO Auto-generated method stub
}
@Override
public void onHide() {
// TODO Auto-generated method stub
}
@Override
public boolean onKeyEvent(KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
|
pigknight/AndroidApp-UI-Arch
|
Example/src/com/adnroid/pigknight/example/ui/CategoryNetwork.java
|
Java
|
apache-2.0
| 1,969
|
package test.category;
/**
* Stable test that must pass.
*/
public interface Stable {
}
|
tdomzal/junit-docker-rule
|
src/test/java/test/category/Stable.java
|
Java
|
apache-2.0
| 92
|
/*
* Copyright 2013 The GDG Frisbee Project
*
* 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.gdg.frisbee.android.api;
import android.util.Log;
import com.android.volley.*;
import timber.log.Timber;
import java.util.HashMap;
import java.util.Map;
/**
* GDG Aachen
* org.gdg.frisbee.android.api
* <p/>
* User: maui
* Date: 26.05.13
* Time: 19:39
*/
public abstract class GdgRequest<T> extends Request<T> {
private static final String LOG_TAG = "GDG-GdgRequest";
private static final String BASE_URL = "https://developers.google.com";
private static final String DIRECTORY_URL = BASE_URL + "/groups/directory/";
private static final String USER_AGENT = "GDG-Frisbee/0.1 (Android)";
public static String mCsrfToken = null;
protected Response.Listener<T> mListener;
public GdgRequest(int method, String url, Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
}
public void setResponseListener(Response.Listener<T> listener) {
mListener = listener;
}
public Response.Listener<T> getResponseListener() {
return mListener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
super.getHeaders();
Timber.d("getHeaders()");
HashMap<String, String> additionalHeaders = new HashMap<String, String>();
additionalHeaders.put("User-Agent", USER_AGENT);
additionalHeaders.put("Referer", "https://developers.google.com/groups/directory/");
additionalHeaders.put("X-Requested-With", "XMLHttpRequest");
additionalHeaders.put("Cache-Control", "no-cache");
additionalHeaders.put("DNT", "1");
return additionalHeaders;
}
@Override
public byte[] getBody() throws AuthFailureError {
return "".getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
}
|
gdgjodhpur/gdgapp
|
app/src/main/java/org/gdg/frisbee/android/api/GdgRequest.java
|
Java
|
apache-2.0
| 2,517
|
/*
* Copyright 2016 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
*
* 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.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import com.google.cloud.bigquery.JobInfo.CreateDisposition;
import com.google.cloud.bigquery.JobInfo.SchemaUpdateOption;
import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.cloud.bigquery.TimePartitioning.Type;
import com.google.common.collect.ImmutableList;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.Test;
public class LoadJobConfigurationTest {
private static final String TEST_PROJECT_ID = "test-project-id";
private static final CsvOptions CSV_OPTIONS =
CsvOptions.newBuilder()
.setAllowJaggedRows(true)
.setAllowQuotedNewLines(false)
.setEncoding(StandardCharsets.UTF_8)
.build();
private static final TableId TABLE_ID = TableId.of("dataset", "table");
private static final CreateDisposition CREATE_DISPOSITION = CreateDisposition.CREATE_IF_NEEDED;
private static final WriteDisposition WRITE_DISPOSITION = WriteDisposition.WRITE_APPEND;
private static final Integer MAX_BAD_RECORDS = 42;
private static final String FORMAT = "CSV";
private static final Boolean IGNORE_UNKNOWN_VALUES = true;
private static final Field FIELD_SCHEMA =
Field.newBuilder("IntegerField", LegacySQLTypeName.INTEGER)
.setMode(Field.Mode.REQUIRED)
.setDescription("FieldDescription")
.build();
private static final List<String> SOURCE_URIS = ImmutableList.of("uri1", "uri2");
private static final List<SchemaUpdateOption> SCHEMA_UPDATE_OPTIONS =
ImmutableList.of(SchemaUpdateOption.ALLOW_FIELD_ADDITION);
private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA);
private static final Boolean AUTODETECT = true;
private static final Boolean USERAVROLOGICALTYPES = true;
private static final EncryptionConfiguration JOB_ENCRYPTION_CONFIGURATION =
EncryptionConfiguration.newBuilder().setKmsKeyName("KMS_KEY_1").build();
private static final TimePartitioning TIME_PARTITIONING = TimePartitioning.of(Type.DAY);
private static final Clustering CLUSTERING =
Clustering.newBuilder().setFields(ImmutableList.of("Foo", "Bar")).build();
private static final LoadJobConfiguration LOAD_CONFIGURATION_CSV =
LoadJobConfiguration.newBuilder(TABLE_ID, SOURCE_URIS)
.setCreateDisposition(CREATE_DISPOSITION)
.setWriteDisposition(WRITE_DISPOSITION)
.setFormatOptions(CSV_OPTIONS)
.setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES)
.setMaxBadRecords(MAX_BAD_RECORDS)
.setSchema(TABLE_SCHEMA)
.setSchemaUpdateOptions(SCHEMA_UPDATE_OPTIONS)
.setAutodetect(AUTODETECT)
.setDestinationEncryptionConfiguration(JOB_ENCRYPTION_CONFIGURATION)
.setTimePartitioning(TIME_PARTITIONING)
.setClustering(CLUSTERING)
.build();
private static final DatastoreBackupOptions BACKUP_OPTIONS =
DatastoreBackupOptions.newBuilder()
.setProjectionFields(ImmutableList.of("field_1", "field_2"))
.build();
private static final LoadJobConfiguration LOAD_CONFIGURATION_BACKUP =
LoadJobConfiguration.newBuilder(TABLE_ID, SOURCE_URIS)
.setCreateDisposition(CREATE_DISPOSITION)
.setWriteDisposition(WRITE_DISPOSITION)
.setFormatOptions(BACKUP_OPTIONS)
.setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES)
.setMaxBadRecords(MAX_BAD_RECORDS)
.setSchema(TABLE_SCHEMA)
.setSchemaUpdateOptions(SCHEMA_UPDATE_OPTIONS)
.setAutodetect(AUTODETECT)
.build();
private static final LoadJobConfiguration LOAD_CONFIGURATION_AVRO =
LoadJobConfiguration.newBuilder(TABLE_ID, SOURCE_URIS)
.setCreateDisposition(CREATE_DISPOSITION)
.setWriteDisposition(WRITE_DISPOSITION)
.setFormatOptions(FormatOptions.avro())
.setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES)
.setMaxBadRecords(MAX_BAD_RECORDS)
.setSchema(TABLE_SCHEMA)
.setSchemaUpdateOptions(SCHEMA_UPDATE_OPTIONS)
.setAutodetect(AUTODETECT)
.setDestinationEncryptionConfiguration(JOB_ENCRYPTION_CONFIGURATION)
.setTimePartitioning(TIME_PARTITIONING)
.setClustering(CLUSTERING)
.setUseAvroLogicalTypes(USERAVROLOGICALTYPES)
.build();
@Test
public void testToBuilder() {
compareLoadJobConfiguration(LOAD_CONFIGURATION_CSV, LOAD_CONFIGURATION_CSV.toBuilder().build());
LoadJobConfiguration configurationCSV =
LOAD_CONFIGURATION_CSV
.toBuilder()
.setDestinationTable(TableId.of("dataset", "newTable"))
.build();
assertEquals("newTable", configurationCSV.getDestinationTable().getTable());
configurationCSV = configurationCSV.toBuilder().setDestinationTable(TABLE_ID).build();
compareLoadJobConfiguration(LOAD_CONFIGURATION_CSV, configurationCSV);
compareLoadJobConfiguration(
LOAD_CONFIGURATION_BACKUP, LOAD_CONFIGURATION_BACKUP.toBuilder().build());
LoadJobConfiguration configurationBackup =
LOAD_CONFIGURATION_BACKUP
.toBuilder()
.setDestinationTable(TableId.of("dataset", "newTable"))
.build();
assertEquals("newTable", configurationBackup.getDestinationTable().getTable());
configurationBackup = configurationBackup.toBuilder().setDestinationTable(TABLE_ID).build();
compareLoadJobConfiguration(LOAD_CONFIGURATION_BACKUP, configurationBackup);
compareLoadJobConfiguration(
LOAD_CONFIGURATION_AVRO, LOAD_CONFIGURATION_AVRO.toBuilder().build());
LoadJobConfiguration configurationAvro =
LOAD_CONFIGURATION_AVRO
.toBuilder()
.setDestinationTable(TableId.of("dataset", "newTable"))
.build();
assertEquals("newTable", configurationAvro.getDestinationTable().getTable());
configurationAvro = configurationAvro.toBuilder().setDestinationTable(TABLE_ID).build();
compareLoadJobConfiguration(LOAD_CONFIGURATION_AVRO, configurationAvro);
}
@Test
public void testOf() {
LoadJobConfiguration configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS);
assertEquals(TABLE_ID, configuration.getDestinationTable());
assertEquals(SOURCE_URIS, configuration.getSourceUris());
configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS, CSV_OPTIONS);
assertEquals(TABLE_ID, configuration.getDestinationTable());
assertEquals(FORMAT, configuration.getFormat());
assertEquals(CSV_OPTIONS, configuration.getCsvOptions());
assertEquals(SOURCE_URIS, configuration.getSourceUris());
configuration = LoadJobConfiguration.of(TABLE_ID, "uri1");
assertEquals(TABLE_ID, configuration.getDestinationTable());
assertEquals(ImmutableList.of("uri1"), configuration.getSourceUris());
configuration = LoadJobConfiguration.of(TABLE_ID, "uri1", CSV_OPTIONS);
assertEquals(TABLE_ID, configuration.getDestinationTable());
assertEquals(FORMAT, configuration.getFormat());
assertEquals(CSV_OPTIONS, configuration.getCsvOptions());
assertEquals(ImmutableList.of("uri1"), configuration.getSourceUris());
}
@Test
public void testToBuilderIncomplete() {
LoadJobConfiguration configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS);
compareLoadJobConfiguration(configuration, configuration.toBuilder().build());
}
@Test
public void testToPbAndFromPb() {
compareLoadJobConfiguration(
LOAD_CONFIGURATION_CSV, LoadJobConfiguration.fromPb(LOAD_CONFIGURATION_CSV.toPb()));
LoadJobConfiguration configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS);
compareLoadJobConfiguration(configuration, LoadJobConfiguration.fromPb(configuration.toPb()));
}
@Test
public void testSetProjectId() {
LoadConfiguration configuration = LOAD_CONFIGURATION_CSV.setProjectId(TEST_PROJECT_ID);
assertEquals(TEST_PROJECT_ID, configuration.getDestinationTable().getProject());
}
@Test
public void testSetProjectIdDoNotOverride() {
LoadConfiguration configuration =
LOAD_CONFIGURATION_CSV
.toBuilder()
.setDestinationTable(TABLE_ID.setProjectId(TEST_PROJECT_ID))
.build()
.setProjectId("do-not-update");
assertEquals(TEST_PROJECT_ID, configuration.getDestinationTable().getProject());
}
@Test
public void testGetType() {
assertEquals(JobConfiguration.Type.LOAD, LOAD_CONFIGURATION_CSV.getType());
}
private void compareLoadJobConfiguration(
LoadJobConfiguration expected, LoadJobConfiguration value) {
assertEquals(expected, value);
assertEquals(expected.hashCode(), value.hashCode());
assertEquals(expected.toString(), value.toString());
assertEquals(expected.getDestinationTable(), value.getDestinationTable());
assertEquals(expected.getCreateDisposition(), value.getCreateDisposition());
assertEquals(expected.getWriteDisposition(), value.getWriteDisposition());
assertEquals(expected.getCsvOptions(), value.getCsvOptions());
assertEquals(expected.getFormat(), value.getFormat());
assertEquals(expected.ignoreUnknownValues(), value.ignoreUnknownValues());
assertEquals(expected.getMaxBadRecords(), value.getMaxBadRecords());
assertEquals(expected.getSchema(), value.getSchema());
assertEquals(expected.getDatastoreBackupOptions(), value.getDatastoreBackupOptions());
assertEquals(expected.getAutodetect(), value.getAutodetect());
assertEquals(expected.getSchemaUpdateOptions(), value.getSchemaUpdateOptions());
assertEquals(
expected.getDestinationEncryptionConfiguration(),
value.getDestinationEncryptionConfiguration());
assertEquals(expected.getTimePartitioning(), value.getTimePartitioning());
assertEquals(expected.getClustering(), value.getClustering());
assertEquals(expected.getUseAvroLogicalTypes(), value.getUseAvroLogicalTypes());
}
}
|
vam-google/google-cloud-java
|
google-cloud-clients/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java
|
Java
|
apache-2.0
| 10,561
|
// Copyright 2014 Software Freedom Conservancy
// 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.
#include "IEWebDriverManagerCommandExecutor.h"
#include "CommandExecutor.h"
#include "command_types.h"
#include "errorcodes.h"
#include "IEWebDriverManagerIds.h"
#include "interactions.h"
#include "json.h"
#include "logging.h"
#include "StringUtilities.h"
namespace webdriver {
LRESULT IEWebDriverManagerCommandExecutor::OnCreate(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::OnCreate";
CREATESTRUCT* create = reinterpret_cast<CREATESTRUCT*>(lParam);
// NOTE: COM should be initialized on this thread, so we
// could use CoCreateGuid() and StringFromGUID2() instead.
UUID guid;
RPC_WSTR guid_string = NULL;
RPC_STATUS status = ::UuidCreate(&guid);
status = ::UuidToString(&guid, &guid_string);
// RPC_WSTR is currently typedef'd in RpcDce.h (pulled in by rpc.h)
// as unsigned short*. It needs to be typedef'd as wchar_t*
wchar_t* cast_guid_string = reinterpret_cast<wchar_t*>(guid_string);
this->SetWindowText(L"IEWebDriverManagerExecutor");
std::string session_id = StringUtilities::ToString(cast_guid_string);
this->session_id_ = session_id;
this->is_valid_ = true;
this->is_quitting_ = false;
::RpcStringFree(&guid_string);
this->current_browser_id_ = "";
this->serialized_response_ = "";
// This call may not be required, but let's not take any chances.
setEnablePersistentHover(false);
this->factory_ = new BrowserFactory();
HRESULT hr = ::CoCreateInstance(CLSID_IEWebDriverManager,
NULL,
CLSCTX_INPROC_SERVER,
IID_IIEWebDriverManager,
reinterpret_cast<void**>(&this->manager_));
if (FAILED(hr)) {
// TOOD: Handle the case where the COM object is not installed.
LOGHR(WARN, hr) << "Could not create instance of class IEWebDriverManager";
}
return 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnDestroy(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(DEBUG) << "Entering IEWebDriverManagerCommandExecutor::OnDestroy";
LOG(DEBUG) << "Posting quit message";
this->manager_.Release();
::PostQuitMessage(0);
LOG(DEBUG) << "Leaving IEWebDriverManagerCommandExecutor::OnDestroy";
return 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnSetCommand(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::OnSetCommand";
LPCSTR json_command = reinterpret_cast<LPCSTR>(lParam);
this->current_command_.Deserialize(json_command);
return 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnExecCommand(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::OnExecCommand";
this->DispatchCommand();
return 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnGetResponseLength(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
// Not logging trace entering IEDevChannelCommandExecutor::OnGetResponseLength,
// because it is polled repeatedly for a non-zero return value.
size_t response_length = 0;
if (!this->is_waiting_) {
response_length = this->serialized_response_.size();
}
return response_length;
}
LRESULT IEWebDriverManagerCommandExecutor::OnGetResponse(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::OnGetResponse";
LPSTR str = reinterpret_cast<LPSTR>(lParam);
strcpy_s(str,
this->serialized_response_.size() + 1,
this->serialized_response_.c_str());
// Reset the serialized response for the next command.
this->serialized_response_ = "";
return 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnIsSessionValid(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::OnIsSessionValid";
return this->is_valid_ ? 1 : 0;
}
LRESULT IEWebDriverManagerCommandExecutor::OnGetQuitStatus(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
BOOL& bHandled) {
// At present, there is no need to track when the executor
// is quitting. We can simply assume all instances have
// appropriately quit, and can proceed with destroying the
// executor.
return 0;
}
unsigned int WINAPI IEWebDriverManagerCommandExecutor::ThreadProc(LPVOID lpParameter) {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::ThreadProc";
IECommandExecutorThreadContext* thread_context = reinterpret_cast<IECommandExecutorThreadContext*>(lpParameter);
HWND window_handle = thread_context->hwnd;
// it is better to use IECommandExecutorSessionContext instead
// but use ThreadContext for code minimization
IECommandExecutorThreadContext* session_context = new IECommandExecutorThreadContext();
session_context->port = thread_context->port;
DWORD error = 0;
HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr)) {
LOGHR(DEBUG, hr) << "COM library initialization encountered an error";
}
IEWebDriverManagerCommandExecutor new_session;
HWND session_window_handle = new_session.Create(/*HWND*/ HWND_MESSAGE,
/*_U_RECT rect*/ CWindow::rcDefault,
/*LPCTSTR szWindowName*/ NULL,
/*DWORD dwStyle*/ NULL,
/*DWORD dwExStyle*/ NULL,
/*_U_MENUorID MenuOrID*/ 0U,
/*LPVOID lpCreateParam*/ reinterpret_cast<LPVOID*>(session_context));
if (session_window_handle == NULL) {
LOGERR(WARN) << "Unable to create new IECommandExecutor session";
}
MSG msg;
::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
// Return the HWND back through lpParameter, and signal that the
// window is ready for messages.
thread_context->hwnd = session_window_handle;
HANDLE event_handle = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME);
if (event_handle != NULL) {
::SetEvent(event_handle);
::CloseHandle(event_handle);
} else {
LOGERR(DEBUG) << "Unable to signal that window is ready";
}
// Run the message loop
BOOL get_message_return_value;
while ((get_message_return_value = ::GetMessage(&msg, NULL, 0, 0)) != 0) {
if (get_message_return_value == -1) {
LOGERR(WARN) << "Windows GetMessage() API returned error";
break;
} else {
if (msg.message == WD_SHUTDOWN) {
LOG(DEBUG) << "Shutdown message received";
new_session.DestroyWindow();
LOG(DEBUG) << "Returned from DestroyWindow()";
break;
} else {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
}
LOG(DEBUG) << "Exited IECommandExecutor thread message loop";
::CoUninitialize();
delete session_context;
return 0;
}
void IEWebDriverManagerCommandExecutor::DispatchCommand() {
LOG(TRACE) << "Entering IEWebDriverManagerCommandExecutor::DispatchCommand";
std::wstring serialized_command = StringUtilities::ToWString(this->current_command_.Serialize());
LPWSTR pszResult = nullptr;
HRESULT hr = this->manager_->ExecuteCommand((LPWSTR)serialized_command.c_str(), &pszResult);
std::wstring result(pszResult);
Response actual_response;
actual_response.Deserialize(StringUtilities::ToString(result));
this->serialized_response_ = actual_response.Serialize();
::CoTaskMemFree(pszResult);
if (this->current_command_.command_type() == webdriver::CommandType::Close ||
this->current_command_.command_type() == webdriver::CommandType::Quit) {
this->is_valid_ = false;
}
}
} // namespace webdriver
|
cisco-open-source/selenium
|
cpp/iedriver/IEWebDriverManagerCommandExecutor.cpp
|
C++
|
apache-2.0
| 9,421
|
package com.okhttp.listener;
/**
* @author vision
*
*/
public class DisposeDataHandle
{
public DisposeDataListener mListener = null;
public Class<?> mClass = null;
public String mSource = null;
public DisposeDataHandle(DisposeDataListener listener)
{
this.mListener = listener;
}
public DisposeDataHandle(DisposeDataListener listener, Class<?> clazz)
{
this.mListener = listener;
this.mClass = clazz;
}
public DisposeDataHandle(DisposeDataListener listener, String source)
{
this.mListener = listener;
this.mSource = source;
}
}
|
qndroid/CommonLibrary
|
CommonHttpLibrary/src/com/okhttp/listener/DisposeDataHandle.java
|
Java
|
apache-2.0
| 557
|
package com.maojianwei.chinese.poetry.log;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by mao on 4/10/16.
*/
public class LogSystem {
public static void initAppLogSystem(){
LogManager.resetConfiguration();//avoid config override by other jar
PropertyConfigurator.configure(LogSystem.class.getResource("/log4j.properties"));
// TODO - Attention!!! The method of Reference to resource file included by Maven is below!
// LogSystem.class.getResource("/log4j.properties")
}
public static void main(String args[]){
LogSystem logSystem = new LogSystem();
logSystem.testLog();
}
public void testLog() {
Logger logger = LoggerFactory.getLogger(getClass());
logger.info("radar");
int a = 118;
logger.warn("contect tower on {}", a);
logger.error("contect tower on {}", a);
}
}
|
MaoJianwei/Chinese_Poetry
|
src/main/java/com/maojianwei/chinese/poetry/log/LogSystem.java
|
Java
|
apache-2.0
| 999
|
package tastytest
object TestNestedEnum extends Suite("TestNestedEnum") {
test("call toString on enum of inner class") {
val n = new NestedEnum()
assert(n.Mode.On.toString == "On")
}
test("nested enums do not have same type") {
val n1 = new NestedEnum()
val n2 = new NestedEnum()
implicitly[scala.util.NotGiven[n1.Mode.Off.type =:= n2.Mode.Off.type]]
assert(n1.Mode.Off != n2.Mode.Off)
}
}
|
scala/scala
|
test/tasty/run/src-2/tastytest/TestNestedEnum.scala
|
Scala
|
apache-2.0
| 426
|
/*
* Author: Arjune
*/
body {
max-width: 1200px;
background-color: #F0F0F0;
margin: 0 auto;
}
#main-header {
height: 150px;
width: 100%;
}
#container {
width: 100%;
background-color: #fff;
border: 1px solid #F8F8F8;
border-radius: 20px;
padding-left: 30px;
}
nav#menu {
width: 100%;
height: 50px;
margin: 20px 0;
}
nav#menu ul {
}
nav#menu li {
list-style-type: none;
display: inline-block;
width: 60px;
padding: 13px;
color: #f71570;
background-color: #e6e6e6;
box-shadow: 1px 1px 1px #F0F0F0;
margin: 0 10px;
text-align: center;
border: 1px solid;
border-color: #fff #c9c9c9 #c9c9c9 #fff;
background-image: -webkit-linear-gradient(top, #f2f2f2, #e6e6e6 100%);
font-size: 1.3em;
text-shadow: 0 1px 0 #fff;
}
nav#menu li.active {
background-color: #f71570;
background-image: -webkit-linear-gradient(top, #f950ab, #f71570 100%);
border-radius: 10px 0 10px 0;
color: #fff;
text-shadow: 0 1px 0 #f71570;
}
nav#menu li:hover, nav#menu li.active:hover {
border-radius: 0 10px 0 10px;
cursor: pointer;
}
|
arjumn/bane-repo
|
UIs/pinktheme.css
|
CSS
|
apache-2.0
| 1,152
|
<!DOCTYPE html >
<html>
<head>
<title>Conductors - ScalaTest 3.0.0 - org.scalatest.concurrent.Conductors</title>
<meta name="description" content="Conductors - ScalaTest 3.0.0 - org.scalatest.concurrent.Conductors" />
<meta name="keywords" content="Conductors ScalaTest 3.0.0 org.scalatest.concurrent.Conductors" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../index.html';
var hash = 'org.scalatest.concurrent.Conductors';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<img alt="Trait" src="../../../lib/trait_big.png" />
<p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.concurrent">concurrent</a></p>
<h1>Conductors</h1><h3><span class="morelinks"><div>Related Doc:
<a href="package.html" class="extype" name="org.scalatest.concurrent">package concurrent</a>
</div></span></h3><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">trait</span>
</span>
<span class="symbol">
<span class="name">Conductors</span><span class="result"> extends <a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Trait whose <code>Conductor</code> member facilitates the testing of classes, traits, and libraries designed
to be used by multiple threads concurrently.</p><p>A <code>Conductor</code> conducts a multi-threaded scenario by maintaining
a clock of "beats." Beats are numbered starting with 0. You can ask a
<code>Conductor</code> to run threads that interact with the class, trait,
or library (the <em>subject</em>)
you want to test. A thread can call the <code>Conductor</code>'s
<code>waitForBeat</code> method, which will cause the thread to block
until that beat has been reached. The <code>Conductor</code> will advance
the beat only when all threads participating in the test are blocked. By
tying the timing of thread activities to specific beats, you can write
tests for concurrent systems that have deterministic interleavings of
threads.</p><p>A <code>Conductor</code> object has a three-phase lifecycle. It begins its life
in the <em>setup</em> phase. During this phase, you can start threads by
invoking the <code>thread</code> method on the <code>Conductor</code>.
When <code>conduct</code> is invoked on a <code>Conductor</code>, it enters
the <em>conducting</em> phase. During this phase it conducts the one multi-threaded
scenario it was designed to conduct. After all participating threads have exited, either by
returning normally or throwing an exception, the <code>conduct</code> method
will complete, either by returning normally or throwing an exception. As soon as
the <code>conduct</code> method completes, the <code>Conductor</code>
enters its <em>defunct</em> phase. Once the <code>Conductor</code> has conducted
a multi-threaded scenario, it is defunct and can't be reused. To run the same test again,
you'll need to create a new instance of <code>Conductor</code>.</p><p>Here's an example of the use of <code>Conductor</code> to test the <code>ArrayBlockingQueue</code>
class from <code>java.util.concurrent</code>:</p><p><pre class="stHighlighted">
<span class="stReserved">import</span> org.scalatest.fixture.FunSuite
<span class="stReserved">import</span> org.scalatest.matchers.Matchers
<span class="stReserved">import</span> java.util.concurrent.ArrayBlockingQueue
<span class="stReserved">import</span> org.scalatest.concurrent.Conductors
<span class="stReserved">class</span> <span class="stType">ArrayBlockingQueueSuite</span> <span class="stReserved">extends</span> <span class="stType">FunSuite</span> <span class="stReserved">with</span> <span class="stType">Matchers</span> <span class="stReserved">with</span> <span class="stType">Conductors</span> {
test(<span class="stQuotedString">"calling put on a full queue blocks the producer thread"</span>) {
<span class="stReserved">val</span> conductor = <span class="stReserved">new</span> <span class="stType">Conductor</span>
<span class="stReserved">import</span> conductor._
<span class="stReserved">val</span> buf = <span class="stReserved">new</span> <span class="stType">ArrayBlockingQueue[Int]</span>(<span class="stLiteral">1</span>)
thread(<span class="stQuotedString">"producer"</span>) {
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
beat should be (<span class="stLiteral">1</span>)
}
thread(<span class="stQuotedString">"consumer"</span>) {
waitForBeat(<span class="stLiteral">1</span>)
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
}
whenFinished {
buf should be (<span class="stQuotedString">'empty</span>)
}
}
}
</pre></p><p>When the test shown is run, it will create one thread named <em>producer</em> and another named
<em>consumer</em>. The producer thread will eventually execute the code passed as a by-name
parameter to <code>thread("producer")</code>:</p><p><pre class="stHighlighted">
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
beat should be (<span class="stLiteral">1</span>)
</pre></p><p>Similarly, the consumer thread will eventually execute the code passed as a by-name parameter
to <code>thread("consumer")</code>:</p><p><pre class="stHighlighted">
waitForBeat(<span class="stLiteral">1</span>)
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
</pre></p><p>The <code>thread</code> creates the threads and starts them, but they will not immediately
execute the by-name parameter passed to them. They will first block, waiting for the <code>Conductor</code>
to give them a green light to proceed.</p><p>The next call in the test is <code>whenFinished</code>. This method will first call <code>conduct</code> on
the <code>Conductor</code>, which will wait until all threads that were created (in this case, producer and consumer) are
at the "starting line", <em>i.e.</em>, they have all started and are blocked, waiting on the green light.
The <code>conduct</code> method will then give these threads the green light and they will
all start executing their blocks concurrently.</p><p>When the threads are given the green light, the beat is 0. The first thing the producer thread does is put 42 in
into the queue. As the queue is empty at this point, this succeeds. The producer thread next attempts to put a 17
into the queue, but because the queue has size 1, this can't succeed until the consumer thread has read the 42
from the queue. This hasn't happened yet, so producer blocks. Meanwhile, the consumer thread's first act is to
call <code>waitForBeat(1)</code>. Because the beat starts out at 0, this call will block the consumer thread.
As a result, once the producer thread has executed <code>buf put 17</code> and the consumer thread has executed
<code>waitForBeat(1)</code>, both threads will be blocked.</p><p>The <code>Conductor</code> maintains a clock that wakes up periodically and checks to see if all threads
participating in the multi-threaded scenario (in this case, producer and consumer) are blocked. If so, it
increments the beat. Thus sometime later the beat will be incremented, from 0 to 1. Because consumer was
waiting for beat 1, it will wake up (<em>i.e.</em>, the <code>waitForBeat(1)</code> call will return) and
execute the next line of code in its block, <code>buf.take should be (42)</code>. This will succeed, because
the producer thread had previously (during beat 0) put 42 into the queue. This act will also make
producer runnable again, because it was blocked on the second <code>put</code>, which was waiting for another
thread to read that 42.</p><p>Now both threads are unblocked and able to execute their next statement. The order is
non-deterministic, and can even be simultaneous if running on multiple cores. If the <code>consumer</code> thread
happens to execute <code>buf.take should be (17)</code> first, it will block (<code>buf.take</code> will not return), because the queue is
at that point empty. At some point later, the producer thread will execute <code>buf put 17</code>, which will
unblock the consumer thread. Again both threads will be runnable and the order non-deterministic and
possibly simulataneous. The producer thread may charge ahead and run its next statement, <code>beat should be (1)</code>.
This will succeed because the beat is indeed 1 at this point. As this is the last statement in the producer's block,
the producer thread will exit normally (it won't throw an exception). At some point later the consumer thread will
be allowed to complete its last statement, the <code>buf.take</code> call will return 17. The consumer thread will
execute <code>17 should be (17)</code>. This will succeed and as this was the last statement in its block, the consumer will return
normally.</p><p>If either the producer or consumer thread had completed abruptbly with an exception, the <code>conduct</code> method
(which was called by <code>whenFinished</code>) would have completed abruptly with an exception to indicate the test
failed. However, since both threads returned normally, <code>conduct</code> will return. Because <code>conduct</code> doesn't
throw an exception, <code>whenFinished</code> will execute the block of code passed as a by-name parameter to it: <code>buf should be ('empty)</code>.
This will succeed, because the queue is indeed empty at this point. The <code>whenFinished</code> method will then return, and
because the <code>whenFinished</code> call was the last statement in the test and it didn't throw an exception, the test completes successfully.</p><p>This test tests <code>ArrayBlockingQueue</code>, to make sure it works as expected. If there were a bug in <code>ArrayBlockingQueue</code>
such as a <code>put</code> called on a full queue didn't block, but instead overwrote the previous value, this test would detect
it. However, if there were a bug in <code>ArrayBlockingQueue</code> such that a call to <code>take</code> called on an empty queue
never blocked and always returned 0, this test might not detect it. The reason is that whether the consumer thread will ever call
<code>take</code> on an empty queue during this test is non-deterministic. It depends on how the threads get scheduled during beat 1.
What is deterministic in this test, because the consumer thread blocks during beat 0, is that the producer thread will definitely
attempt to write to a full queue. To make sure the other scenario is tested, you'd need a different test:</p><p><pre class="stHighlighted">
test(<span class="stQuotedString">"calling take on an empty queue blocks the consumer thread"</span>) {
<span class="stReserved">val</span> conductor = <span class="stReserved">new</span> <span class="stType">Conductor</span>
<span class="stReserved">import</span> conductor._
<span class="stReserved">val</span> buf = <span class="stReserved">new</span> <span class="stType">ArrayBlockingQueue[Int]</span>(<span class="stLiteral">1</span>)
thread(<span class="stQuotedString">"producer"</span>) {
waitForBeat(<span class="stLiteral">1</span>)
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
}
thread(<span class="stQuotedString">"consumer"</span>) {
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
beat should be (<span class="stLiteral">1</span>)
}
whenFinished {
buf should be (<span class="stQuotedString">'empty</span>)
}
}
</pre></p><p>In this test, the producer thread will block, waiting for beat 1. The consumer thread will invoke <code>buf.take</code>
as its first act. This will block, because the queue is empty. Because both threads are blocked, the <code>Conductor</code>
will at some point later increment the beat to 1. This will awaken the producer thread. It will return from its
<code>waitForBeat(1)</code> call and execute <code>buf put 42</code>. This will unblock the consumer thread, which will
take the 42, and so on.</p><p>The problem that <code>Conductor</code> is designed to address is the difficulty, caused by the non-deterministic nature
of thread scheduling, of testing classes, traits, and libraries that are intended to be used by multiple threads.
If you just create a test in which one thread reads from an <code>ArrayBlockingQueue</code> and
another writes to it, you can't be sure that you have tested all possible interleavings of threads, no matter
how many times you run the test. The purpose of <code>Conductor</code>
is to enable you to write tests with deterministic interleavings of threads. If you write one test for each possible
interleaving of threads, then you can be sure you have all the scenarios tested. The two tests shown here, for example,
ensure that both the scenario in which a producer thread tries to write to a full queue and the scenario in which a
consumer thread tries to take from an empty queue are tested.</p><p>Class <code>Conductor</code> was inspired by the
<a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/">MultithreadedTC project</a>,
created by Bill Pugh and Nat Ayewah of the University of Maryland.</p><p>Although useful, bear in mind that a <code>Conductor</code>'s results are not guaranteed to be
accurate 100% of the time. The reason is that it uses <code>java.lang.Thread</code>'s <code>getState</code> method to
decide when to advance the beat. This use goes against the advice given in the Javadoc documentation for
<code>getState</code>, which says, "This method is designed for use in monitoring of the system state, not for
synchronization." In short, sometimes the return value of <code>getState</code> occasionally may be inacurrate,
which in turn means that sometimes a <code>Conductor</code> could decide to advance the beat too early. In practice,
<code>Conductor</code> has proven to be very helpful when developing thread safe classes. It is also useful in
for regression tests, but you may have to tolerate occasional false negatives.</p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.0/scalatest//src/main/scala/org/scalatest/concurrent/Conductors.scala" target="_blank">Conductors.scala</a></dd></dl><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a>, <a href="AbstractPatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.AbstractPatienceConfiguration">AbstractPatienceConfiguration</a>, <a href="ScaledTimeSpans.html" class="extype" name="org.scalatest.concurrent.ScaledTimeSpans">ScaledTimeSpans</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div><div class="toggleContainer block">
<span class="toggle">Known Subclasses</span>
<div class="subClasses hiddenContent"><a href="ConductorFixture.html" class="extype" name="org.scalatest.concurrent.ConductorFixture">ConductorFixture</a>, <a href="ConductorMethods.html" class="extype" name="org.scalatest.concurrent.ConductorMethods">ConductorMethods</a></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="org.scalatest.concurrent.Conductors"><span>Conductors</span></li><li class="in" name="org.scalatest.concurrent.PatienceConfiguration"><span>PatienceConfiguration</span></li><li class="in" name="org.scalatest.concurrent.AbstractPatienceConfiguration"><span>AbstractPatienceConfiguration</span></li><li class="in" name="org.scalatest.concurrent.ScaledTimeSpans"><span>ScaledTimeSpans</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="types" class="types members">
<h3>Type Members</h3>
<ol><li name="org.scalatest.concurrent.Conductors.Conductor" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ConductorextendsAnyRef"></a>
<a id="Conductor:Conductor"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">class</span>
</span>
<span class="symbol">
<a href="Conductors$Conductor.html"><span class="name">Conductor</span></a><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@ConductorextendsAnyRef" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Class that facilitates the testing of classes, traits, and libraries designed
to be used by multiple threads concurrently.</p><div class="fullcomment"><div class="comment cmt"><p>Class that facilitates the testing of classes, traits, and libraries designed
to be used by multiple threads concurrently.</p><p>A <code>Conductor</code> conducts a multi-threaded scenario by maintaining
a clock of "beats." Beats are numbered starting with 0. You can ask a
<code>Conductor</code> to run threads that interact with the class, trait,
or library (the <em>subject</em>)
you want to test. A thread can call the <code>Conductor</code>'s
<code>waitForBeat</code> method, which will cause the thread to block
until that beat has been reached. The <code>Conductor</code> will advance
the beat only when all threads participating in the test are blocked. By
tying the timing of thread activities to specific beats, you can write
tests for concurrent systems that have deterministic interleavings of
threads.</p><p>A <code>Conductor</code> object has a three-phase lifecycle. It begins its life
in the <em>setup</em> phase. During this phase, you can start threads by
invoking the <code>thread</code> method on the <code>Conductor</code>.
When <code>conduct</code> is invoked on a <code>Conductor</code>, it enters
the <em>conducting</em> phase. During this phase it conducts the one multi-threaded
scenario it was designed to conduct. After all participating threads have exited, either by
returning normally or throwing an exception, the <code>conduct</code> method
will complete, either by returning normally or throwing an exception. As soon as
the <code>conduct</code> method completes, the <code>Conductor</code>
enters its <em>defunct</em> phase. Once the <code>Conductor</code> has conducted
a multi-threaded scenario, it is defunct and can't be reused. To run the same test again,
you'll need to create a new instance of <code>Conductor</code>.</p><p>Here's an example of the use of <code>Conductor</code> to test the <code>ArrayBlockingQueue</code>
class from <code>java.util.concurrent</code>:</p><p><pre class="stHighlighted">
<span class="stReserved">import</span> org.scalatest.fixture.FunSuite
<span class="stReserved">import</span> org.scalatest.matchers.Matchers
<span class="stReserved">import</span> java.util.concurrent.ArrayBlockingQueue
<span class="stReserved">import</span> org.scalatest.concurrent.Conductors
<span class="stReserved">class</span> <span class="stType">ArrayBlockingQueueSuite</span> <span class="stReserved">extends</span> <span class="stType">FunSuite</span> <span class="stReserved">with</span> <span class="stType">Matchers</span> <span class="stReserved">with</span> <span class="stType">Conductors</span> {
test(<span class="stQuotedString">"calling put on a full queue blocks the producer thread"</span>) {
<span class="stReserved">val</span> conductor = <span class="stReserved">new</span> <span class="stType">Conductor</span>
<span class="stReserved">import</span> conductor._
<span class="stReserved">val</span> buf = <span class="stReserved">new</span> <span class="stType">ArrayBlockingQueue[Int]</span>(<span class="stLiteral">1</span>)
thread(<span class="stQuotedString">"producer"</span>) {
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
beat should be (<span class="stLiteral">1</span>)
}
thread(<span class="stQuotedString">"consumer"</span>) {
waitForBeat(<span class="stLiteral">1</span>)
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
}
whenFinished {
buf should be (<span class="stQuotedString">'empty</span>)
}
}
}
</pre></p><p>When the test shown is run, it will create one thread named <em>producer</em> and another named
<em>consumer</em>. The producer thread will eventually execute the code passed as a by-name
parameter to <code>thread("producer")</code>:</p><p><pre class="stHighlighted">
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
beat should be (<span class="stLiteral">1</span>)
</pre></p><p>Similarly, the consumer thread will eventually execute the code passed as a by-name parameter
to <code>thread("consumer")</code>:</p><p><pre class="stHighlighted">
waitForBeat(<span class="stLiteral">1</span>)
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
</pre></p><p>The <code>thread</code> calls create the threads and starts them, but they will not immediately
execute the by-name parameter passed to them. They will first block, waiting for the <code>Conductor</code>
to give them a green light to proceed.</p><p>The next call in the test is <code>whenFinished</code>. This method will first call <code>conduct</code> on
the <code>Conductor</code>, which will wait until all threads that were created (in this case, producer and consumer) are
at the "starting line", <em>i.e.</em>, they have all started and are blocked, waiting on the green light.
The <code>conduct</code> method will then give these threads the green light and they will
all start executing their blocks concurrently.</p><p>When the threads are given the green light, the beat is 0. The first thing the producer thread does is put 42 in
into the queue. As the queue is empty at this point, this succeeds. The producer thread next attempts to put a 17
into the queue, but because the queue has size 1, this can't succeed until the consumer thread has read the 42
from the queue. This hasn't happened yet, so producer blocks. Meanwhile, the consumer thread's first act is to
call <code>waitForBeat(1)</code>. Because the beat starts out at 0, this call will block the consumer thread.
As a result, once the producer thread has executed <code>buf put 17</code> and the consumer thread has executed
<code>waitForBeat(1)</code>, both threads will be blocked.</p><p>The <code>Conductor</code> maintains a clock that wakes up periodically and checks to see if all threads
participating in the multi-threaded scenario (in this case, producer and consumer) are blocked. If so, it
increments the beat. Thus sometime later the beat will be incremented, from 0 to 1. Because consumer was
waiting for beat 1, it will wake up (<em>i.e.</em>, the <code>waitForBeat(1)</code> call will return) and
execute the next line of code in its block, <code>buf.take should be (42)</code>. This will succeed, because
the producer thread had previously (during beat 0) put 42 into the queue. This act will also make
producer runnable again, because it was blocked on the second <code>put</code>, which was waiting for another
thread to read that 42.</p><p>Now both threads are unblocked and able to execute their next statement. The order is
non-deterministic, and can even be simultaneous if running on multiple cores. If the <code>consumer</code> thread
happens to execute <code>buf.take should be (17)</code> first, it will block (<code>buf.take</code> will not return), because the queue is
at that point empty. At some point later, the producer thread will execute <code>buf put 17</code>, which will
unblock the consumer thread. Again both threads will be runnable and the order non-deterministic and
possibly simulataneous. The producer thread may charge ahead and run its next statement, <code>beat should be (1)</code>.
This will succeed because the beat is indeed 1 at this point. As this is the last statement in the producer's block,
the producer thread will exit normally (it won't throw an exception). At some point later the consumer thread will
be allowed to complete its last statement, the <code>buf.take</code> call will return 17. The consumer thread will
execute <code>17 should be (17)</code>. This will succeed and as this was the last statement in its block, the consumer will return
normally.</p><p>If either the producer or consumer thread had completed abruptbly with an exception, the <code>conduct</code> method
(which was called by <code>whenFinished</code>) would have completed abruptly with an exception to indicate the test
failed. However, since both threads returned normally, <code>conduct</code> will return. Because <code>conduct</code> doesn't
throw an exception, <code>whenFinished</code> will execute the block of code passed as a by-name parameter to it: <code>buf should be ('empty)</code>.
This will succeed, because the queue is indeed empty at this point. The <code>whenFinished</code> method will then return, and
because the <code>whenFinished</code> call was the last statement in the test and it didn't throw an exception, the test completes successfully.</p><p>This test tests <code>ArrayBlockingQueue</code>, to make sure it works as expected. If there were a bug in <code>ArrayBlockingQueue</code>
such as a <code>put</code> called on a full queue didn't block, but instead overwrote the previous value, this test would detect
it. However, if there were a bug in <code>ArrayBlockingQueue</code> such that a call to <code>take</code> called on an empty queue
never blocked and always returned 0, this test might not detect it. The reason is that whether the consumer thread will ever call
<code>take</code> on an empty queue during this test is non-deterministic. It depends on how the threads get scheduled during beat 1.
What is deterministic in this test, because the consumer thread blocks during beat 0, is that the producer thread will definitely
attempt to write to a full queue. To make sure the other scenario is tested, you'd need a different test:</p><p><pre class="stHighlighted">
test(<span class="stQuotedString">"calling take on an empty queue blocks the consumer thread"</span>) {
<span class="stReserved">val</span> conductor = <span class="stReserved">new</span> <span class="stType">Conductor</span>
<span class="stReserved">import</span> conductor._
<span class="stReserved">val</span> buf = <span class="stReserved">new</span> <span class="stType">ArrayBlockingQueue[Int]</span>(<span class="stLiteral">1</span>)
thread(<span class="stQuotedString">"producer"</span>) {
waitForBeat(<span class="stLiteral">1</span>)
buf put <span class="stLiteral">42</span>
buf put <span class="stLiteral">17</span>
}
thread(<span class="stQuotedString">"consumer"</span>) {
buf.take should be (<span class="stLiteral">42</span>)
buf.take should be (<span class="stLiteral">17</span>)
beat should be (<span class="stLiteral">1</span>)
}
whenFinished {
buf should be (<span class="stQuotedString">'empty</span>)
}
}
</pre></p><p>In this test, the producer thread will block, waiting for beat 1. The consumer thread will invoke <code>buf.take</code>
as its first act. This will block, because the queue is empty. Because both threads are blocked, the <code>Conductor</code>
will at some point later increment the beat to 1. This will awaken the producer thread. It will return from its
<code>waitForBeat(1)</code> call and execute <code>buf put 42</code>. This will unblock the consumer thread, which will
take the 42, and so on.</p><p>The problem that <code>Conductor</code> is designed to address is the difficulty, caused by the non-deterministic nature
of thread scheduling, of testing classes, traits, and libraries that are intended to be used by multiple threads.
If you just create a test in which one thread reads from an <code>ArrayBlockingQueue</code> and
another writes to it, you can't be sure that you have tested all possible interleavings of threads, no matter
how many times you run the test. The purpose of <code>Conductor</code>
is to enable you to write tests with deterministic interleavings of threads. If you write one test for each possible
interleaving of threads, then you can be sure you have all the scenarios tested. The two tests shown here, for example,
ensure that both the scenario in which a producer thread tries to write to a full queue and the scenario in which a
consumer thread tries to take from an empty queue are tested.</p><p>Class <code>Conductor</code> was inspired by the
<a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/">MultithreadedTC project</a>,
created by Bill Pugh and Nat Ayewah of the University of Maryland.</p><p>Although useful, bear in mind that a <code>Conductor</code>'s results are not guaranteed to be
accurate 100% of the time. The reason is that it uses <code>java.lang.Thread</code>'s <code>getState</code> method to
decide when to advance the beat. This use goes against the advice given in the Javadoc documentation for
<code>getState</code>, which says, "This method is designed for use in monitoring of the system state, not for
synchronization." In short, sometimes the return value of <code>getState</code> occasionally may be inacurrate,
which in turn means that sometimes a <code>Conductor</code> could decide to advance the beat too early. In practice,
<code>Conductor</code> has proven to be very helpful when developing thread safe classes. It is also useful in
for regression tests, but you may have to tolerate occasional false negatives.</p></div></div>
</li><li name="org.scalatest.concurrent.AbstractPatienceConfiguration.PatienceConfig" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="PatienceConfigextendsProductwithSerializable"></a>
<a id="PatienceConfig:PatienceConfig"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">case class</span>
</span>
<span class="symbol">
<a href="AbstractPatienceConfiguration$PatienceConfig.html"><span class="name">PatienceConfig</span></a><span class="params">(<span name="timeout">timeout: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a> = <span class="symbol"><span class="name"><a href="../../package.html">scaled(Span(150, Millis))</a></span></span></span>, <span name="interval">interval: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a> = <span class="symbol"><span class="name"><a href="../../package.html">scaled(Span(15, Millis))</a></span></span></span>)</span><span class="result"> extends <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.AbstractPatienceConfiguration@PatienceConfigextendsProductwithSerializable" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Configuration object for asynchronous constructs, such as those provided by traits <a href="Eventually.html"><code>Eventually</code></a> and
<a href="Waiters.html"><code>Waiters</code></a>.</a></a></p><div class="fullcomment"><div class="comment cmt"><p>Configuration object for asynchronous constructs, such as those provided by traits <a href="Eventually.html"><code>Eventually</code></a> and
<a href="Waiters.html"><code>Waiters</code></a>.</p><p>The default values for the parameters are:</p><p><table style="border-collapse: collapse; border: 1px solid black">
<tr><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Configuration Parameter</strong></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Default Value</strong></th></tr>
<tr>
<td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
<code>timeout</code>
</td>
<td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
<code>scaled(150 milliseconds)</code>
</td>
</tr>
<tr>
<td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
<code>interval</code>
</td>
<td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
<code>scaled(15 milliseconds)</code>
</td>
</tr>
</table>
</p></div><dl class="paramcmts block"><dt class="param">timeout</dt><dd class="cmt"><p>the maximum amount of time to wait for an asynchronous operation to complete before giving up and throwing
<code>TestFailedException</code>.</p></dd><dt class="param">interval</dt><dd class="cmt"><p>the amount of time to sleep between each check of the status of an asynchronous operation when polling</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="AbstractPatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.AbstractPatienceConfiguration">AbstractPatienceConfiguration</a></dd></dl></div>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@!=(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@##():Int" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@==(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@asInstanceOf[T0]:T0" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@clone():Object" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@equals(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@finalize():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@getClass():Class[_]" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@hashCode():Int" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="org.scalatest.concurrent.PatienceConfiguration#interval" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="interval(value:org.scalatest.time.Span):org.scalatest.concurrent.PatienceConfiguration.Interval"></a>
<a id="interval(Span):Interval"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">interval</span><span class="params">(<span name="value">value: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a></span>)</span><span class="result">: <a href="PatienceConfiguration$$Interval.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration.Interval">Interval</a></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@interval(value:org.scalatest.time.Span):org.scalatest.concurrent.PatienceConfiguration.Interval" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Returns an <code>Interval</code> configuration parameter containing the passed value, which
specifies the amount of time to sleep after a retry.</code></p><div class="fullcomment"><div class="comment cmt"><p>Returns an <code>Interval</code> configuration parameter containing the passed value, which
specifies the amount of time to sleep after a retry.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a></dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@isInstanceOf[T0]:Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@notify():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@notifyAll():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.concurrent.PatienceConfiguration#patienceConfig" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="patienceConfig:PatienceConfiguration.this.PatienceConfig"></a>
<a id="patienceConfig:PatienceConfig"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">implicit </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">patienceConfig</span><span class="result">: <a href="#PatienceConfigextendsProductwithSerializable" class="extmbr" name="org.scalatest.concurrent.AbstractPatienceConfiguration.PatienceConfig">PatienceConfig</a></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@patienceConfig:PatienceConfiguration.this.PatienceConfig" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Implicit <code>PatienceConfig</code> value providing default configuration values.</code></p><div class="fullcomment"><div class="comment cmt"><p>Implicit <code>PatienceConfig</code> value providing default configuration values.</p><p>To change the default configuration, override or hide this <code>def</code> with another implicit
<code>PatienceConfig</code> containing your desired default configuration values.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a> → <a href="AbstractPatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.AbstractPatienceConfiguration">AbstractPatienceConfiguration</a></dd></dl></div>
</li><li name="org.scalatest.concurrent.ScaledTimeSpans#scaled" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="scaled(span:org.scalatest.time.Span):org.scalatest.time.Span"></a>
<a id="scaled(Span):Span"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">scaled</span><span class="params">(<span name="span">span: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a></span>)</span><span class="result">: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@scaled(span:org.scalatest.time.Span):org.scalatest.time.Span" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Scales the passed <code>Span</code> by the <code>Double</code> factor returned
by <code>spanScaleFactor</code>.</code></code></code></p><div class="fullcomment"><div class="comment cmt"><p>Scales the passed <code>Span</code> by the <code>Double</code> factor returned
by <code>spanScaleFactor</code>.</p><p>The <code>Span</code> is scaled by invoking its <code>scaledBy</code> method,
thus this method has the same behavior:
The value returned by <code>spanScaleFactor</code> can be any positive number or zero,
including a fractional number. A number greater than one will scale the <code>Span</code>
up to a larger value. A fractional number will scale it down to a smaller value. A
factor of 1.0 will cause the exact same <code>Span</code> to be returned. A
factor of zero will cause <code>Span.ZeroLength</code> to be returned.
If overflow occurs, <code>Span.Max</code> will be returned. If underflow occurs,
<code>Span.ZeroLength</code> will be returned.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="ScaledTimeSpans.html" class="extype" name="org.scalatest.concurrent.ScaledTimeSpans">ScaledTimeSpans</a></dd><dt>Exceptions thrown</dt><dd><span class="cmt"><p><span class="extype" name="IllegalArgumentException"><code>IllegalArgumentException</code></span> if the value returned from <code>spanScaleFactor</code>
is less than zero</p></span></dd></dl></div>
</li><li name="org.scalatest.concurrent.ScaledTimeSpans#spanScaleFactor" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="spanScaleFactor:Double"></a>
<a id="spanScaleFactor:Double"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">spanScaleFactor</span><span class="result">: <span class="extype" name="scala.Double">Double</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@spanScaleFactor:Double" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">The factor by which the <code>scaled</code> method will scale <code>Span</code>s.</code></code></p><div class="fullcomment"><div class="comment cmt"><p>The factor by which the <code>scaled</code> method will scale <code>Span</code>s.</p><p>The default implementation of this method will return the <em>span scale factor</em> that
was specified for the run, or 1.0 if no factor was specified. For example, you can specify a span scale factor when invoking ScalaTest
via the command line by passing a <a href="../tools/Runner$.html#scalingTimeSpans"><code>-F</code> argument</a> to <a href="../tools/Runner$.html"><code>Runner</code></a>.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="ScaledTimeSpans.html" class="extype" name="org.scalatest.concurrent.ScaledTimeSpans">ScaledTimeSpans</a></dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@synchronized[T0](x$1:=>T0):T0" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.concurrent.PatienceConfiguration#timeout" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="timeout(value:org.scalatest.time.Span):org.scalatest.concurrent.PatienceConfiguration.Timeout"></a>
<a id="timeout(Span):Timeout"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">timeout</span><span class="params">(<span name="value">value: <a href="../time/Span.html" class="extype" name="org.scalatest.time.Span">Span</a></span>)</span><span class="result">: <a href="PatienceConfiguration$$Timeout.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration.Timeout">Timeout</a></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@timeout(value:org.scalatest.time.Span):org.scalatest.concurrent.PatienceConfiguration.Timeout" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Returns a <code>Timeout</code> configuration parameter containing the passed value, which
specifies the maximum amount to wait for an asynchronous operation to complete.</code></p><div class="fullcomment"><div class="comment cmt"><p>Returns a <code>Timeout</code> configuration parameter containing the passed value, which
specifies the maximum amount to wait for an asynchronous operation to complete.
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a></dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@toString():String" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@wait():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.concurrent.Conductors@wait(x$1:Long):Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="org.scalatest.concurrent.PatienceConfiguration">
<h3>Inherited from <a href="PatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.PatienceConfiguration">PatienceConfiguration</a></h3>
</div><div class="parent" name="org.scalatest.concurrent.AbstractPatienceConfiguration">
<h3>Inherited from <a href="AbstractPatienceConfiguration.html" class="extype" name="org.scalatest.concurrent.AbstractPatienceConfiguration">AbstractPatienceConfiguration</a></h3>
</div><div class="parent" name="org.scalatest.concurrent.ScaledTimeSpans">
<h3>Inherited from <a href="ScaledTimeSpans.html" class="extype" name="org.scalatest.concurrent.ScaledTimeSpans">ScaledTimeSpans</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
|
scalatest/scalatest-website
|
public/scaladoc/3.0.0/org/scalatest/concurrent/Conductors.html
|
HTML
|
apache-2.0
| 68,108
|
/*
* Copyright 2010-2017 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.
*/
#pragma once
#include <aws/cloudhsmv2/CloudHSMV2_EXPORTS.h>
#include <aws/cloudhsmv2/CloudHSMV2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
namespace CloudHSMV2
{
namespace Model
{
/**
*/
class AWS_CLOUDHSMV2_API UntagResourceRequest : public CloudHSMV2Request
{
public:
UntagResourceRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UntagResource"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline const Aws::String& GetResourceId() const{ return m_resourceId; }
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline bool ResourceIdHasBeenSet() const { return m_resourceIdHasBeenSet; }
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline void SetResourceId(const Aws::String& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline void SetResourceId(Aws::String&& value) { m_resourceIdHasBeenSet = true; m_resourceId = std::move(value); }
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline void SetResourceId(const char* value) { m_resourceIdHasBeenSet = true; m_resourceId.assign(value); }
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline UntagResourceRequest& WithResourceId(const Aws::String& value) { SetResourceId(value); return *this;}
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline UntagResourceRequest& WithResourceId(Aws::String&& value) { SetResourceId(std::move(value)); return *this;}
/**
* <p>The cluster identifier (ID) for the cluster whose tags you are removing. To
* find the cluster ID, use <a>DescribeClusters</a>.</p>
*/
inline UntagResourceRequest& WithResourceId(const char* value) { SetResourceId(value); return *this;}
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline const Aws::Vector<Aws::String>& GetTagKeyList() const{ return m_tagKeyList; }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline bool TagKeyListHasBeenSet() const { return m_tagKeyListHasBeenSet; }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline void SetTagKeyList(const Aws::Vector<Aws::String>& value) { m_tagKeyListHasBeenSet = true; m_tagKeyList = value; }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline void SetTagKeyList(Aws::Vector<Aws::String>&& value) { m_tagKeyListHasBeenSet = true; m_tagKeyList = std::move(value); }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline UntagResourceRequest& WithTagKeyList(const Aws::Vector<Aws::String>& value) { SetTagKeyList(value); return *this;}
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline UntagResourceRequest& WithTagKeyList(Aws::Vector<Aws::String>&& value) { SetTagKeyList(std::move(value)); return *this;}
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline UntagResourceRequest& AddTagKeyList(const Aws::String& value) { m_tagKeyListHasBeenSet = true; m_tagKeyList.push_back(value); return *this; }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline UntagResourceRequest& AddTagKeyList(Aws::String&& value) { m_tagKeyListHasBeenSet = true; m_tagKeyList.push_back(std::move(value)); return *this; }
/**
* <p>A list of one or more tag keys for the tags that you are removing. Specify
* only the tag keys, not the tag values.</p>
*/
inline UntagResourceRequest& AddTagKeyList(const char* value) { m_tagKeyListHasBeenSet = true; m_tagKeyList.push_back(value); return *this; }
private:
Aws::String m_resourceId;
bool m_resourceIdHasBeenSet;
Aws::Vector<Aws::String> m_tagKeyList;
bool m_tagKeyListHasBeenSet;
};
} // namespace Model
} // namespace CloudHSMV2
} // namespace Aws
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-cloudhsmv2/include/aws/cloudhsmv2/model/UntagResourceRequest.h
|
C
|
apache-2.0
| 6,455
|
# Epidendrum macrothyrsis F.Lehm. & Kraenzl. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Epidendrum/Epidendrum macrothyrsis/README.md
|
Markdown
|
apache-2.0
| 192
|
# Euplassa itatiaiae Sleumer SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Euplassa/Euplassa itatiaiae/README.md
|
Markdown
|
apache-2.0
| 176
|
# Picris scaberrima Ten. SPECIES
#### Status
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Picris/Picris scaberrima/README.md
|
Markdown
|
apache-2.0
| 159
|
# Trichosalpinx rotundata (C.Schweinf.) Dressler SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Pleurothallis rotundata C.Schweinf.
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Trichosalpinx/Trichosalpinx rotundata/README.md
|
Markdown
|
apache-2.0
| 235
|
# Enydra paludosa (Reinw. ex Reinw.) DC. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Enydra fluctuans/ Syn. Enydra paludosa/README.md
|
Markdown
|
apache-2.0
| 195
|
# Polypodium beccarii Alderw. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Polypodium/Polypodium beccarii/README.md
|
Markdown
|
apache-2.0
| 177
|
# Barkhausia glandulosa var. glandulosa VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Crepis/Crepis foetida/ Syn. Barkhausia glandulosa glandulosa/README.md
|
Markdown
|
apache-2.0
| 194
|
# Libanotis lehmanniana Bunge SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Libanotis/Libanotis lehmanniana/README.md
|
Markdown
|
apache-2.0
| 185
|
# Clandestinotrema GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Ostropales/Graphidaceae/Clandestinotrema/README.md
|
Markdown
|
apache-2.0
| 172
|
# Asterina cansjericola var. indica Hosag., N.P. Balakr. & Goos VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 59: 170 (1996)
#### Original name
Asterina cansjericola var. indica Hosag., N.P. Balakr. & Goos
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Asterinaceae/Asterina/Asterina cansjericola/Asterina cansjericola indica/README.md
|
Markdown
|
apache-2.0
| 271
|
# Boletellus coccineus var. crassotunicatus (Singer) Singer, 1992 VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Beih. Nova Hedwigia 105: 7 (1992)
#### Original name
Boletellus ananas var. crassotunicatus Singer, 1983
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Boletales/Boletaceae/Boletellus/Boletellus ananas/ Syn. Boletellus coccineus crassotunicatus/README.md
|
Markdown
|
apache-2.0
| 296
|
# Cineraria senecifolia Poir. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cineraria/Cineraria senecifolia/README.md
|
Markdown
|
apache-2.0
| 177
|
/*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.example.web.applied.ex50;
import java.io.Serializable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.context.MessageSourceResolvable;
import cherry.foundation.logicalerror.LogicalErrorUtil;
@Getter
@Setter
@EqualsAndHashCode
@ToString
public abstract class AppliedEx51FormBase implements Serializable {
private static final long serialVersionUID = 1L;
@cherry.foundation.type.format.CustomDateTimeFormat()
private org.joda.time.LocalDate dt;
@cherry.foundation.type.format.CustomDateTimeFormat()
private org.joda.time.LocalTime tm;
@cherry.foundation.type.format.CustomDateTimeFormat()
private org.joda.time.LocalDateTime dtm;
@Getter
public enum Prop {
Dt("dt", "appliedEx51Form.dt"), //
Tm("tm", "appliedEx51Form.tm"), //
Dtm("dtm", "appliedEx51Form.dtm"), //
DUMMY("dummy", "dummy");
private final String name;
private final String nameWithForm;
private Prop(String name, String nameWithForm) {
this.name = name;
this.nameWithForm = nameWithForm;
}
public MessageSourceResolvable resolve() {
return LogicalErrorUtil.resolve(nameWithForm);
}
}
}
|
agwlvssainokuni/springapp
|
example-web/src/main/java/cherry/example/web/applied/ex50/AppliedEx51FormBase.java
|
Java
|
apache-2.0
| 1,870
|
/*
* Copyright 2012 AMG.lab, a Bull Group Company
*
* 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.xlcloud.service.heat.parsers;
import java.util.Iterator;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.xlcloud.service.heat.template.Parameter;
import org.xlcloud.service.heat.template.Parameters;
/**
* Implementation of {@link JSONParser} for {@link Parameters}.
* @author Konrad Król, AMG.net
*/
public class ParametersParser implements JSONParser<Parameters> {
private ParameterParser parameterParser = new ParameterParser();
/** {@inheritDoc}
* @throws JSONException */
@Override
public Parameters fromJSON(JSONObject json) throws JSONException {
Parameters parameters = new Parameters();
@SuppressWarnings( "unchecked" )
Iterator<String> keysIterator = (Iterator<String>) json.keys();
while(keysIterator.hasNext()) {
String parameterName = keysIterator.next();
if(StringUtils.isBlank(parameterName)) { throw new JSONException("Parameter name can not be empty."); }
JSONObject parameterJson = json.getJSONObject(parameterName);
Parameter parameter = parameterParser.fromJSON(parameterJson);
parameter.setName(parameterName);
parameters.getParameter().add(parameter);
}
return parameters;
}
/** {@inheritDoc} */
@Override
public JSONObject fromPojo(Parameters pojo) throws JSONException {
JSONObject jsonObject = new JSONObject();
for(Parameter parameter : pojo.getParameter()) {
jsonObject.put(parameter.getName(), parameterParser.fromPojo(parameter));
}
return jsonObject;
}
}
|
ow2-xlcloud/vcms
|
heat-template-model/src/main/java/org/xlcloud/service/heat/parsers/ParametersParser.java
|
Java
|
apache-2.0
| 2,369
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.