repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
sin-ivan/AdiumPipeEvent | adium/Source/AIXMLAppender.h | /*
* AIXMLAppender.h
*
* Created by <NAME> on 12/23/05.
*
* This class is explicitly released under the BSD license with the following modification:
* It may be used without reproduction of its copyright notice within The Adium Project.
*
* This class was created for use in the Adium project, which is released under the GPL.
* The release of this specific class (AIXMLAppender) under BSD in no way changes the licensing of any other portion
* of the Adium project.
*
****
Copyright (c) 2005, 2006 <NAME>
Copyright (c) 2008 The Adium Team
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of Adium nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@class AIAppendXMLOperation, AIXMLElement;
@interface AIXMLAppender : NSObject {
NSFileHandle *file;
NSString *path;
AIXMLElement *rootElement;
BOOL initialized;
}
+ (id)documentWithPath:(NSString *)path rootElement:(AIXMLElement *)root;
- (id)initWithPath:(NSString *)path rootElement:(AIXMLElement *)elm;
@property (readonly, copy, nonatomic) NSString *path;
- (void)appendElement:(AIXMLElement *)element;
@end
|
sillsdev/xlingpaper | javasrc/XLingPapExtensions/src/xlingpaper/xxe/ConvertCollectionToCitation.java | <gh_stars>0
package xlingpaper.xxe;
import com.xmlmind.guiutil.Alert;
import com.xmlmind.xml.doc.Document;
import com.xmlmind.xml.doc.Element;
import com.xmlmind.xml.doc.Node;
import com.xmlmind.xml.doc.Text;
import com.xmlmind.xml.name.Name;
import com.xmlmind.xml.name.Namespace;
import com.xmlmind.xml.validate.Data;
import com.xmlmind.xml.validate.IDDataTypeImpl;
import com.xmlmind.xml.validate.IdEntry;
import com.xmlmind.xmledit.edit.ElementEditor;
import com.xmlmind.xmledit.edit.MarkManager;
import com.xmlmind.xmledit.view.DocumentView;
import com.xmlmind.xmleditapp.cmd.helper.Prompt;
public class ConvertCollectionToCitation extends ConvertCollectionOrProceedingsToCitation{
public boolean prepare(DocumentView docView, String parameter, int x, int y) {
MarkManager markManager = docView.getMarkManager();
if (markManager == null) {
return false;
}
Element editedElement = docView.getSelectedElement(/* implicit */true);
if (editedElement == null) {
return false;
}
docView.getElementEditor().editElement(editedElement);
return true;
}
protected Object doExecute(DocumentView docView, String parameter, int x, int y) {
ElementEditor elementEditor = docView.getElementEditor();
Element editedElement = elementEditor.getEditedElement();
if (editedElement == null) {
return null;
}
try {
Element collection = editedElement;
if (collection == null) {
return null;
}
if (!"collection".equals(collection.name().localPart)) {
return null;
}
Element refWork = collection.getParentElement();
if (refWork == null)
return null;
Element refAuthor = refWork.getParentElement();
if (refAuthor == null) {
return null;
}
Element references = refAuthor.getParentElement();
if (references == null) {
return null;
}
Element newCollection = new Element(collection.name());
Element newRefAuthor = new Element(Name.get(Namespace.NONE, "refAuthor"));
Element newRefWork = new Element(refWork.name());
String sDate = copyRefDate(refWork, newRefWork);
Element newBook = new Element(Name.get(Namespace.NONE, "book"));
Element newCollCitation = new Element(Name.get(Namespace.NONE, "collCitation"));
newCollection.appendChild(newCollCitation);
String citeName = null;
boolean fCollEdPlural = true;
Element newRefTitle = null;
Element[] children = collection.getChildElements();
for (Element e : children) {
if ("url".equals(e.name().localPart)) {
newCollection.appendChild(e);
} else if ("dateAccessed".equals(e.name().localPart)) {
newCollection.appendChild(e);
} else if ("iso639-3code".equals(e.name().localPart)) {
newCollection.appendChild(e);
} else if ("comment".equals(e.name().localPart)) {
newCollection.appendChild(e);
} else if ("collEd".equals(e.name().localPart)) {
fCollEdPlural = checkEditorPlural(fCollEdPlural, e);
citeName = getAndSetCiteName(newRefAuthor, e);
} else if ("collEdInitials".equals(e.name().localPart)) {
newRefAuthor.appendChild(copyTextIntoNewElement(e, "refAuthorInitials"));
} else if ("collTitle".equals(e.name().localPart)) {
newRefTitle = copyTextIntoNewElement(e, "refTitle");
newRefWork.appendChild(newRefTitle);
} else if ("collTitleLowerCase".equals(e.name().localPart)) {
newRefWork.appendChild(copyTextIntoNewElement(e, "refTitleLowerCase"));
} else if ("edition".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "edition"));
} else if ("collVol".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "bVol"));
} else if ("seriesEd".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "seriesEd"));
} else if ("seriesEdInitials".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "seriesEdInitials"));
} else if ("series".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "series"));
} else if ("location".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "location"));
} else if ("publisher".equals(e.name().localPart)) {
newBook.appendChild(copyTextIntoNewElement(e, "publisher"));
}
}
setAuthorRole(newRefWork, newRefTitle, fCollEdPlural);
String newRefWorkId = "r" + citeName + sDate + "CollectionCitation";
boolean result = askUserForIdAndSetIt(docView, newRefWorkId, newRefWork, newCollCitation, x, y);
if (!result) {
// abort!
return null;
}
Document doc = docView.getDocument();
if (doc == null) {
return null;
}
doc.beginEdit();
try {
refWork.replaceChild(collection, newCollection);
} catch (Exception e) {
// TODO: handle exception
// can get null exception here if the original gloss element was
// selected; not sure why; ignore it
}
newRefWork.appendChild(newBook);
newRefAuthor.appendChild(newRefWork);
references.insertChild(refAuthor, newRefAuthor);
doc.endEdit();
return null;
} catch (Exception e) {
Alert.showError(docView.getPanel(), "doExecute: Exception caught:" + e.getMessage());
return e.getMessage();
}
}
}
|
melkishengue/cpachecker | src/org/sosy_lab/cpachecker/cpa/statistics/StatisticsDataProvider.java | <filename>src/org/sosy_lab/cpachecker/cpa/statistics/StatisticsDataProvider.java<gh_stars>1-10
/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 <NAME>
* 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.
* 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.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.statistics;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
/**
* Represents Data of an StatisticsProvider.
* The data provider takes care of tracking the current value, calculating the next value
* and merging paths.
* All instances of this interface should be immutable.
* (Create new StatisticsDataProvider instances for new data)
*/
public interface StatisticsDataProvider {
Object getPropertyValue();
StatisticsDataProvider calculateNext(CFAEdge node);
StatisticsDataProvider mergePath(StatisticsDataProvider other);
}
|
beardedtim/bambi | modules/T.js | <gh_stars>1-10
const T = () => true;
module.exports = T;
|
JeffreyThiessen/staramr | staramr/tests/unit/blast/pointfinder/test_PointfinderDatabaseInfo.py | <filename>staramr/tests/unit/blast/pointfinder/test_PointfinderDatabaseInfo.py
import unittest
import pandas as pd
from staramr.blast.pointfinder.PointfinderDatabaseInfo import PointfinderDatabaseInfo
from staramr.blast.results.pointfinder.codon.CodonMutationPosition import CodonMutationPosition
class PointfinderDatabaseInfoTest(unittest.TestCase):
def setUp(self):
pandas_pointfinder_table = pd.DataFrame([
['gyrA', 'gyrA', 1, 1, 'ATC', 'I', 'F', 'Quinolones', 15848289],
['gyrA', 'gyrA', 1, 2, 'GAT', 'D', 'N,H', 'Quinolones', 15848289],
],
columns=(
'#Gene_ID', 'Gene_name', 'No of mutations needed', 'Codon_pos', 'Ref_nuc', 'Ref_codon', 'Res_codon',
'Resistance', 'PMID'))
self.database = PointfinderDatabaseInfo.from_pandas_table(pandas_pointfinder_table)
mutation_position = 0
amr_gene_string = "ATCGATCGA"
genome_string = "TTCGATCGA"
amr_gene_start = 1
self.mutation1 = CodonMutationPosition(mutation_position, amr_gene_string, genome_string, amr_gene_start)
mutation_position = 3
amr_gene_string = "ATCGATCGA"
genome_string = "ATCAATCGA"
amr_gene_start = 1
self.mutation2 = CodonMutationPosition(mutation_position, amr_gene_string, genome_string, amr_gene_start)
mutation_position = 8
amr_gene_string = "ATCGATCGA"
genome_string = "ATCGATCGT"
amr_gene_start = 1
self.mutation_missing = CodonMutationPosition(mutation_position, amr_gene_string, genome_string, amr_gene_start)
def testGetResistanceCodons1Mutation1Codon(self):
resistance_mutations = self.database.get_resistance_codons('gyrA', [self.mutation1])
self.assertEqual(resistance_mutations, [self.mutation1], "Did not pick up correct mutations")
def testGetResistanceCodons1Mutation2Codons(self):
resistance_mutations = self.database.get_resistance_codons('gyrA', [self.mutation2])
self.assertEqual(resistance_mutations, [self.mutation2], "Did not pick up correct mutations")
def testGetResistanceCodons2Mutation2Codons(self):
resistance_mutations = self.database.get_resistance_codons('gyrA', [self.mutation1, self.mutation2])
self.assertEqual(resistance_mutations, [self.mutation1, self.mutation2], "Did not pick up correct mutations")
def testGetResistanceCodons2Mutation1Missing(self):
resistance_mutations = self.database.get_resistance_codons('gyrA', [self.mutation1, self.mutation_missing])
self.assertEqual(resistance_mutations, [self.mutation1], "Did not pick up correct mutations")
def testGetResistanceCodons1Mutation1Missing(self):
resistance_mutations = self.database.get_resistance_codons('gyrA', [self.mutation_missing])
self.assertEqual(resistance_mutations, [], "Did not pick up correct mutations")
def testGetResistanceCodons1MutationAANotMatch(self):
mutation_position = 3
amr_gene_string = "ATCGATCGA"
genome_string = "ATCGAACGA"
amr_gene_start = 1
mutation_aa_not_match = CodonMutationPosition(mutation_position, amr_gene_string, genome_string, amr_gene_start)
resistance_mutations = self.database.get_resistance_codons('gyrA', [mutation_aa_not_match])
self.assertEqual(resistance_mutations, [], "Did not pick up correct mutations")
def testGetResistanceCodons1MutationStartCodon(self):
mutation_position = 0
amr_gene_string = "ATCGATCGA"
genome_string = "ATGGATCGA"
amr_gene_start = 1
mutation_start_methionine = CodonMutationPosition(mutation_position, amr_gene_string, genome_string,
amr_gene_start)
resistance_mutations = self.database.get_resistance_codons('gyrA', [mutation_start_methionine])
self.assertEqual(resistance_mutations, [], "Did not pick up correct mutations")
def testGetResistanceCodons1MutationStopCodon(self):
mutation_position = 2
amr_gene_string = "TACGATCGA"
genome_string = "TAAGATCGA"
amr_gene_start = 1
mutation_stop = CodonMutationPosition(mutation_position, amr_gene_string, genome_string, amr_gene_start)
resistance_mutations = self.database.get_resistance_codons('gyrA', [mutation_stop])
self.assertEqual(resistance_mutations, [], "Did not pick up correct mutations")
def testGetResfinderPhenotype(self):
phenotype = self.database.get_phenotype('gyrA', self.mutation1)
self.assertEqual(phenotype, 'Quinolones')
def testGetResfinderPhenotypeMissingFail(self):
self.assertRaises(Exception, self.database.get_phenotype, 'gyrA', self.mutation_missing)
|
cheminfo/nmredata | src/__tests__/processContent.test.js | <reponame>cheminfo/nmredata
import { processContent } from '../processContent';
describe('processContent testing', () => {
let dataLines = [
'Larmor=500.13300078',
'CorrType=HMBC',
'Pulseprogram=hmbcetgpl3nd',
'Spectrum_Location=file:dj_ca_2017_ernestin_EN4/15/pdata/1/',
'3/H1',
];
/*eslint-disable camelcase*/
let shouldBe = [
{ larmor: '500.13300078' },
{ corrtype: 'HMBC' },
{ pulseprogram: 'hmbcetgpl3nd' },
{ spectrum_location: 'file:dj_ca_2017_ernestin_EN4/15/pdata/1/' },
{ delta: { y: ['3'], x: ['h1'] } },
];
/*eslint-enable camelcase*/
it('process 2D data lines', () => {
for (let i = 0; i < shouldBe.length; i++) {
let result = processContent(dataLines[i], {
tag: '2D_13C_NJ_1H',
});
expect(result).toStrictEqual(shouldBe[i]);
}
});
});
|
kniz/wrd | mod/wrd/builtin/primitive/wVoid.cpp | #include "wVoid.hpp"
#include "../../ast/mgd/defaultCtor.hpp"
#include "../../ast/mgd/defaultCopyCtor.hpp"
namespace wrd {
WRD_DEF_ME(wVoid)
wbool me::wVoidType::isImmutable() const { return true; }
const ases& me::wVoidType::_getImpliAses() const {
static ases inner;
return inner;
}
me::wVoid() {}
me& me::singletone() {
static me inner;
return inner;
}
dumScope* me::_onMakeCtors() const {
scope scapegoat;
scapegoat.add(obj::CTOR_NAME, new defaultCtor(getType()));
scapegoat.add(obj::CTOR_NAME, new defaultCopyCtor(getType()));
return new dumScope(scapegoat);
}
}
|
asanoviskhak/Outtalent | Leetcode/1175. Prime Arrangements/solution1.py | <reponame>asanoviskhak/Outtalent<filename>Leetcode/1175. Prime Arrangements/solution1.py<gh_stars>10-100
from math import factorial
class Solution:
def numPrimeArrangements(self, n: int) -> int:
primes = [True] * (n + 1)
for prime in range(2, int(n ** 0.5) + 1):
if not primes[prime]: continue
for composite in range(prime * prime, n + 1, prime): primes[composite] = False
cnt = sum(primes[2:])
return factorial(cnt) * factorial(n - cnt) % (10 ** 9 + 7)
|
dmitryryintel/cm-compiler | test/external_contribution/CopyPipelineHigh6/include/CmdParser.h | <reponame>dmitryryintel/cm-compiler
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <gflags/gflags.h>
// @brief message for help argument
static const char help_message[] = "Print a usage message.";
// @brief message for input image argument
static const char input_image_message[] = "Path to an 24bit .bmp RGB image. Default value: nest.bmp";
// @brief message for output image argument
static const char output_image_message[] = "Path to save 1bpp CMYK output image. Default: no output file";
// @brief message for lightness setting
static const char lightness_message[] = "Lightness control where ranges -3 to 3. Default value: 0";
// @brief message for contrast setting
static const char contrast_message[] = "Contrast control where ranges -2 to 2. Default value: 0.";
// @brief message for max-frames
static const char max_frames_message[] = "Maximum number of frames to run.";
// @brief message for halftone path
static const char halftone_message[] = "Halftone path. Default=no";
// @brief message for error diffusion path
static const char ed_message[] = "Error diffusion path. Default=yes";
// @brief Define flag for showing help message
DEFINE_bool(h, false, help_message);
// @brief Define parameter for input image file
DEFINE_string(i, "nest.bmp", input_image_message);
// @brief Define parameter for output image file
DEFINE_string(o, "", output_image_message);
// @brief Define parameter for brightness control
// Default is 0
DEFINE_int32(lightness, 0, lightness_message);
// @brief Define parameter for contrast control
// Default is 0
DEFINE_int32(contrast, 0, contrast_message);
// @brief Define parameter for maximum number of frames to run
// Default is 10
DEFINE_int32(maxframes, 10, max_frames_message);
// @brief Define flag for halftone path
DEFINE_bool(halftonepath, false, halftone_message);
// @brief Define flag for error diffusion path
DEFINE_bool(edpath, true, ed_message);
static void showUsage() {
std::cout << std::endl;
std::cout << "hw_x64.CopyPipelineHigh6 [OPTION]" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << std::endl;
std::cout << " -h " << help_message << std::endl;
std::cout << " -i <filename> " << input_image_message << std::endl;
std::cout << " -o <filename> " << output_image_message << std::endl;
std::cout << " --lightness <integer> " << lightness_message << std::endl;
std::cout << " --contrast <integer> " << contrast_message << std::endl;
std::cout << " --maxframes <integer> " << max_frames_message << std::endl;
std::cout << " --halftonepath " << halftone_message << std::endl;
std::cout << " --edpath " << ed_message << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
bool ParseCommandLine(int argc, char *argv[])
{
gflags::ParseCommandLineNonHelpFlags(&argc, &argv, true);
if (FLAGS_h) {
showUsage();
return false;
}
if (FLAGS_i.empty()) {
throw std::logic_error("Parameter -i is not set");
}
if ((!FLAGS_halftonepath) && (!FLAGS_edpath))
{
throw std::logic_error("Select either halftone path or error diffusion path");
}
return true;
}
|
laohubuzaijia/fbthrift | thrift/compiler/test/fixtures/complex-union/gen-swift/test/fixtures/complex_union/Val.java | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package test.fixtures.complex_union;
import com.facebook.swift.codec.*;
import com.facebook.swift.codec.ThriftField.Requiredness;
import com.facebook.swift.codec.ThriftField.Recursiveness;
import com.google.common.collect.*;
import java.util.*;
import org.apache.thrift.*;
import org.apache.thrift.async.*;
import org.apache.thrift.meta_data.*;
import org.apache.thrift.server.*;
import org.apache.thrift.transport.*;
import org.apache.thrift.protocol.*;
import org.apache.thrift.meta_data.FieldValueMetaData;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.MoreObjects.ToStringHelper;
@SwiftGenerated
@com.facebook.swift.codec.ThriftStruct(value="Val", builder=Val.Builder.class)
public final class Val {
@ThriftConstructor
public Val(
@com.facebook.swift.codec.ThriftField(value=1, name="strVal", requiredness=Requiredness.NONE) final String strVal,
@com.facebook.swift.codec.ThriftField(value=2, name="intVal", requiredness=Requiredness.NONE) final int intVal,
@com.facebook.swift.codec.ThriftField(value=9, name="typedefValue", requiredness=Requiredness.NONE) final Map<Short, String> typedefValue
) {
this.strVal = strVal;
this.intVal = intVal;
this.typedefValue = typedefValue;
}
@ThriftConstructor
protected Val() {
this.strVal = null;
this.intVal = 0;
this.typedefValue = null;
}
public static class Builder {
private String strVal = null;
private int intVal = 0;
private Map<Short, String> typedefValue = null;
@com.facebook.swift.codec.ThriftField(value=1, name="strVal", requiredness=Requiredness.NONE)
public Builder setStrVal(String strVal) {
this.strVal = strVal;
return this;
}
public String getStrVal() { return strVal; }
@com.facebook.swift.codec.ThriftField(value=2, name="intVal", requiredness=Requiredness.NONE)
public Builder setIntVal(int intVal) {
this.intVal = intVal;
return this;
}
public int getIntVal() { return intVal; }
@com.facebook.swift.codec.ThriftField(value=9, name="typedefValue", requiredness=Requiredness.NONE)
public Builder setTypedefValue(Map<Short, String> typedefValue) {
this.typedefValue = typedefValue;
return this;
}
public Map<Short, String> getTypedefValue() { return typedefValue; }
public Builder() { }
public Builder(Val other) {
this.strVal = other.strVal;
this.intVal = other.intVal;
this.typedefValue = other.typedefValue;
}
@ThriftConstructor
public Val build() {
Val result = new Val (
this.strVal,
this.intVal,
this.typedefValue
);
return result;
}
}
public static final Map<String, Integer> NAMES_TO_IDS = new HashMap();
public static final Map<Integer, TField> FIELD_METADATA = new HashMap<>();
private static final TStruct STRUCT_DESC = new TStruct("Val");
private final String strVal;
public static final int _STRVAL = 1;
private static final TField STR_VAL_FIELD_DESC = new TField("strVal", TType.STRING, (short)1);
private final int intVal;
public static final int _INTVAL = 2;
private static final TField INT_VAL_FIELD_DESC = new TField("intVal", TType.I32, (short)2);
private final Map<Short, String> typedefValue;
public static final int _TYPEDEFVALUE = 9;
private static final TField TYPEDEF_VALUE_FIELD_DESC = new TField("typedefValue", TType.MAP, (short)9);
static {
NAMES_TO_IDS.put("strVal", 1);
FIELD_METADATA.put(1, STR_VAL_FIELD_DESC);
NAMES_TO_IDS.put("intVal", 2);
FIELD_METADATA.put(2, INT_VAL_FIELD_DESC);
NAMES_TO_IDS.put("typedefValue", 9);
FIELD_METADATA.put(9, TYPEDEF_VALUE_FIELD_DESC);
}
@com.facebook.swift.codec.ThriftField(value=1, name="strVal", requiredness=Requiredness.NONE)
public String getStrVal() { return strVal; }
@com.facebook.swift.codec.ThriftField(value=2, name="intVal", requiredness=Requiredness.NONE)
public int getIntVal() { return intVal; }
@com.facebook.swift.codec.ThriftField(value=9, name="typedefValue", requiredness=Requiredness.NONE)
public Map<Short, String> getTypedefValue() { return typedefValue; }
@java.lang.Override
public String toString() {
ToStringHelper helper = toStringHelper(this);
helper.add("strVal", strVal);
helper.add("intVal", intVal);
helper.add("typedefValue", typedefValue);
return helper.toString();
}
@java.lang.Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Val other = (Val)o;
return
Objects.equals(strVal, other.strVal) &&
Objects.equals(intVal, other.intVal) &&
Objects.equals(typedefValue, other.typedefValue) &&
true;
}
@java.lang.Override
public int hashCode() {
return Arrays.deepHashCode(new Object[] {
strVal,
intVal,
typedefValue
});
}
public static Val read0(TProtocol oprot) throws TException {
TField __field;
oprot.readStructBegin(Val.NAMES_TO_IDS, Val.FIELD_METADATA);
Val.Builder builder = new Val.Builder();
while (true) {
__field = oprot.readFieldBegin();
if (__field.type == TType.STOP) { break; }
switch (__field.id) {
case _STRVAL:
if (__field.type == TType.STRING) {
String strVal = oprot.readString();
builder.setStrVal(strVal);
} else {
TProtocolUtil.skip(oprot, __field.type);
}
break;
case _INTVAL:
if (__field.type == TType.I32) {
int intVal = oprot.readI32();
builder.setIntVal(intVal);
} else {
TProtocolUtil.skip(oprot, __field.type);
}
break;
case _TYPEDEFVALUE:
if (__field.type == TType.MAP) {
Map<Short, String> typedefValue;
{
TMap _map = oprot.readMapBegin();
typedefValue = new HashMap<Short, String>(Math.max(0, _map.size));
for (int _i = 0; (_map.size < 0) ? oprot.peekMap() : (_i < _map.size); _i++) {
short _key1 = oprot.readI16();
String _value1 = oprot.readString();
typedefValue.put(_key1, _value1);
}
}
oprot.readMapEnd();
builder.setTypedefValue(typedefValue);
} else {
TProtocolUtil.skip(oprot, __field.type);
}
break;
default:
TProtocolUtil.skip(oprot, __field.type);
break;
}
oprot.readFieldEnd();
}
oprot.readStructEnd();
return builder.build();
}
public void write0(TProtocol oprot) throws TException {
oprot.writeStructBegin(STRUCT_DESC);
if (this.strVal != null) {
oprot.writeFieldBegin(STR_VAL_FIELD_DESC);
oprot.writeString(this.strVal);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(INT_VAL_FIELD_DESC);
oprot.writeI32(this.intVal);
oprot.writeFieldEnd();
if (this.typedefValue != null) {
oprot.writeFieldBegin(TYPEDEF_VALUE_FIELD_DESC);
Map<Short, String> _iter0 = this.typedefValue;
oprot.writeMapBegin(new TMap(TType.I16, TType.STRING, _iter0.size()));
for (Map.Entry<Short, String> _iter1 : _iter0.entrySet()) {
oprot.writeI16(_iter1.getKey());
oprot.writeString(_iter1.getValue());
}
oprot.writeMapEnd();
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
private static class _ValLazy {
private static final Val _DEFAULT = new Val.Builder().build();
}
public static Val defaultInstance() {
return _ValLazy._DEFAULT;
}
}
|
andela-jejezie/peopleProject | node_modules/karma/node_modules/http-proxy/examples/balancer/simple-balancer.js | var httpProxy = require('../../lib/node-http-proxy');
//
// A simple round-robin load balancing strategy.
//
// First, list the servers you want to use in your rotation.
//
var addresses = [
{
host: 'ws1.0.0.0',
port: 80
},
{
host: 'ws2.0.0.0',
port: 80
}
];
httpProxy.createServer(function (req, res, proxy) {
//
// On each request, get the first location from the list...
//
var target = addresses.shift();
//
// ...then proxy to the server whose 'turn' it is...
//
console.log('balancing request to: ', target);
proxy.proxyRequest(req, res, target);
//
// ...and then the server you just used becomes the last item in the list.
//
addresses.push(target);
}).listen(8000);
// Rinse; repeat; enjoy. |
jhouser/houseoffun | frontend/src/actions/games.js | import { RSAA } from 'redux-api-middleware';
import {withAuth} from "../util/api";
export const GAME_LIST_REQUEST = '@@games/GAME_LIST_REQUEST';
export const GAME_LIST_SUCCESS = '@@games/GAME_LIST_SUCCESS';
export const GAME_LIST_FAILURE = '@@games/GAME_LIST_FAILURE';
export const GAME_DETAIL_REQUEST = '@@games/GAME_DETAIL_REQUEST';
export const GAME_DETAIL_SUCCESS = '@@games/GAME_DETAIL_SUCCESS';
export const GAME_DETAIL_FAILURE = '@@games/GAME_DETAIL_FAILURE';
export const GAME_CREATE_REQUEST = '@@games/GAME_CREATE_REQUEST';
export const GAME_CREATE_SUCCESS = '@@games/GAME_CREATE_SUCCESS';
export const GAME_CREATE_FAILURE = '@@games/GAME_CREATE_FAILURE';
export const gameList = () => ({
[RSAA]: {
endpoint: process.env.REACT_APP_API_ENDPOINT + '/api/games/',
method: 'GET',
headers: withAuth({ 'Content-Type': 'application/json' }),
types: [
GAME_LIST_REQUEST, GAME_LIST_SUCCESS, GAME_LIST_FAILURE
]
}
});
export const gameDetail = (id) => ({
[RSAA]: {
endpoint: process.env.REACT_APP_API_ENDPOINT + '/api/games/' + id + '/',
method: 'GET',
headers: withAuth({ 'Content-Type': 'application/json' }),
types: [
GAME_DETAIL_REQUEST, GAME_DETAIL_SUCCESS, GAME_DETAIL_FAILURE
]
}
});
export const gameCreate = (data) => ({
[RSAA]: {
endpoint: process.env.REACT_APP_API_ENDPOINT + '/api/games/',
method: 'POST',
body: JSON.stringify(data),
headers: withAuth({ 'Content-Type': 'application/json' }),
types: [
GAME_CREATE_REQUEST,
GAME_CREATE_SUCCESS,
GAME_CREATE_FAILURE
]
}
}); |
voidFunctionReturn0/TeamHome | Client(AndroidStrudio Project)/Woori2/library/src/test/java/com/github/sundeepk/compactcalendarview/CompactCalendarControllerTest.java | package com.github.sundeepk.compactcalendarview;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.OverScroller;
import com.github.sundeepk.compactcalendarview.domain.Event;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompactCalendarControllerTest {
@Mock private Paint paint;
@Mock private OverScroller overScroller;
@Mock private Canvas canvas;
@Mock private Rect rect;
@Mock private Calendar calendar;
@Mock private MotionEvent motionEvent;
@Mock private VelocityTracker velocityTracker;
private static final String[] dayColumnNames = {"M", "T", "W", "T", "F", "S", "S"};
CompactCalendarController underTest;
@Before
public void setUp(){
when(velocityTracker.getXVelocity()).thenReturn(-200f);
underTest = new CompactCalendarController(paint, overScroller, rect, null, null, 0, 0, 0, velocityTracker, 0);
}
@Test(expected=IllegalArgumentException.class)
public void testItThrowsWhenDayColumnsIsNotLengthSeven(){
String[] dayNames = {"Mon", "Tue", "Wed", "Thur", "Fri"};
underTest.setDayColumnNames(dayNames);
}
@Test
public void testManualScrollAndGestureScrollPlayNicelyTogether(){
//Set width of view so that scrolling will return a correct value
underTest.onMeasure(720, 1080, 0, 0);
Calendar cal = Calendar.getInstance();
//Sun, 08 Feb 2015 00:00:00 GMT
underTest.setCurrentDate(setTimeToMidnightAndGet(cal, 1423353600000L));
underTest.showNextMonth();
//Sun, 01 Mar 2015 00:00:00 GMT - expected
assertEquals(setTimeToMidnightAndGet(cal, 1425168000000L), underTest.getFirstDayOfCurrentMonth());
when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP);
//Scroll enough to push calender to next month
underTest.onScroll(motionEvent, motionEvent, 600, 0);
underTest.onDraw(canvas);
underTest.onTouch(motionEvent);
//Wed, 01 Apr 2015 00:00:00 GMT
assertEquals(setTimeToMidnightAndGet(cal, 1427842800000L), underTest.getFirstDayOfCurrentMonth());
}
@Test
public void testItScrollsToNextMonth(){
//Sun, 08 Feb 2015 00:00:00 GMT
underTest.setCurrentDate(new Date(1423353600000L));
underTest.showNextMonth();
Date actualDate = underTest.getFirstDayOfCurrentMonth();
//Sun, 01 Mar 2015 00:00:00 GMT - expected
assertEquals(new Date(1425168000000L), actualDate);
}
@Test
public void testItScrollsToPreviousMonth(){
//Sun, 08 Feb 2015 00:00:00 GMT
underTest.setCurrentDate(new Date(1423353600000L));
underTest.showPreviousMonth();
Date actualDate = underTest.getFirstDayOfCurrentMonth();
// Thu, 01 Jan 2015 00:00:00 GMT - expected
assertEquals(new Date(1420070400000L), actualDate);
}
@Test
public void testItSetsDayColumns(){
//simulate Feb month
when(calendar.get(Calendar.DAY_OF_WEEK)).thenReturn(1);
when(calendar.get(Calendar.MONTH)).thenReturn(1);
when(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(28);
String[] dayNames = {"Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"};
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.setDayColumnNames(dayNames);
underTest.drawMonth(canvas, calendar, 0);
InOrder inOrder = inOrder(canvas);
inOrder.verify(canvas).drawText(eq("Mon"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Tue"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Wed"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Thur"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Fri"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Sat"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Sun"), anyInt(), anyInt(), eq(paint));
}
@Test
public void testListenerIsCalledOnMonthScroll(){
//Sun, 01 Mar 2015 00:00:00 GMT
Date expectedDateOnScroll = new Date(1425168000000L);
when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_UP);
//Set width of view so that scrolling will return a correct value
underTest.onMeasure(720, 1080, 0, 0);
//Sun, 08 Feb 2015 00:00:00 GMT
underTest.setCurrentDate(new Date(1423353600000L));
//Scroll enough to push calender to next month
underTest.onScroll(motionEvent, motionEvent, 600, 0);
underTest.onDraw(canvas);
underTest.onTouch(motionEvent);
assertEquals(expectedDateOnScroll, underTest.getFirstDayOfCurrentMonth());
}
@Test
public void testItAbbreviatesDayNames(){
//simulate Feb month
when(calendar.get(Calendar.DAY_OF_WEEK)).thenReturn(1);
when(calendar.get(Calendar.MONTH)).thenReturn(1);
when(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(28);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.setLocale(Locale.FRANCE);
reset(canvas); //reset because invalidate is called
underTest.setUseWeekDayAbbreviation(true);
reset(canvas); //reset because invalidate is called
underTest.drawMonth(canvas, calendar, 0);
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.FRANCE);
String[] dayNames = dateFormatSymbols.getShortWeekdays();
InOrder inOrder = inOrder(canvas);
inOrder.verify(canvas).drawText(eq(dayNames[2]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[3]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[4]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[5]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[6]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[7]), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq(dayNames[1]), anyInt(), anyInt(), eq(paint));
}
@Test
public void testItReturnsFirstDayOfMonthAfterDateHasBeenSet(){
//Sun, 01 Feb 2015 00:00:00 GMT
Date expectedDate = new Date(1422748800000L);
//Sun, 08 Feb 2015 00:00:00 GMT
underTest.setCurrentDate(new Date(1423353600000L));
Date actualDate = underTest.getFirstDayOfCurrentMonth();
assertEquals(expectedDate, actualDate);
}
@Test
public void testItReturnsFirstDayOfMonth(){
Calendar currentCalender = Calendar.getInstance();
currentCalender.set(Calendar.DAY_OF_MONTH, 1);
currentCalender.set(Calendar.HOUR_OF_DAY, 0);
currentCalender.set(Calendar.MINUTE, 0);
currentCalender.set(Calendar.SECOND, 0);
currentCalender.set(Calendar.MILLISECOND, 0);
Date expectFirstDayOfMonth = currentCalender.getTime();
Date actualDate = underTest.getFirstDayOfCurrentMonth();
assertEquals(expectFirstDayOfMonth, actualDate);
}
@Test
public void testItDrawsSundayAsFirstDay(){
//simulate Feb month
when(calendar.get(Calendar.DAY_OF_WEEK)).thenReturn(1);
when(calendar.get(Calendar.MONTH)).thenReturn(1);
when(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(28);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.setShouldShowMondayAsFirstDay(false);
underTest.setUseWeekDayAbbreviation(true);
underTest.drawMonth(canvas, calendar, 0);
InOrder inOrder = inOrder(canvas);
inOrder.verify(canvas).drawText(eq("Sun"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Mon"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Tue"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Wed"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Thu"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Fri"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("Sat"), anyInt(), anyInt(), eq(paint));
}
@Test
public void testItDrawsFirstLetterOfEachDay(){
//simulate Feb month
when(calendar.get(Calendar.DAY_OF_WEEK)).thenReturn(1);
when(calendar.get(Calendar.MONTH)).thenReturn(1);
when(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(28);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.drawMonth(canvas, calendar, 0);
InOrder inOrder = inOrder(canvas);
inOrder.verify(canvas).drawText(eq("M"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("T"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("W"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("T"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("F"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("S"), anyInt(), anyInt(), eq(paint));
inOrder.verify(canvas).drawText(eq("S"), anyInt(), anyInt(), eq(paint));
}
@Test
public void testItDrawsDaysOnCalender(){
//simulate Feb month
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
when(calendar.get(Calendar.DAY_OF_WEEK)).thenReturn(1);
when(calendar.get(Calendar.MONTH)).thenReturn(1);
when(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(28);
underTest.drawMonth(canvas, calendar, 0);
for(int dayColumn = 0, dayRow = 0; dayColumn <= 6; dayRow++){
if(dayRow == 7){
dayRow = 0;
if(dayColumn <= 6){
dayColumn++;
}
}
if(dayColumn == dayColumnNames.length){
break;
}
if(dayColumn == 0){
verify(canvas).drawText(eq(dayColumnNames[dayColumn]), anyInt(), anyInt(), eq(paint));
}else{
int day = ((dayRow - 1) * 7 + dayColumn + 1) - 6;
if( day > 0 && day <= 28){
verify(canvas).drawText(eq(String.valueOf(day)), anyInt(), anyInt(), eq(paint));
}
}
}
}
@Test
public void testItRemovesAllEvents(){
//Sun, 01 Feb 2015 00:00:00 GMT
List<Event> events = getEvents(0, 30, 1422748800000L);
for(Event event : events){
underTest.addEvent(event);
}
underTest.removeAllEvents();
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(1422748800000L));
Assert.assertEquals(new ArrayList<Event>(), actualEvents);
}
@Test
public void testItAddsAndGetsEvents(){
//Sun, 01 Feb 2015 00:00:00 GMT
List<Event> events = getEvents(0, 30, 1422748800000L);
for(Event event : events){
underTest.addEvent(event);
}
events = getEvents(0, 28, 1422748800000L);
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(1422748800000L));
Assert.assertEquals(events.get(0), actualEvents.get(0));
}
@Test
public void testItAddsEventsUsingList(){
//Sun, 01 Feb 2015 00:00:00 GMT
List<Event> events = getEvents(0, 30, 1422748800000L);
underTest.addEvents(events);
events = getEvents(0, 28, 1422748800000L);
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(1422748800000L));
Assert.assertEquals(1, actualEvents.size());
Assert.assertEquals(events.get(0), actualEvents.get(0));
}
@Test
public void testItRemovesEvents(){
//Sun, 01 Feb 2015 00:00:00 GMT
List<Event> events = getEvents(0, 30, 1422748800000L);
for(Event event : events){
underTest.addEvent(event);
}
underTest.removeEvent(events.get(0));
underTest.removeEvent(events.get(1));
underTest.removeEvent(events.get(5));
underTest.removeEvent(events.get(20));
List<Event> expectedEvents = getEvents(0, 28, 1422748800000L);
expectedEvents.remove(events.get(0));
expectedEvents.remove(events.get(1));
expectedEvents.remove(events.get(5));
expectedEvents.remove(events.get(20));
for (Event e : expectedEvents) {
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(e.getTimeInMillis()));
Assert.assertEquals(1, actualEvents.size());
Assert.assertEquals(e, actualEvents.get(0));
}
}
@Test
public void testItGetsMultipleEventsThatWereAddedForADay(){
//Add 3 events per a day for Feb starting from Sun, 01 Feb 2015 00:00:00 GMT
Map<Long, List<Event>> events = getMultipleEventsForEachDayAsMap(0, 30, 1422748800000L);
for(Map.Entry<Long, List<Event>> entry : events.entrySet()){
for (Event event: entry.getValue()) {
underTest.addEvent(event);
}
}
//if multiple events were added for every day, then check that all events are present by day
for(Map.Entry<Long, List<Event>> entry : events.entrySet()){
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(entry.getKey()));
Assert.assertEquals(entry.getValue(), actualEvents);
}
}
@Test
public void testItRemovesEventsUsingList(){
//Sun, 01 Feb 2015 00:00:00 GMT
List<Event> events = getEvents(0, 30, 1422748800000L);
for(Event event : events){
underTest.addEvent(event);
}
underTest.removeEvents(Arrays.asList(events.get(0), events.get(1), events.get(5), events.get(20)));
List<Event> expectedEvents = getEvents(0, 28, 1422748800000L);
expectedEvents.removeAll(Arrays.asList(events.get(0), events.get(1), events.get(5), events.get(20)));
for (Event e : expectedEvents) {
List<Event> actualEvents = underTest.getCalendarEventsFor(new Date(e.getTimeInMillis()));
Assert.assertEquals(1, actualEvents.size());
Assert.assertEquals(e, actualEvents.get(0));
}
}
@Test
public void testItDrawsEventDaysOnCalendar(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 30 events in total
List<Event> events = getEvents(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
when(calendar.get(Calendar.MONTH)).thenReturn(5);
when(calendar.get(Calendar.YEAR)).thenReturn(2015);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.drawEvents(canvas, calendar, 0);
//draw events 29 times because we don't draw events for the current selected day since it wil be highlighted with another indicator
verify(canvas, times(29)).drawCircle(anyFloat(), anyFloat(), anyFloat(), eq(paint));
}
@Test
public void testItDrawsMultipleEventDaysOnCalendar(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 60 events in total
List<Event> events = getDayEventWith2EventsPerDay(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
when(calendar.get(Calendar.MONTH)).thenReturn(5);
when(calendar.get(Calendar.YEAR)).thenReturn(2015);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.drawEvents(canvas, calendar, 0);
//draw events 58 times because we don't draw events for the current selected day since it wil be highlighted with another indicator
verify(canvas, times(58)).drawCircle(anyFloat(), anyFloat(), anyFloat(), eq(paint));
}
@Test
public void testItDrawsMultipleEventDaysOnCalendarWithPlusIndicator(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 120 events in total but only draw 3 event indicators per a day
List<Event> events = getDayEventWithMultipleEventsPerDay(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
when(calendar.get(Calendar.MONTH)).thenReturn(5);
when(calendar.get(Calendar.YEAR)).thenReturn(2015);
underTest.setGrowProgress(1000); //set grow progress so that it simulates the calendar being open
underTest.drawEvents(canvas, calendar, 0);
//draw events 58 times because we don't draw more than 3 indicators
verify(canvas, times(58)).drawCircle(anyFloat(), anyFloat(), anyFloat(), eq(paint));
//draw event indicator with lines
// 2 calls for each plus event indicator since it takes 2 draw calls to make a plus sign
verify(canvas, times(58)).drawLine(anyFloat(), anyFloat(), anyFloat(), anyFloat(), eq(paint));
}
@Test
public void testItGetsEventsForSpecificDay(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 30 events in total
List<Event> events = getEvents(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
//Wed, 24 Aug 2016 09:21:09 GMT
//get 30 events in total
List<Event> events2 = getEvents(0, 30, 1472030469000L);
for(Event event : events2){
underTest.addEvent(event);
}
//Sun, 07 Jun 2015 18:20:51 GMT
List<Event> calendarDayEvents = underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
assertNotNull(calendarDayEvents);
//Assert 6th item since it will represent Sun, 07 Jun 2015 which is the day that we queried for
assertEquals(1, calendarDayEvents.size());
assertEquals(events.get(6), calendarDayEvents.get(0));
}
@Test
public void testItRemovesEventByDate(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 30 events in total
List<Event> events = getEvents(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
assertEquals(1, underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L)).size());
assertEquals(events.get(6), underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L)).get(0));
//Sun, 07 Jun 2015 18:20:51 GMT
underTest.removeEventsByDate(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
//Remove 6th item since it will represent Sun, 07 Jun 2015 which is the day that was removed
events.remove(6);
assertEquals(0, underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L)).size());
}
@Test
public void testItUpdatesEvents(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 30 events in total
List<Event> events = getEvents(0, 30, 1433701251000L);
for(Event event : events){
underTest.addEvent(event);
}
//Sun, 07 Jun 2015 18:20:51 GMT
List<Event> calendarDayEvents = underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
assertNotNull(calendarDayEvents);
//Assert 6th item since it will represent Sun, 07 Jun 2015 which is the day that we queried for
assertEquals(events.get(6), calendarDayEvents.get(0));
//Add a random event Sun, 07 Jun 2015 21:24:21 GMT
Event updateItem = new Event(Color.GREEN, 1433712261000L);
calendarDayEvents.add(updateItem);
//Query again Sun, 07 Jun 2015 18:20:51 GMT to make sure list is updated
List<Event> calendarDayEvents2 = underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
assertTrue(calendarDayEvents2.contains(updateItem));
}
@Test
public void testItAddsEventsToExistingList(){
//Sun, 07 Jun 2015 18:20:51 GMT
//get 30 events in total
List<Event> events = getEvents(0, 30, 1433701251000L);
underTest.addEvents(events);
//Sun, 07 Jun 2015 18:20:51 GMT
List<Event> calendarDayEvents = underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
//Assert 6th item since it will represent Sun, 07 Jun 2015 which is the day that we queried for
assertEquals(events.get(6), calendarDayEvents.get(0));
//add event in Sun, 07 Jun 2015 18:20:51 GMT for same day, making total 2 events for same day now
Event extraEventAdded = new Event(Color.GREEN, 1433701251000L);
underTest.addEvent(extraEventAdded);
//Sun, 07 Jun 2015 18:20:51 GMT
List<Event> calendarDayEvents2 = underTest.getCalendarEventsFor(setTimeToMidnightAndGet(Calendar.getInstance(), 1433701251000L));
assertNotNull(calendarDayEvents2);
//Assert 6th item since it will represent Sun, 07 Jun 2015 which is the day that we queried for
assertEquals(2, calendarDayEvents2.size());
assertEquals(events.get(6), calendarDayEvents2.get(0));
assertEquals(extraEventAdded, calendarDayEvents2.get(1));
}
private List<Event> getEvents(int start, int days, long timeStamp) {
return getEvents(start, days, timeStamp, Color.BLUE);
}
//generate one event per a day for a month
private List<Event> getEvents(int start, int days, long timeStamp, int color) {
Calendar currentCalender = Calendar.getInstance(Locale.getDefault());
List<Event> events = new ArrayList<>();
for(int i = start; i < days; i++){
setDateTime(timeStamp, currentCalender, i);
events.add(new Event(color, currentCalender.getTimeInMillis()));
}
return events;
}
private List<Event> getDayEventWith2EventsPerDay(int start, int days, long timeStamp) {
Calendar currentCalender = Calendar.getInstance(Locale.getDefault());
List<Event> eventList = new ArrayList<>();
for(int i = start; i < days; i++){
setDateTime(timeStamp, currentCalender, i);
eventList.add(new Event(Color.BLUE, currentCalender.getTimeInMillis()));
eventList.add(new Event(Color.RED, currentCalender.getTimeInMillis() + 3600 * 1000));
}
return eventList;
}
private List<Event> getDayEventWithMultipleEventsPerDay(int start, int days, long timeStamp) {
Calendar currentCalender = Calendar.getInstance(Locale.getDefault());
List<Event> eventList = new ArrayList<>();
for(int i = start; i < days; i++){
setDateTime(timeStamp, currentCalender, i);
List<Event> events = Arrays.asList(new Event(Color.BLUE, currentCalender.getTimeInMillis()),
new Event(Color.RED, currentCalender.getTimeInMillis() + 3600 * 1000),
new Event(Color.RED, currentCalender.getTimeInMillis() + (3600 * 2) * 1000),
new Event(Color.RED, currentCalender.getTimeInMillis() + (3600 * 3) * 1000));
eventList.addAll(events);
}
return eventList;
}
private Map<Long, List<Event>> getMultipleEventsForEachDayAsMap(int start, int days, long timeStamp) {
Calendar currentCalender = Calendar.getInstance(Locale.getDefault());
Map<Long, List<Event>> epochMillisToEvents = new HashMap<>();
for(int i = start; i < days; i++){
setDateTime(timeStamp, currentCalender, i);
List<Event> eventList = new ArrayList<>();
List<Event> events = Arrays.asList(new Event(Color.BLUE, currentCalender.getTimeInMillis()),
new Event(Color.RED, currentCalender.getTimeInMillis() + 3600 * 1000),
new Event(Color.RED, currentCalender.getTimeInMillis() + (3600 * 2) * 1000),
new Event(Color.RED, currentCalender.getTimeInMillis() + (3600 * 3) * 1000));
eventList.addAll(events);
epochMillisToEvents.put(currentCalender.getTimeInMillis(), eventList);
}
return epochMillisToEvents;
}
private void setDateTime(long timeStamp, Calendar currentCalender, int i) {
currentCalender.setTimeInMillis(timeStamp);
currentCalender.set(Calendar.DATE, 1);
currentCalender.set(Calendar.HOUR_OF_DAY, 0);
currentCalender.set(Calendar.MINUTE, 0);
currentCalender.set(Calendar.SECOND, 0);
currentCalender.set(Calendar.MILLISECOND, 0);
currentCalender.add(Calendar.DATE, i);
}
private Date setTimeToMidnightAndGet(Calendar cal, long epoch) {
cal.setTime(new Date(epoch));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
|
antonelloceravola/ToolBOSCore | include/ToolBOSCore/Util/FastScript.py | <gh_stars>0
# -*- coding: utf-8 -*-
#
# convenience functions for frequently used scripting operations
#
# Copyright (c) Honda Research Institute Europe GmbH
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
import getpass
import logging
import os
import platform
import re
import shutil
import socket
import sys
from ToolBOSCore.Util import Any
#----------------------------------------------------------------------------
# Filesystem access
#----------------------------------------------------------------------------
def getDirsInDir( path = '.', excludePattern = None, onError = None ):
"""
Return all directories within a specified one, except "." and "..".
You may specify a regular expression for directories to be excluded:
\param path absolute or relative path to directory
\param excludePattern regular expression object that will be
used to match against the found element, e.g.:
\code
excludePattern = re.compile( "\d+.\d+" )
dirList = getDirsInDir( "/tmp", excludePattern )
\endcode
\param onError You may pass a function callback that will be called
upon errors, e.g. permission denied. This function needs
to take a single path parameter. If omitted, an
OSError will be raised upon errors.
\return List of all directories (except "." and "..") within the
specified on. If the directory does not exist, is empty or
if all subdirectories match the exclude blacklist then the
result list will be empty.
"""
Any.requireIsTextNonEmpty( path )
subdirList = []
if not os.path.isdir( path ):
return subdirList
try:
for item in os.listdir( path ):
if os.path.isdir( os.path.join( path, item ) ):
if excludePattern:
if excludePattern.search( item ) is None:
# exclude pattern does not match, so file can be added
subdirList.append( item )
else:
# exclude pattern matches --> skip
pass
else:
subdirList.append( item )
except OSError:
if onError:
onError( path )
else:
raise
return subdirList
def getDirsInDirRecursive( path = '.',
excludePattern = None,
keepSubDirs = True,
onError = None ):
"""
Unlike to FastScript.getDirsInDir() this one recursively returns all
directories within a given one. You may specify a regular expression
for directories to be excluded. If "keepSubDirs" is True the path to
the subdirectories will be preserved, if False only the leaf names
will be returned.
'excludePattern' must be a regular expression object that will be
used to match against the found element, e.g.:
excludePattern = re.compile( "\d+.\d+" )
dirList = getDirsInDirRecursive( "/tmp", excludePattern )
If the directory does not exist, is empty or if all subdirectories
match the exclude blacklist then the result list will be empty.
You may pass a function callback that will be called upon errors,
e.g. permission denied. This function needs to take a single
path parameter. If omitted, an OSError will be raised upon errors.
"""
Any.requireIsTextNonEmpty( path )
result = []
if not os.path.isdir( path ):
return result
for item in os.listdir( path ):
# skip symlinks which are also returned by os.listdir():
joinedPath = os.path.join( path, item )
if os.path.islink( joinedPath ):
continue
if os.path.isdir( joinedPath ):
if ( excludePattern == None ) or \
( excludePattern != None and excludePattern.search( item ) == None ):
subDirList = []
try:
subDirList = getDirsInDirRecursive( joinedPath,
excludePattern,
keepSubDirs,
onError )
except OSError:
if onError:
onError( joinedPath )
else:
raise
if keepSubDirs == True or len( subDirList ) == 0:
result.append( joinedPath )
result.extend( subDirList )
return result
def getFilesInDir( path, excludePattern = '' ):
"""
Returns all files within a specified directory. You may specify a
regular expression for filenames to be excluded.
This function is pretty equal to Python's glob.glob() and might be
removed in the future.
"""
Any.requireIsTextNonEmpty( path )
subdirList = []
if not os.path.isdir( path ):
return subdirList
for item in os.listdir( path ):
if os.path.isfile( os.path.join( path, item ) ):
if excludePattern == '' or re.search( excludePattern, item ) == None:
subdirList.append( item )
return subdirList
def getFilesInDirRecursive( path, excludePattern = None ):
"""
Returns a set of all files that can be recursively found under 'path'.
'excludePattern' must be a regular expression object that will be
used to exclude certain directories (such as "build" and ".svn") in
the following example:
excludePattern = re.compile( "(build|.svn)" )
fileList = getFilesInDirRecursive( "Package/1.0", excludePattern )
"""
result = set()
subDirs = getDirsInDirRecursive( path, excludePattern )
# files directly within 'path'
for fileName in getFilesInDir( path ):
result.add( os.path.join( path, fileName ) )
# files within subdirectories
for subDir in subDirs:
for fileName in getFilesInDir( subDir ):
result.add( os.path.join( subDir, fileName ) )
return result
def changeDirectory( path ):
"""
Changes the current working directory.
"""
logging.debug( 'cd %s', path )
os.chdir( path )
def rename( src, dst ):
"""
Renames/moves a files from "src" path to "dst" path.
In contrast to Python's os.rename() function this checks the
validity of the "src" filename first, and requires that the "dst"
file has been successfully written.
"""
Any.requireIsTextNonEmpty( src )
Any.requireIsTextNonEmpty( dst )
Any.requireIsFile( src )
dstDir = os.path.dirname( dst )
mkdir( dstDir )
os.rename( src, dst )
Any.requireIsFile( dst )
def remove( path, dryRun=False, ignoreErrors=False ):
"""
Removes/unlinks the file or directory "path". If "path" is a
directory, it will be deleted recursively (caution!).
"""
if os.path.isfile( path ) or os.path.islink( path ):
if dryRun:
logging.debug( '[DRY-RUN] rm %s', path )
else:
logging.debug( 'rm %s', path )
os.remove( path )
elif os.path.isdir( path ):
if dryRun:
logging.debug( '[DRY-RUN] rm -R %s', path )
else:
logging.debug( 'rm -R %s', path )
shutil.rmtree( path, ignoreErrors )
def copy( src, dst ):
"""
If 'src' is a file, it will be copied. In case of symlinks the
content (!) is copied, not the link itself.
If 'src' is a directory, it will be copied recursively.
"""
if os.path.isdir( src ):
logging.debug( 'cp -R %s %s', src, dst )
shutil.copytree( src, dst )
else:
logging.debug( 'cp %s %s', src, dst )
shutil.copy2( src, dst ) # this also copies file meta-infos
def copyWithRetry( src, dst, maxAttempts=3, waitSeconds=2 ):
"""
Decorator for copy() which attempts to re-try the copy operation
for the given amount of attempts, with the given delay time in
between.
This is a not-so-nice but practical workaround for NFS hiccups.
"""
import time
Any.requireIsTextNonEmpty( src )
Any.requireIsTextNonEmpty( dst )
Any.requireIsInRange( maxAttempts, 1, 100 )
Any.requireIsInRange( waitSeconds, 1, 3600 )
i = 0
while i < maxAttempts:
i += 1
try:
copy( src, dst )
break # we managed to get here --> success
except OSError as e:
logging.debug( 'problem while copying: %s', e )
if i >= maxAttempts:
raise
else:
logging.debug( 'trying again in %ss...', waitSeconds )
time.sleep( waitSeconds )
def link( target, symlink, dryRun=False ):
"""
Creates a symlink, incl. all the necessary paths to it,
and also prints a debug message.
"""
Any.requireIsTextNonEmpty( symlink )
Any.requireIsTextNonEmpty( target ) # allow initially broken links
Any.requireIsBool( dryRun )
# create destination directory (if it does not exist, yet)
if not dryRun:
mkdir( os.path.dirname( symlink ) )
# remove any existing link under that name (if existing)
if not dryRun:
remove( symlink )
# create symlink
if dryRun:
logging.debug( '[DRY-RUN] ln -s %s %s', target, symlink )
else:
logging.debug( 'ln -s %s %s', target, symlink )
os.symlink( target, symlink )
def mkdir( path, verbose=False ):
"""
Creates the directory "path", with all intermediate directories to
this path if they do not exist, yet (like the "mkdir -p <path>" on
the GNU/Linux shell).
This is a convenience wrapper around os.makedirs(): If the directory
already exists this function returns silently.
If the directory can't be created, an exception will be thrown.
"""
Any.requireIsText( path )
if not path:
return
if verbose:
logging.info( 'mkdir -p %s', path )
else:
logging.debug( 'mkdir -p %s', path )
try:
os.makedirs( path )
except ( AssertionError, OSError ) as details:
if details.errno == 17: # 17 = directory exists
# ensure it's really a directory and not a file
Any.requireIsDir( path )
else:
raise
def getFileOwner( path ):
"""
Returns the username (if possible) of the owner of the specified
file or directory. If the username cannot be retrieved, the
numerical user ID will be used as fallback.
"""
from pwd import getpwuid
Any.requireIsTextNonEmpty( path )
ownerID = os.stat( path ).st_uid
ownerName = getpwuid( ownerID ).pw_name
return ownerName
def printPermissionDenied( path ):
logging.warning( '%s: Permission denied', path )
def ignore( path ):
pass
def getDirSize( path ):
"""
Returns the size occupied by a certain directory and all its
files and subdirectories inside.
This is an equivalent to "du -s" on the shell.
Size is returned in Bytes.
"""
size = 0
for root, dirs, files in os.walk( path ):
for f in files:
fullPath = os.path.join( root, f )
try:
size += os.path.getsize( fullPath )
except OSError:
logging.debug( "can't stat: %s" % fullPath )
return size
#----------------------------------------------------------------------------
# File I/O
#----------------------------------------------------------------------------
def getFileContent( filename, splitLines = False, asBinary=False ):
"""
Returns the whole content of a file as a single long string
(default) or as a list of lines if "splitLines=True".
If `asBinary` is set to True, the contents of the file are returned as
a byte array.
"""
if not os.path.isfile( filename ):
raise IOError( "%s: No such file" % filename )
mode = 'rU'
if asBinary:
mode += 'b'
with open( filename, mode ) as f:
logging.debug( 'reading file: %s', filename )
return f.readlines() if splitLines else f.read()
def setFileContent( filename, content ):
"""
Writes "content" (of type 'str' or 'unicode') to the specified file.
"""
Any.requireIsTextNonEmpty( filename )
Any.requireIsText( content )
dirName = os.path.dirname( filename )
if dirName and not os.path.isdir( dirName ):
mkdir( dirName )
f = open( filename, "w" )
f.write( content )
f.close()
def serializeToFile( filename, obj ):
"""
This function serializes 'object' into 'filename'.
Attention: If the specified file exists it will be overwritten.
"""
from pickle import Pickler
from ToolBOSCore.External.atomicfile import AtomicFile
Any.requireIsTextNonEmpty( filename )
with AtomicFile( filename, 'wb' ) as f: # Pickle uses binary streams
Pickler( f ).dump( obj )
def deserializeFromFile( filename ):
"""
Deserializes the content from 'filename' and returns it as
Python object.
"""
from pickle import Unpickler
Any.requireIsTextNonEmpty( filename )
try:
f = open( filename, 'rb' ) # Pickle uses binary streams
obj = Unpickler( f ).load()
f.close()
except EOFError as details:
raise IOError( details )
return obj
def findFiles( path, regexp=None, ext=None, excludeSVN=True ):
"""
Returns a list with all files in 'path' whoms names match a certain
pattern. Pattern can be:
* regexp: a precompiled regular expression object
* ext: file has a certain extension, e.g. ".c" (mind the dot!)
Note that both 'regexp' and 'ext' can be scalar values as well
as lists. In such case, any of the expression (or extension) must
match.
If 'excludeSVN=True', files under ".svn" are skipped.
"""
fileList = []
# recursively search for files
for root, dirs, files in os.walk( path ):
for entry in files:
path = os.path.join( root, entry )
fileExt = os.path.splitext( entry )[1]
# skip SVN files (if requested)
if excludeSVN == True and path.find( '.svn' ) != -1:
continue
# found a file with requested extension
if isinstance(ext,str) and ext == fileExt:
fileList.append( path )
elif isinstance(ext,list) or isinstance(ext,tuple):
if fileExt in ext:
fileList.append( path )
elif isinstance(regexp,list) or isinstance(regexp,tuple):
for exp in regexp:
if exp.search( entry ):
fileList.append( path )
break
# found a file matching regexp
elif regexp:
if regexp.search( entry ):
fileList.append( path )
return fileList
#----------------------------------------------------------------------------
# Inter-process communication
#----------------------------------------------------------------------------
def execFile( filename ):
"""
Evaluates/executes the content of the specified file which must
contain valid Python code.
If the code in this file declares any variables then their values
are returned in a map.
"""
Any.requireIsTextNonEmpty( filename )
# redundant check removed for performance reasons:
# open() itself will raise an IOError if file not present,
# avoid superfluous underlying stat() which is especially noticable
# when batch-loading a number of files
#
# if not os.path.isfile( filename ):
# raise IOError( "%s: No such file" % filename )
result = {}
with open( filename ) as fd:
exec( fd.read(), None, result)
return result
def execProgram( cmd, workingDir = None, host = 'localhost',
stdin = None, stdout = None, stderr = None,
username = None ):
"""
Executes another program/command.
You may redirect input/output streams by providing StringIO instances.
If 'host' is different than the default 'localhost' or the actual
hostname, an SSH tunnel will be opened and the command executed
remotely. 'host' can also be an IPv4/IPv6 address.
A 'username' can be specified to execute as a certain user. This
is most useful via SSH, on local machines only 'root' can do that.
Normal users will get prompted for a password in such case.
Restrictions on SSH:
* no check if 'workingDir' exists
* server must listen on default port 22
* authorized_keys must be configured with no passphrase
Returns the exit code of the program. Raises an exception if it is
not zero.
"""
import six
Any.requireIsTextNonEmpty( cmd )
from shlex import split
from subprocess import CalledProcessError
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
cmd, localWorkingDir = getCommandLine( cmd, workingDir, host, username )
logging.debug( 'executing: %s', cmd )
# execvp() will not accept unicode strings
try:
posix = platform.system().lower() != 'windows'
if posix:
# When running on Windows, there is no need to split the
# command line with shlex.
# See discussion on TBCORE-1496
cmd = split( cmd, posix=posix ) # array of parameters
except ValueError as details:
logging.error( 'parsing command line failed: %s', cmd )
logging.error( details )
raise ValueError( details )
inData = None
inStream = None
outStream = None
errStream = None
if stdin:
inStream = PIPE
inData = stdin.read()
if stdout:
outStream = PIPE
if stderr:
if stdout == stderr:
errStream = STDOUT
else:
errStream = PIPE
if six.PY3:
p = Popen( cmd, stdin=inStream, stdout=outStream,
stderr=errStream, cwd=localWorkingDir,
encoding='utf8' )
else:
p = Popen( cmd, stdin=inStream, stdout=outStream,
stderr=errStream, cwd=localWorkingDir )
( outData, errData ) = p.communicate( inData )
sys.stdout.flush()
sys.stderr.flush()
if stdout and outData:
stdout.writelines( outData )
stdout.flush()
if stderr and errData:
stderr.writelines( errData )
stderr.flush()
if p.returncode != 0:
raise CalledProcessError( p.returncode, cmd )
return p.returncode
def getCommandLine( cmd, workingDir=None, host=None, user=None ):
"""
Returns a tuple of the the appropriate SSH-wrapped commandline to
execute the given command on the specified host, and the working
directory to pass to Popen(), hence:
( command, workingDir )
If 'host' is the current machine, the plain 'cmd' will be
returned and the workingDir will be None.
"""
Any.requireIsTextNonEmpty( cmd )
if host is not None:
Any.requireIsTextNonEmpty( host )
if workingDir is not None:
Any.requireIsTextNonEmpty( workingDir )
localHostname = socket.gethostname()
if host in ( None, 'localhost', '127.0.0.1', '::1', localHostname ):
resultWorkingDir = workingDir
if user:
resultCmd = 'su - %s -c "%s"' % ( user, cmd )
else:
resultCmd = cmd
else:
if not workingDir:
workingDir = os.getcwd()
# disable fingerprint check to avoid interactive prompt
# in case the hostkey has changed
sshOpts = '-o BatchMode=yes -o StrictHostKeyChecking=no'
if user:
resultCmd = "ssh %s -X %s@%s 'cd %s; %s'" % \
(sshOpts, user, host, workingDir, cmd)
else:
resultCmd = "ssh %s -X %s 'cd %s; %s'" % \
(sshOpts, host, workingDir, cmd)
# unset the working dir. so that Popen() will not get it as
# argument (because we don't want to set workingDir of the local
# SSH process, but instead we have injected the "cd ..." into the
# remote command above)
resultWorkingDir = None
return resultCmd, resultWorkingDir
def getEnv( varName = False ):
"""
If called without parameter this function returns a deep copy of
the whole environment map (not just references).
If the parameter 'varName' is given it only returns a string with
the value of that variable. If there is no such environment variable
it will return 'None'.
"""
if not varName:
return os.environ
else:
try:
return os.environ[ varName ]
except KeyError:
return None
def getEnvChk( varName, default=None ):
"""
Like FastScript.getEnv, with additional support for a default parameter.
If the requested 'varName' is not found in the environment and no default
parameter is specified, an EnvironmentError is raised.
"""
Any.requireIsTextNonEmpty( varName )
value = getEnv( varName )
if value is None:
if default is None:
if not Any.isTextNonEmpty( value ):
raise EnvironmentError( '%s: empty environment variable' % varName )
else:
return default
else:
return value
def setEnv( varNameOrMap, varValue = '' ):
"""
This function can be used to set the process environment variables.
a) If 'varNameOrMap' is of type 'dict' (a whole map of environment
variables mapped to their values), it will set the environment
to this. The second parameter is ignored in such case.
Please note that all environment variables will be modified,
even those not present in the map (those effectively get deleted).
b) If 'varNameOrMap' is of type "str" it will set an environment
variable with this name. Optionally you can specify 'varValue' of
type 'str' to assign a value to this environment variable.
"""
if Any.isText( varNameOrMap ): # set single variable
logging.debug( 'export %s="%s"', varNameOrMap, varValue )
os.environ[ varNameOrMap ] = varValue
else: # set whole map
os.environ.clear()
os.environ.update( varNameOrMap )
def setEnv_withExpansion( varName, varValue ):
"""
This function can be used to set a particular process environment
variable.
Unlike setEnv(), which works verbatim, this function also searches
for environment variables inside 'varValue' and in case replaces
them first.
Example:
setEnv_withExpansion( 'MATLAB_ROOT',
'${SIT}/External/Matlab/8.4' )
setEnv_withExpansion( 'PATH',
'${MATLAB_ROOT}/bin:${PATH}' )
will first define MATLAB_ROOT as absolute path to Matlab/8.4
(replacing ${SIT} by its current environment value)
and in a second step prepend the absolute path to Matlab's
"bin"-directory to the current value of ${PATH}.
"""
Any.requireIsTextNonEmpty( varName )
Any.requireIsTextNonEmpty( varValue )
setEnv( varName, os.path.expandvars( varValue ) )
def unsetEnv( varName = False ):
"""
This function can be used to delete all or a particular environment
variable.
a) If 'varName' is specified, it will only delete this environment
variable.
Please note: If the variable was already present before starting
this process, it will still be present in your shell after
terminating this process. Deleting environment variables from
within Python will only have effect within this particular process.
b) If the 'varName' parameter is omitted, all environment variables
will be deleted (caution!). This might not be useful ;-)
The function silently catches the exception if there is no variable
with the given name.
"""
if isinstance( varName, str ): # remove single variable
try:
logging.debug( 'unset %s', varName )
del os.environ[ varName ]
except KeyError:
pass
else:
os.environ.clear() # clear whole process env.
def appendEnv( varName, s ):
"""
Adds 's' at the end of the existing value of the given env.var.
If 'varName' was not defined it will be created.
Example:
append( 'PATH', ':/path/to/foo' )
"""
Any.requireIsTextNonEmpty( varName )
Any.requireIsText( s )
oldValue = getEnv( varName )
if oldValue:
newValue = oldValue + s
else:
newValue = s
setEnv( varName, newValue )
def prependEnv( varName, s ):
"""
Adds 's' at the beginning of the existing value of the given env.var.
If 'varName' was not defined it will be created.
Example:
prepend( 'PATH', '/path/to/foo:' )
"""
Any.requireIsTextNonEmpty( varName )
Any.requireIsText( s )
oldValue = getEnv( varName )
if oldValue:
newValue = s + oldValue
else:
newValue = s
setEnv( varName, newValue )
#----------------------------------------------------------------------------
# Security & Permissions
#----------------------------------------------------------------------------
def chmodRecursive( path, dirPermission, filePermission ):
"""
Changes the attributes (permissions) of the file or directory
<path> recursively so that the given path has permissions as specified in
<dirPermission> and <filePermission>.
For example, to make a directory writeable for all HRI-EU members:
FastScript.setPermissions( '/path', 0o775, 0o664 )
ATTENTION: <dirPermission> and <filePermission> needs to be passed as octal number,
with a leading '0o' prefix to support Python 2 and 3.
"""
Any.requireIsTextNonEmpty( path )
Any.requireIsIntNotZero( dirPermission )
Any.requireIsIntNotZero( filePermission )
for dirpath, dirs, files in os.walk( path ):
for item in dirs:
path = os.path.join( dirpath, item )
logging.debug( "chmod %o %s", dirPermission, path )
os.chmod( path, dirPermission )
for item in files:
path = os.path.join( dirpath, item )
logging.debug( "chmod %o %s", filePermission, path )
os.chmod( os.path.join( dirpath, item ), filePermission )
def readOnlyChmod( path ):
"""
Set read only permissions to the given path recursively.
"""
Any.requireIsTextNonEmpty( path )
dirPerms = 0o555
filePerms = 0o444
chmodRecursive( path, dirPerms, filePerms )
def readWriteChmod( path ):
"""
Set read-write permissions to the given path recursively.
"""
Any.requireIsTextNonEmpty( path )
dirPerms = 0o775
filePerms = 0o664
chmodRecursive( path, dirPerms, filePerms )
def setGroupPermission( path, groupName, mode ):
"""
Changes the attributes (permissions) of the file or directory
<path> so that the given group has permissions as specified in
<mode>.
For example, to make a directory writeable for all HRI-EU members:
FastScript.setGroupPermission( '/path', 'users', 0775 )
ATTENTION: <mode> needs to be passed as octal number with a
leading zero!
If an operation failed e.g. due to insufficient rights it will be
silently ignored! If you need to catch such cases please use
the 'os' module directly. We are also not checking if <path>
exists at all.
The only known exception will be if the specified group
does not exist.
"""
from grp import getgrnam
Any.requireIsTextNonEmpty( path ) # do not check if exists
Any.requireIsTextNonEmpty( groupName )
Any.requireIsIntNotZero( mode )
groupID = getgrnam( groupName ).gr_gid
try:
os.chmod( path, mode )
except OSError:
pass
try:
os.chown( path, -1, groupID ) # -1 == don't change userID
except OSError:
pass
def getCurrentUserID():
"""
Returns the UID of the current process.
"""
from pwd import getpwnam
return getpwnam( getpass.getuser() ).pw_uid
def getCurrentUserName():
"""
Returns the login name for the UID of the current process.
"""
return getpass.getuser()
def getCurrentUserFullName():
"""
Returns the full name for the UID of the current process.
"""
from pwd import getpwnam
return getpwnam( getpass.getuser() ).pw_gecos
def getCurrentGroupID():
"""
Returns the primary GID of the user running the current process.
"""
from pwd import getpwnam
return getpwnam( getpass.getuser() ).pw_gid
def getCurrentGroupName():
"""
Returns the primary group name of the user running the current
process.
"""
from grp import getgrgid
return getgrgid( getCurrentGroupID() ).gr_name
#----------------------------------------------------------------------------
# String processing
#----------------------------------------------------------------------------
def expandVar( string, varName ):
"""
This function retrieves the value of the environment variable
"varName". Then it searches for "${varName}" in "string" and
replaces it with the actual value, e.g.:
str = '${SIT}/DevelopmentTools/ToolBOSCore'
path = FastScript.expandVar( str, 'SIT' )
"path" will then be e.g. "/hri/sit/latest/DevelopmentTools/ToolBOSCore"
"""
Any.requireIsTextNonEmpty( string )
Any.requireIsTextNonEmpty( varName )
value = getEnv( varName )
if not value:
return string
else:
return string.replace( "${" + varName + "}", value )
def expandVars( string ):
"""
Loops over all environment variables in the process environment,
and searches for "${varName}" in "string" and replaces it with the
actual value, e.g.:
str = '${SIT}/users/${USER}'
path = FastScript.expandVars( str )
"path" will then be e.g. "/hri/sit/latest/users/torvalds".
"""
Any.requireIsText( string ) # might be empty
if len(string) == 0:
return string
for varName, value in os.environ.items():
string = string.replace( "${" + varName + "}", value )
return string
def collapseVar( string, varName ):
"""
This function retrieves the value of the environment variable
"varName". Then it searches for this value in "string" and
replaces it with the "${varName}", e.g.:
path = "/hri/sit/latest/DevelopmentTools/ToolBOSCore"
str = FastScript.collapseVar( str, 'SIT' )
"str" will then be '${SIT}/DevelopmentTools/ToolBOSCore'
"""
Any.requireIsTextNonEmpty( string )
Any.requireIsTextNonEmpty( varName )
value = getEnv( varName )
if not value:
return string
else:
return string.replace( value, "${" + varName + "}" )
def countCharacters( string ):
"""
Returns the number of different characters within given string.
Example: countCharacters( 'abcabc' ) would return 3.
This is a re-implementation of PHP's count_chars() function.
"""
Any.requireIsText( string )
tmp = {}
for char in string:
try:
tmp[ char ] += 1 # increment number of occurrences
except KeyError:
tmp[ char ] = 1 # first time found
return len( tmp.keys() )
#----------------------------------------------------------------------------
# List processing
#----------------------------------------------------------------------------
def flattenList( nestedList ):
"""
Flattens a nested list into a one-dimensional list.
"""
from ToolBOSCore.External.Flatten import flatten
Any.requireIsList( nestedList )
return flatten( nestedList )
def removeDuplicates( aList ):
"""
Removes all duplicate elements from a list.
"""
from ToolBOSCore.External.f5 import f5
Any.requireIsList( aList )
return f5( aList )
def reduceList( nestedList ):
"""
Flattens a nested list into a one-dimensional list and removes
all duplicate elements.
"""
Any.requireIsList( nestedList )
resultList = flattenList( nestedList )
resultList = removeDuplicates( resultList )
return resultList
def getTreeView( nestedList, level = 0, levelPadding = '' ):
"""
Returns a string representation of the given (optionally nested)
list.
The parameters 'level' and 'levelPadding' are only internally used
for recursion and should not be set by the user.
"""
Any.requireIsList( nestedList )
result = ''
if level > 20: # loop guard
raise ValueError
for i, entry in enumerate( nestedList ):
if Any.isText( entry ):
entryPadding = levelPadding + '%c---' % _getTreeChar( nestedList, i )
result += "%s%s\n" % ( entryPadding, entry )
elif Any.isList( entry ):
entryPadding = levelPadding + '%c ' % _getTreeChar( nestedList, i )
result += getTreeView( entry, level + 1, entryPadding )
else:
raise TypeError
return result
#----------------------------------------------------------------------------
# Time functions
#----------------------------------------------------------------------------
def isoTime( dt=None ):
"""
Returns a string with human-readable ISO 8601 time format of the
provided datetime-instance (or current time if omitted).
"""
import time
if dt is None:
dt = now()
naive = dt.strftime( '%Y-%m-%d %H:%M:%S' )
offset = time.strftime( '%z' )
return '%s %s' % ( naive, offset )
def now():
"""
Returns the current time as datetime object.
"""
from datetime import datetime
return datetime.now()
def startTiming():
"""
Returns a time object for measuring code execution times.
In fact it is the same as FastScript.now().
"""
return now()
def stopTiming( startTime ):
"""
Prints the elapsed time from 'startTime' to now.
Useful for measuring code execution times.
"""
import datetime
Any.requireIsInstance( startTime, datetime.datetime )
stopTime = now()
logging.debug( 'elapsed time: %s', stopTime - startTime )
#----------------------------------------------------------------------------
# Misc
#----------------------------------------------------------------------------
def prettyPrintError( msg ):
"""
Throws a SystemExit exception, which if uncaught shows 'msg' as
red text on the console.
"""
from textwrap import wrap
Any.requireIsTextNonEmpty( msg )
lines = wrap( msg )
finalMsg = '\n\t' + '\n\t'.join( lines ) + '\n'
raise SystemExit( "\033[1m%s\033[0m\n" % finalMsg )
def tryImport( modules ):
"""
Checks that the provided modules can be imported.
Stops with a message to the user if some are not found.
"""
import importlib
import six
if Any.isText( modules ):
modules = [ modules ]
Any.requireIsIterable( modules )
notFound = set()
for moduleName in modules:
Any.requireIsTextNonEmpty( moduleName )
if six.PY2:
errorClass = ImportError
else:
errorClass = ModuleNotFoundError
try:
importlib.import_module( moduleName )
except errorClass:
notFound.add( moduleName )
if notFound:
raise SystemExit( 'Python module(s) not installed: %s' % \
' '.join( sorted( notFound ) ) )
#----------------------------------------------------------------------------
# Private functions
#----------------------------------------------------------------------------
def _getTreeChar( searchList, index ):
Any.requireIsList( searchList )
lastStringIndex = _getLastStringInList( searchList )
if index < lastStringIndex:
treeChar = '|'
elif index == lastStringIndex:
treeChar = '`'
else:
treeChar = ' '
return treeChar
def _getLastStringInList( searchList ):
Any.requireIsList( searchList )
index = 0
for i in range( 0, len(searchList) ):
if isinstance( searchList[i], str ):
index = i
return index
# EOF
|
hyller/GladiatorLibrary | D4D/eGUI/D4D/common_files/d4d_font.h | <gh_stars>1-10
/**************************************************************************
*
* Copyright 2014 by <NAME>. eGUI Community.
* Copyright 2009-2013 by <NAME>. Freescale Semiconductor, Inc.
*
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License Version 3
* or later (the "LGPL").
*
* As a special exception, the copyright holders of the eGUI project give you
* permission to link the eGUI sources with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library.
* If you modify the eGUI sources, you may extend this exception
* to your version of the eGUI sources, but you are not obligated
* to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
***************************************************************************//*!
*
* @file d4d_font.h
*
* @author <NAME>
*
* @version 0.0.35.0
*
* @date Oct-2-2013
*
* @brief D4D Driver fonts header file
*
*******************************************************************************/
#ifndef __D4D_FONT_H
#define __D4D_FONT_H
/******************************************************************************
* Includes
******************************************************************************/
/******************************************************************************
* D4D FONTS setting constants
*
*//*! @addtogroup doxd4d_font_const
* @{
*******************************************************************************/
/*! @brief This macro is used to enable external fonts resource support.
If not defined, the external font resource support is disabled as a default.*/
#ifndef D4D_FNT_EXTSRC_SUPPORT
#define D4D_FNT_EXTSRC_SUPPORT D4D_FALSE
#endif
/*! @} End of doxd4d_font_const */
/******************************************************************************
* D4D FONTS types
*
*//*! @addtogroup doxd4d_font_type
* @{
*******************************************************************************/
/*!
@defgroup doxd4d_font_type_underline D4D FONT Defines masks of underline properties
This section specifies masks of underline properties.
@ingroup doxd4d_font_type
*/
/**
* @addtogroup doxd4d_font_type_underline
* @{
*/
/*! @brief Font Underline property masks*/
#define D4D_FNT_PRTY_UNDERLINE_MASK (0x03) ///< Underline Property mask
#define D4D_FNT_PRTY_UNDERLINE_NONE_MASK (0x00) ///< None Underline Text Property mask
#define D4D_FNT_PRTY_UNDERLINE_LINE_MASK (0x01) ///< One Line Underline Text Property mask
#define D4D_FNT_PRTY_UNDERLINE_DOT_MASK (0x02) ///< Dot Line Underline Text Property mask
#define D4D_FNT_PRTY_UNDERLINE_RES_MASK (0x03) ///< Reserved - Underline Text Property mask
/* @} */
/*!
@defgroup doxd4d_font_type_strikethrough D4D FONT Defines masks of strike through properties
This section specifies masks of strike through properties.
@ingroup doxd4d_font_type
*/
/**
* @addtogroup doxd4d_font_type_strikethrough
* @{
*/
/*! @brief Font Strike through property masks*/
#define D4D_FNT_PRTY_STRIKETHROUGH_MASK (0x0C) ///< Strike Through Property mask
#define D4D_FNT_PRTY_STRIKETHROUGH_NONE_MASK (0x00) ///< None Strike Through Text Property mask
#define D4D_FNT_PRTY_STRIKETHROUGH_SINGLE_MASK (0x04) ///< One Line Strike Through Text Property mask
#define D4D_FNT_PRTY_STRIKETHROUGH_DOUBLE_MASK (0x08) ///< Two Lines Strike Through Text Property mask
#define D4D_FNT_PRTY_STRIKETHROUGH_TRIPLE_MASK (0x0C) ///< Three Lines Strike Through Text Property mask
#define D4D_FNT_PRTY_STRIKETHROUGH_SHIFT (0x02) ///< Strike through property bits shift
/* @} */
#define D4D_FNT_PRTY_TRANSPARENT_MASK (0x10)
#define D4D_FNT_PRTY_TRANSPARENT_NO_MASK (0x00)
#define D4D_FNT_PRTY_TRANSPARENT_YES_MASK (0x10)
typedef Byte D4D_FONT_PROPERTIES;
/*! @} End of doxd4d_font_type */
/******************************************************************************
* Internal types
******************************************************************************/
#define D4D_FONT_PACK_BITORDER 0x01
#define D4D_FONT_PACK_BITORDER_BIGEND 0
#define D4D_FONT_PACK_BITORDER_LITTLEEND 0x01
#define D4D_FONT_PACK_SCANBASED 0x02
#define D4D_FONT_PACK_SCANBASED_ROW 0
#define D4D_FONT_PACK_SCANBASED_COLUMN 0x02
#define D4D_FONT_PACK_SCANPREFERRED 0x04
#define D4D_FONT_PACK_SCANPREFERRED_ROW 0
#define D4D_FONT_PACK_SCANPREFERRED_COLUMN 0x04
#define D4D_FONT_PACK_COMPRESSED 0x08
#define D4D_FONT_PACK_COMPRESSED_OFF 0
#define D4D_FONT_PACK_COMPRESSED_ON 0x08
#define D4D_FONT_PACK_DATA_LEN 0x030
#define D4D_FONT_PACK_DATA_LEN_8B 0x00
#define D4D_FONT_PACK_DATA_LEN_16B 0x10
#define D4D_FONT_PACK_DATA_LEN_32B 0x20
#define D4D_FONT_FLAGS_IX_STYLE 0x01
#define D4D_FONT_FLAGS_IX_STYLE_LINEAR 0x00
#define D4D_FONT_FLAGS_IX_STYLE_NONLINEAR 0x01
#define D4D_FONT_FLAGS_IX_TYPE 0x02
#define D4D_FONT_FLAGS_IX_TYPE_LOOKUP 0x00
#define D4D_FONT_FLAGS_IX_TYPE_MAP 0x02
#define D4D_FONT_FLAGS_FNT_WIDTH 0x04
#define D4D_FONT_FLAGS_FNT_WIDTH_MONOSPACE 0x00
#define D4D_FONT_FLAGS_FNT_WIDTH_PROPORTIONAL 0x04
typedef Byte D4D_FONT_PACK;
typedef Byte D4D_FONT_FLAGS;
#ifdef D4D_UNICODE
typedef D4D_TCHAR D4D_FONT_IX;
typedef Word D4D_FONT_REV;
#else
typedef Byte D4D_FONT_IX;
typedef Byte D4D_FONT_REV;
#endif
typedef Word D4D_FONT_OFFSET;
typedef Byte D4D_FONT_DATA;
typedef Byte D4D_FONT;
typedef Byte D4D_FONT_SIZE;
typedef Word D4D_FONT_DSIZE;
#pragma pack (push)
#pragma pack (1)
typedef struct
{
D4D_FONT_SIZE width;
D4D_FONT_SIZE height;
}D4D_FONT_SIZES;
typedef struct D4D_FONT_DESCRIPTOR_S
{
D4D_FONT_REV revision; //1 Font descriptor version number
D4D_FONT_FLAGS flags; //1 linear / non linear , proporcional or not,
D4D_FONT_IX startChar; //2/1 start char of used table
D4D_FONT_IX charCnt; //2/1 end char of used table
D4D_FONT_IX charDefault; //2/1 index of char that will be printed instead of
D4D_FONT_SIZE charSize; //1 Font size (size of font loaded in PC)
D4D_FONT_DSIZE charBmpSize; //2 Size of font bitmpap for non proportional fonts
D4D_FONT_SIZE charBaseLine; //1 offset from Y0 coordinate to baseline
D4D_FONT_SIZES charFullSize; //2 size of biggest char x/y
D4D_FONT_PACK pack; //1 packing condition of individual bitmaps 15
const D4D_FONT_IX *pIxTable; // Index table - is used when nonlinearIX is set in flags, flags also determine the type of IxTable
const D4D_FONT_OFFSET *pOffTable; // Offset table - used when proporcial font is set in flags
const D4D_FONT_SIZE *pSizeTable; // Size table - used when proporcial font is set in flags
const D4D_FONT_DATA *pFontData; // bitmap/font data array
const struct D4D_FONT_DESCRIPTOR_S* pNext; // pointer on next page for this font (used in unicode)
}D4D_FONT_DESCRIPTOR;
#pragma pack (pop)
typedef struct
{
D4D_FONT ix_font;
D4D_FONT_DESCRIPTOR* pFontDescriptor;
D4D_FONT_SIZES scale; // the scale of the font in both axes values must be > 0
D4D_FONT_SIZES charSpacing; // increment for finest cell in x/y to provide line/char spacing
D4D_CHAR* fileName;
}D4D_FONT_TYPE;
typedef struct{
D4D_COOR x;
D4D_COOR y;
D4D_TCHAR* pText;
D4D_FONT_TYPE* pFontType;
D4D_TAB* pTab;
D4D_COLOR colorText;
D4D_COLOR colorBack;
D4D_FONT_PROPERTIES properties;
D4D_INDEX textLength;
D4D_INDEX textOffset;
D4D_COOR maxWidth;
}D4D_PRINT_DESC;
/******************************************************************************
* Macros
******************************************************************************/
#define D4D_DECLARE_USR_FONT_TABLE_BEGIN(name) const D4D_FONT_TYPE name[] = {
#define D4D_DECLARE_FONT_TABLE_BEGIN D4D_DECLARE_USR_FONT_TABLE_BEGIN(d4d_FontTable)
#define D4D_DECLARE_FONT(fontId, font_descriptor, xScale, yScale, charSpace, lineSpace) \
{fontId, (D4D_FONT_DESCRIPTOR*)&(font_descriptor), { xScale, yScale }, { charSpace, lineSpace }, NULL}, // font info will be replaced by font descriptor
#define D4D_DECLARE_FONT_FILE(fontId, fileName, xScale, yScale, charSpace, lineSpace) \
{fontId, NULL, { xScale, yScale }, { charSpace, lineSpace }, fileName}, // font info will be replaced by font descriptor
#define D4D_DECLARE_FONT_TABLE_END {0, NULL, {0, 0}, {0, 0}, NULL } };
/******************************************************************************
* Global variables
******************************************************************************/
extern const D4D_FONT_TYPE d4d_FontTable[];
/******************************************************************************
* Global functions
******************************************************************************/
void D4D_SetFontTable(D4D_FONT_TYPE* pFontTable);
D4D_FONT_TYPE* D4D_GetFontTable(void);
D4D_FONT_TYPE* D4D_GetFont(D4D_FONT ix);
D4D_FONT_SIZES D4D_GetFontSize(D4D_FONT ix);
D4D_FONT_SIZE D4D_GetFontHeight(D4D_FONT ix);
D4D_FONT_SIZE D4D_GetFontWidth(D4D_FONT ix);
D4D_FONT_SIZE D4D_GetCharWidth(D4D_FONT ix, D4D_TCHAR ch);
D4D_TCHAR D4D_GetChar(D4D_FONT_TYPE* pFontType, D4D_FONT_IX ix);
D4D_COOR D4D_GetNextTab(D4D_TAB* pTab, D4D_COOR pos);
#if D4D_EXTSRC_FILE_ENABLE != D4D_FALSE
D4D_BOOL D4D_ExtFntInit(void);
void D4D_ExtFntSetWorkPath(D4D_CHAR* pPath);
D4D_CHAR* D4D_ExtFntGetWorkPath(void);
D4D_FILEPTR D4D_OpenFntFile(D4D_CHAR* pFileName);
#endif
#endif /* __D4D_FONT_H */
|
Aurelia-io-fr/ghost-aurelia | src/posts/posts.js | export class Posts {
}
|
foundersandcoders/OTP_Data_Entry | src/otp_sdk/index.js | <filename>src/otp_sdk/index.js
module.exports.events = require('./events.js');
module.exports.places = require('./places.js');
module.exports.auth = {
getRefreshToken: require('./get_refresh_token.js'),
};
|
ploki/aws-sdk-cpp | aws-cpp-sdk-codecommit/include/aws/codecommit/model/PostCommentReplyRequest.h | <gh_stars>1-10
/*
* 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/codecommit/CodeCommit_EXPORTS.h>
#include <aws/codecommit/CodeCommitRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
#include <aws/core/utils/UUID.h>
namespace Aws
{
namespace CodeCommit
{
namespace Model
{
/**
*/
class AWS_CODECOMMIT_API PostCommentReplyRequest : public CodeCommitRequest
{
public:
PostCommentReplyRequest();
// 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 "PostCommentReply"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline const Aws::String& GetInReplyTo() const{ return m_inReplyTo; }
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline void SetInReplyTo(const Aws::String& value) { m_inReplyToHasBeenSet = true; m_inReplyTo = value; }
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline void SetInReplyTo(Aws::String&& value) { m_inReplyToHasBeenSet = true; m_inReplyTo = std::move(value); }
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline void SetInReplyTo(const char* value) { m_inReplyToHasBeenSet = true; m_inReplyTo.assign(value); }
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline PostCommentReplyRequest& WithInReplyTo(const Aws::String& value) { SetInReplyTo(value); return *this;}
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline PostCommentReplyRequest& WithInReplyTo(Aws::String&& value) { SetInReplyTo(std::move(value)); return *this;}
/**
* <p>The system-generated ID of the comment to which you want to reply. To get
* this ID, use <a>GetCommentsForComparedCommit</a> or
* <a>GetCommentsForPullRequest</a>.</p>
*/
inline PostCommentReplyRequest& WithInReplyTo(const char* value) { SetInReplyTo(value); return *this;}
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline const Aws::String& GetClientRequestToken() const{ return m_clientRequestToken; }
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline void SetClientRequestToken(const Aws::String& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = value; }
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline void SetClientRequestToken(Aws::String&& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = std::move(value); }
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline void SetClientRequestToken(const char* value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken.assign(value); }
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline PostCommentReplyRequest& WithClientRequestToken(const Aws::String& value) { SetClientRequestToken(value); return *this;}
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline PostCommentReplyRequest& WithClientRequestToken(Aws::String&& value) { SetClientRequestToken(std::move(value)); return *this;}
/**
* <p>A unique, client-generated idempotency token that when provided in a request,
* ensures the request cannot be repeated with a changed parameter. If a request is
* received with the same parameters and a token is included, the request will
* return information about the initial request that used that token.</p>
*/
inline PostCommentReplyRequest& WithClientRequestToken(const char* value) { SetClientRequestToken(value); return *this;}
/**
* <p>The contents of your reply to a comment.</p>
*/
inline const Aws::String& GetContent() const{ return m_content; }
/**
* <p>The contents of your reply to a comment.</p>
*/
inline void SetContent(const Aws::String& value) { m_contentHasBeenSet = true; m_content = value; }
/**
* <p>The contents of your reply to a comment.</p>
*/
inline void SetContent(Aws::String&& value) { m_contentHasBeenSet = true; m_content = std::move(value); }
/**
* <p>The contents of your reply to a comment.</p>
*/
inline void SetContent(const char* value) { m_contentHasBeenSet = true; m_content.assign(value); }
/**
* <p>The contents of your reply to a comment.</p>
*/
inline PostCommentReplyRequest& WithContent(const Aws::String& value) { SetContent(value); return *this;}
/**
* <p>The contents of your reply to a comment.</p>
*/
inline PostCommentReplyRequest& WithContent(Aws::String&& value) { SetContent(std::move(value)); return *this;}
/**
* <p>The contents of your reply to a comment.</p>
*/
inline PostCommentReplyRequest& WithContent(const char* value) { SetContent(value); return *this;}
private:
Aws::String m_inReplyTo;
bool m_inReplyToHasBeenSet;
Aws::String m_clientRequestToken;
bool m_clientRequestTokenHasBeenSet;
Aws::String m_content;
bool m_contentHasBeenSet;
};
} // namespace Model
} // namespace CodeCommit
} // namespace Aws
|
metaflow/contests | atcoder/agc041/b.cc | #if defined(LOCAL)
const double _max_double_error = 1e-9;
#include "testutils.h"
#define L(x...) (debug(x, #x))
#define I(x, ...) (x)
#define C(x...) CHECK(x)
#else
#define L(x, ...) (x)
#define I(x, ...) (x)
#define C(x, ...) ;
#endif
#include <math.h>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using ii = pair<int, int>;
using lu = unsigned long long;
using l = long long;
using vs = vector<string>;
using vii = vector<ii>;
using vl = vector<l>;
using vvl = vector<vl>;
using vvvl = vector<vvl>;
using vlu = vector<lu>;
using ll = pair<l, l>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvvb = vector<vvb>;
using vd = vector<double>;
using vvd = vector<vd>;
using mll = unordered_map<l, l>;
using sl = unordered_set<l>;
const l INF = numeric_limits<l>::max();
const double EPS = 1e-10;
const double PI = 3.14159265358979323846;
const l e0 = 1, e3 = 1000, e5 = 100000, e6 = 10 * e5, e7 = 10 * e6,
e8 = 10 * e7, e9 = 10 * e8, l0 = 0, l1 = 1, l2 = 2;
const char lf = '\n';
#define all(x) begin(x), end(x)
#define F(a, b, c) for (l a = l(b); a < l(c); a++)
#define B(a, b, c) for (l a = l(c) - 1; a >= l(b); a--)
void solve(istream &in, ostream &out);
void solve_brute(istream &, ostream &);
bool interactive_judge(istream &, istream &, ostream &);
bool generate_random(l, ostream &);
bool solution_checker(istream &, istream &, istream &, ostream &);
int main(int argc, char **argv) {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(15);
#if defined(LOCAL)
tst::test_init(argc, argv);
// _generate_random_test = generate_random;
// _solve_brute = solve_brute;
// _judge = interactive_judge;
// _custom_solution_checker = solution_checker;
tst::maybe_run_tests(cin, cout);
#else
solve(cin, cout);
#endif
}
const l MOD = e9 + 7; // end of template
// finds lowest x: f(x) = true, x within [a, b), b if f(b - 1) = false
l binary_search_lower(l a, l b, function<bool(l)> f) {
l count = b - a;
while (count > 0) {
l step = count / 2;
l m = a + step;
if (f(m)) {
count = step;
} else {
a = m + 1;
count -= step + 1;
}
}
return a;
}
// max x for f transition f(a) = 1, f(b) = 0, (a, b]
l binary_search_upper(l a, l b, function<bool(l)> f) {
return b - binary_search_lower(0, b - a, [&](l x) { return f(b - x); });
}
// finds lowest x: f(x) = true, x within [a, b)
double binary_search_lower_double(double a, double b,
function<bool(double)> f) {
double diff = b - a;
while (diff > EPS) {
diff /= 2;
double m = a + diff;
if (!f(m)) a = m;
}
return a;
}
void solve(istream &in, ostream &out) {
l n, m, votes, picks;
in >> n >> m >> votes >> picks;
vl v(n);
F(i, 0, n) in >> v[i];
sort(all(v));
reverse(all(v));
F(i, 0, picks - 1) v[i] += m;
l left = m * (votes - picks);
L(v, left);
l z = binary_search_upper(0, n - 1, [&](l x) {
if (x < picks) return true;
l t = v[x] + m;
L(t, x);
if (t < v[picks - 1]) return false;
l sum = 0;
F(i, picks - 1, n) {
if (i == x) continue;
sum += max(min(m, t - v[i]), l0);
}
return sum >= left;
});
out << z + 1 << lf;
}
|
Neuron64/ftpclient | data/src/main/java/com/neuron64/ftp/data/exception/ErrorMappingUnavailable.java | package com.neuron64.ftp.data.exception;
/**
* Created by yks-11 on 10/16/17.
*/
public class ErrorMappingUnavailable extends Error{
}
|
lunelson/ln-js | _beta/bricks/gulpfile.js | // imports
const json = require('./package.json')
const sync = require('browser-sync')
const del = require('del')
const fs = require('fs')
const gulp = require('gulp')
const notifier = require('node-notifier')
const rollup = require('rollup')
const babel = require('rollup-plugin-babel')
const commonjs = require('rollup-plugin-commonjs')
const resolve = require('rollup-plugin-node-resolve')
const uglify = require('rollup-plugin-uglify')
// error handler
const onError = function(error) {
notifier.notify({
'title': 'Error',
'message': 'Compilation failure.'
})
console.log(error)
this.emit('end')
}
// clean
gulp.task('clean', () => del('dist'))
// attribution
const attribution =
`/*!
* Bricks.js ${ json.version } - ${ json.description }
* Copyright (c) ${ new Date().getFullYear() } ${ json.author } - ${ json.homepage }
* License: ${ json.license }
*/
`
// js
const read = {
entry: 'src/bricks.js',
sourceMap: true,
plugins: [
resolve({ jsnext: true }),
babel(),
uglify()
]
}
const write = {
format: 'umd',
exports: 'default',
moduleName: 'Bricks',
sourceMap: true
}
gulp.task('js', () => {
return rollup
.rollup(read)
.then(bundle => {
// generate the bundle
const files = bundle.generate(write)
// cache path to JS dist file
const dist = 'dist/bricks.min.js'
// write the attribution
fs.writeFileSync(dist, attribution)
// write the JS and sourcemap
fs.appendFileSync(dist, files.code)
fs.writeFileSync('dist/maps/bricks.js.map', files.map.toString())
})
})
// server
const server = sync.create()
const reload = sync.reload
const sendMaps = (req, res, next) => {
const filename = req.url.split('/').pop()
const extension = filename.split('.').pop()
if(extension === 'css' || extension === 'js') {
res.setHeader('X-SourceMap', '/maps/' + filename + '.map')
}
return next()
}
const options = {
notify: false,
server: {
baseDir: 'dist',
middleware: [
sendMaps
]
},
watchOptions: {
ignored: '*.map'
}
}
gulp.task('server', () => sync(options))
// watch
gulp.task('watch', () => {
gulp.watch('src/bricks.js', ['js', reload])
})
// build and default tasks
gulp.task('build', ['clean'], () => {
// create dist directories
fs.mkdirSync('dist')
fs.mkdirSync('dist/maps')
// run the tasks
gulp.start('js')
})
gulp.task('default', ['build', 'server', 'watch'])
|
emeitch/Lay | src/func.js | import { Func, Native, LiftedNative } from './case';
// defined by case for anti cyclic referencing
export default Func;
export { Native, LiftedNative };
export const func = Func.func.bind(Func);
export const plus = func("x", "y", (x, y) => x + y);
export const concat = func("a", "b", (a, b) => `${a}${b}`);
|
seckcoder/lang-learn | python/sklearn/examples/exercises/plot_iris_exercise.py | <filename>python/sklearn/examples/exercises/plot_iris_exercise.py<gh_stars>1-10
"""
================================
SVM Exercise
================================
This exercise is used in the :ref:`using_kernels_tut` part of the
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
"""
print __doc__
import numpy as np
import pylab as pl
from sklearn import datasets, svm
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y != 0, :2]
y = y[y != 0]
n_sample = len(X)
np.random.seed(0)
order = np.random.permutation(n_sample)
X = X[order]
y = y[order].astype(np.float)
X_train = X[:.9 * n_sample]
y_train = y[:.9 * n_sample]
X_test = X[.9 * n_sample:]
y_test = y[.9 * n_sample:]
# fit the model
for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')):
clf = svm.SVC(kernel=kernel, gamma=10)
clf.fit(X_train, y_train)
pl.figure(fig_num)
pl.clf()
pl.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=pl.cm.Paired)
# Circle out the test data
pl.scatter(X_test[:, 0], X_test[:, 1],
s=80, facecolors='none', zorder=10)
pl.axis('tight')
x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max()
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# Put the result into a color plot
Z = Z.reshape(XX.shape)
pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired)
pl.contour(XX, YY, Z, colors=['k', 'k', 'k'],
linestyles=['--', '-', '--'],
levels=[-.5, 0, .5])
pl.title(kernel)
pl.show()
|
Fedict/fts-gui-sign | src/modules/signWizard/actions/SignatureActions.test.js | <gh_stars>1-10
import { setSignature, SIGNATURE_SET_SIGNATURE } from "./SignatureActions"
describe('SignatureActions', () => {
describe('setSignature', () => {
test('setSignature returns action with type SIGNATURE_SET_SIGNATURE and payload signature', () => {
const payload = { signature: "test" }
const result = setSignature(payload)
expect(result.type).toBe(SIGNATURE_SET_SIGNATURE)
expect(result.payload).toEqual(payload.signature)
})
})
}) |
DekusDenial/framework | packages/data/app/models/navi-dimension.js | export { default } from 'navi-data/models/navi-dimension';
|
VVKot/leetcode-solutions | leetcode/python/36_valid_sudoku.py | <filename>leetcode/python/36_valid_sudoku.py
from typing import List
class Solution:
def check_row(self, board: List[List[str]], i: int, j: int):
val = board[i][j]
for k in range(9):
if k == i:
continue
if board[k][j] == val:
return False
return True
def check_col(self, board: List[List[str]], i: int, j: int):
val = board[i][j]
for k in range(9):
if k == j:
continue
if board[i][k] == val:
return False
return True
def check_square(self, board: List[List[str]], i: int, j: int):
val = board[i][j]
row = i // 3
col = j // 3
for y in range(3*row, 3*(row+1)):
for x in range(3*col, 3*(col+1)):
if y == i and x == j:
continue
if board[y][x] == val:
return False
return True
def isValidSudoku(self, board: List[List[str]]) -> bool:
for y, row in enumerate(board):
for x, ch in enumerate(row):
if ch == '.':
continue
valid = True
valid &= self.check_row(board, y, x)
valid &= self.check_col(board, y, x)
valid &= self.check_square(board, y, x)
if not valid:
return False
return True
|
jairvelazquez/League-the-Logs | models/TopPlayersModels.js | const mongoose = require('mongoose');
const TopPlayersSchema = mongoose.Schema({
summoner_id: {type:String,required:true},
summoner_name: {type:String,required:true},
server: {type:String,required:true},
rank: {type:String,required:true},
division: {type:String,required:true},
position: {type:String,required:true}
});
module.exports = mongoose.model('TopPlayersModels', TopPlayersSchema); |
zhangkn/iOS14Header | Applications/CarPlaySettings/CARSettingsImageCache.h | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@interface CARSettingsImageCache : NSObject
{
}
+ (id)imageForColor:(id)arg1 size:(struct CGSize)arg2; // IMP=0x0000000100002380
+ (id)imageForKey:(id)arg1; // IMP=0x0000000100002300
+ (id)iconImageCache; // IMP=0x000000010000226c
+ (id)internalImage; // IMP=0x0000000100002184
+ (id)albumArtImage; // IMP=0x000000010000209c
+ (id)siriImage; // IMP=0x0000000100001fb4
+ (id)wallpaperImage; // IMP=0x0000000100001ecc
+ (id)appearanceImage; // IMP=0x0000000100001de4
+ (id)displayImage; // IMP=0x0000000100001cfc
+ (id)dndImage; // IMP=0x0000000100001c14
+ (id)checkmark; // IMP=0x0000000100001b60
+ (id)rightChevron; // IMP=0x0000000100001a84
+ (id)leftChevron; // IMP=0x00000001000019d0
@end
|
domenic/mojo | gpu/command_buffer/service/transfer_buffer_manager.cc | <gh_stars>1-10
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/transfer_buffer_manager.h"
#include <limits>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/debug/trace_event.h"
#include "base/process/process_handle.h"
#include "gpu/command_buffer/common/cmd_buffer_common.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
using ::base::SharedMemory;
namespace gpu {
TransferBufferManagerInterface::~TransferBufferManagerInterface() {
}
TransferBufferManager::TransferBufferManager()
: shared_memory_bytes_allocated_(0) {
}
TransferBufferManager::~TransferBufferManager() {
while (!registered_buffers_.empty()) {
BufferMap::iterator it = registered_buffers_.begin();
DCHECK(shared_memory_bytes_allocated_ >= it->second->size());
shared_memory_bytes_allocated_ -= it->second->size();
registered_buffers_.erase(it);
}
DCHECK(!shared_memory_bytes_allocated_);
}
bool TransferBufferManager::Initialize() {
return true;
}
bool TransferBufferManager::RegisterTransferBuffer(
int32 id,
scoped_ptr<BufferBacking> buffer_backing) {
if (id <= 0) {
DVLOG(0) << "Cannot register transfer buffer with non-positive ID.";
return false;
}
// Fail if the ID is in use.
if (registered_buffers_.find(id) != registered_buffers_.end()) {
DVLOG(0) << "Buffer ID already in use.";
return false;
}
// Register the shared memory with the ID.
scoped_refptr<Buffer> buffer(new gpu::Buffer(buffer_backing.Pass()));
// Check buffer alignment is sane.
DCHECK(!(reinterpret_cast<uintptr_t>(buffer->memory()) &
(kCommandBufferEntrySize - 1)));
shared_memory_bytes_allocated_ += buffer->size();
TRACE_COUNTER_ID1(
"gpu", "GpuTransferBufferMemory", this, shared_memory_bytes_allocated_);
registered_buffers_[id] = buffer;
return true;
}
void TransferBufferManager::DestroyTransferBuffer(int32 id) {
BufferMap::iterator it = registered_buffers_.find(id);
if (it == registered_buffers_.end()) {
DVLOG(0) << "Transfer buffer ID was not registered.";
return;
}
DCHECK(shared_memory_bytes_allocated_ >= it->second->size());
shared_memory_bytes_allocated_ -= it->second->size();
TRACE_COUNTER_ID1(
"gpu", "GpuTransferBufferMemory", this, shared_memory_bytes_allocated_);
registered_buffers_.erase(it);
}
scoped_refptr<Buffer> TransferBufferManager::GetTransferBuffer(int32 id) {
if (id == 0)
return NULL;
BufferMap::iterator it = registered_buffers_.find(id);
if (it == registered_buffers_.end())
return NULL;
return it->second;
}
} // namespace gpu
|
AnmolMaharjan/python-level1 | projects/project_03/school_manager/school.py | import json
from typing import List
from utils import clear_screen, display_message, RECORD_PATH
class Student:
def __init__(self, name: str, roll: int, age: int, major: str) -> None:
self.name = name
self.roll = roll
self.age = age
self.major = major
def show_menu(self):
print('Student Management Screen')
def modify(self) -> bool:
clear_screen()
changed = False
print(f'[ Modifying "{self.name}" ]'.center(80, '='), end='\n\n')
name = input(f"Enter New name [Enter to set {self.name}]")
if name.__len__():
self.name = name
changed=True
roll = input(f"Enter New name [Enter to set {self.roll}]")
if roll.__len__():
self.roll = int(roll)
changed=True
age = input(f"Enter New name [Enter to set {self.age}]")
if age.__len__():
self.age = int(age)
changed=True
major = input(f"Enter New name [Enter to set {self.major}]")
if major.__len__():
self.major = major
changed=True
return changed
class ClassRoom:
message = ''
def __init__(self, name) -> None:
self.name = name
self.__students: List[Student] = []
def load_record(self, students: list):
for std in students:
self.__students.append(Student(**std))
def save_record(self):
with open(f"{RECORD_PATH}/{self.name}.json", 'w', encoding='utf-8') as file:
json.dump({'name': self.name, 'students': [s.__dict__ for s in self.__students]}, file, indent=2)
def _rename(self):
self.message = 'This feature is unimplemented'
def _list_students(self):
clear_screen()
print(f'[ Class "{self.name}" Student ]'.center(80, '='), end='\n\n')
print('+', '-' * 6, '+', '-' * 32, '+', '-' * 5, '+', '-' * 17, '+', sep='')
print(f"| {'Roll':4s} | {'Name'.center(30)} | {'Age':3s} | {'Major'.center(15)} |")
print('+', '-' * 6, '+', '-' * 32, '+', '-' * 5, '+', '-' * 17, '+', sep='')
for std in self.__students:
print(f"| {std.roll:4d} | {std.name:30s} | {std.age:3d} | {std.major:15s} |")
print('+', '-' * 6, '+', '-' * 32, '+', '-' * 5, '+', '-' * 17, '+', sep='')
input("\nPress Enter to go back: ")
def _add_student(self):
self.message = ''
clear_screen()
print('[ Adding Student ]'.center(80, '='))
try:
std = Student(
name=input("Enter Student name: "),
roll=int(input("Enter Student roll: ")),
age=int(input("Enter Student age: ")),
major=input("Enter Student major: "),
)
self.__students.append(std)
self.save_record()
self.message = f'Student "{std.name}" successfully added'
except ValueError:
self.message = 'invalid data entered'
def _remove_student(self):
try:
roll: int = int(input("Enter the roll number of a student to remove from the class: "))
students_count = self.__students.__len__()
self.__students = [s for s in self.__students if s.roll != roll]
if students_count == self.__students.__len__():
self.message = f'No student with roll "{roll}" found'
return
self.save_record()
self.message = 'student successfully removed'
except (ValueError, IndexError):
self.message = 'Invalid Option Supplied'
def _modify_student(self):
try:
roll: int = int(input("Enter the roll number of a student to modify: "))
student = [s for s in self.__students if s.roll == roll][0]
success = student.modify()
if success:
self.save_record()
self.message = 'student successfully updated'
else:
self.message = "No Changes were made"
except (ValueError, IndexError):
self.message = 'Student not found'
def show_menu(self):
menu_items = {
'1': {
'title': 'Rename the class',
'action': self._rename
},
'2': {
'title': 'List Students',
'action': self._list_students
},
'3': {
'title': 'Add Student',
'action': self._add_student
},
'4': {
'title': 'Remove Student',
'action': self._remove_student
},
'5': {
'title': 'Modify Student',
'action': self._modify_student
},
'0': {
'title': 'Go to Previous Menu'
}
}
clear_screen()
self.message = ''
while True:
clear_screen()
print(f'[ Managing class {self.name} ]'.center(80, '='))
for k, v in menu_items.items():
print(f'{k}: {v["title"]}')
if self.message.__len__() > 0:
display_message(self.message)
try:
option = input("\nPlease select an option: ")
if option == '0':
return
menu_items[option]['action']()
except (KeyError, ValueError):
self.message = "Invalid option supplied"
|
dev-rbatista/Tutorial_Local_Smoke_Test_with_Docker_Containers-Gradle | src/test/java/switchtwentytwenty/project/interfaceadapters/controller/implcontrollers/FamilyRESTControllerTest.java | <gh_stars>0
package switchtwentytwenty.project.interfaceadapters.controller.implcontrollers;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import switchtwentytwenty.project.dto.OptionsDTO;
import switchtwentytwenty.project.dto.assemblers.implassemblers.CategoryInputDTOAssembler;
import switchtwentytwenty.project.dto.assemblers.implassemblers.FamilyInputDTOAssembler;
import switchtwentytwenty.project.dto.assemblers.implassemblers.PersonInputDTOAssembler;
import switchtwentytwenty.project.dto.assemblers.implassemblers.RelationInputDTOAssembler;
import switchtwentytwenty.project.dto.category.CreateCategoryDTO;
import switchtwentytwenty.project.dto.category.InputCustomCategoryDTO;
import switchtwentytwenty.project.dto.category.OutputCategoryDTO;
import switchtwentytwenty.project.dto.category.OutputCategoryTreeDTO;
import switchtwentytwenty.project.dto.family.*;
import switchtwentytwenty.project.dto.person.InputPersonDTO;
import switchtwentytwenty.project.exceptions.InvalidEmailException;
import switchtwentytwenty.project.usecaseservices.applicationservices.iappservices.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@ExtendWith(MockitoExtension.class)
class FamilyRESTControllerTest {
AddFamilyAndSetAdminDTO dto = new AddFamilyAndSetAdminDTO("<EMAIL>", "Silva", "12/12/1222", 999999999, 919999999, "Rua", "Cidade", "12B", "4400-123", "password", "<PASSWORD>", "12/12/2000");
AddFamilyAndSetAdminDTO invaliddto = new AddFamilyAndSetAdminDTO("<EMAIL>", "Silva", "12/12/1222", 999999999, 919999999, "Rua", "Cidade", "12B", "<PASSWORD>", "password", "<PASSWORD>", "12/12/2000");
@Mock
ICreateFamilyService createFamilyService;
@Mock
FamilyInputDTOAssembler familyAssembler;
@Mock
PersonInputDTOAssembler personAssembler;
@Mock
CategoryInputDTOAssembler categoryAssembler;
@Mock
RelationInputDTOAssembler relationAssembler;
@Mock
IGetFamilyDataService getFamilyDataService;
@Mock
IFamiliesOptionsService familiesOptionsService;
@Mock
IGetFamilyMembersAndRelationshipService getFamilyMembersAndRelationshipService;
@Mock
IChangeRelationService changeRelationService;
@Mock
IFamilyOptionsService familyOptionsService;
@Mock
ICreateRelationService createRelationService;
@Mock
IGetCustomCategoriesService getCustomCategoriesService;
@Mock
ICreateCustomCategoryService createCustomCategoryService;
@InjectMocks
FamilyRESTController familyRESTController;
@Test
@DisplayName("CreateFamilyAndSetAdmin function success case")
void createFamilyAndSetAdmin() {
AddFamilyAndSetAdminDTO addFamilyAndSetAdminDTO = new AddFamilyAndSetAdminDTO("<EMAIL>", "TonyZe", "28/12/1990", 123123123, 919999999, "rua", "cidade", "23b", "1234-<PASSWORD>", "password", "Silva", "12/12/1990");
InputPersonDTO inputPersonDTO = new InputPersonDTO("<EMAIL>", "TonyZe", "28/12/1990", 123123123, 919999999, "rua", "cidade", "23b", "1234-123", "password");
InputFamilyDTO inputFamilyDTO = new InputFamilyDTO("Silva", "12/12/1990");
OutputFamilyDTO outputFamilyDTO = new OutputFamilyDTO("Silva", <EMAIL>", "<EMAIL>", "12/12/1990");
when(personAssembler.toInputPersonDTO(any(AddFamilyAndSetAdminDTO.class))).thenReturn(inputPersonDTO);
when(familyAssembler.toInputFamilyDTO(any(AddFamilyAndSetAdminDTO.class))).thenReturn(inputFamilyDTO);
when(createFamilyService.createFamilyAndAddAdmin(any(), any())).thenReturn(outputFamilyDTO);
// Expected
OutputFamilyDTO expectedOutputDTO = new OutputFamilyDTO("Silva", <EMAIL>", "<EMAIL>", "12/12/1990");
Link expectedLink = linkTo(methodOn(FamilyRESTController.class).getFamily(outputFamilyDTO.getFamilyID())).withSelfRel();
expectedOutputDTO.add(expectedLink);
ResponseEntity expected = new ResponseEntity(expectedOutputDTO, HttpStatus.CREATED);
ResponseEntity result = familyRESTController.createFamilyAndSetAdmin(addFamilyAndSetAdminDTO);
assertNotNull(result);
//assertEquals(result.getStatusCode(),HttpStatus.CREATED);
assertEquals(result, expected);
}
@Test
void testCreateFamilyAndSetAdmin() {
InputPersonDTO inputPersonDTO = new InputPersonDTO("<EMAIL>", "TonyZe", "28/12/1990", 123123123, 919999999, "rua", "cidade", "23b", "1234-123", "password");
InputFamilyDTO inputFamilyDTO = new InputFamilyDTO("Silva", "12/12/1990");
when(personAssembler.toInputPersonDTO(any(AddFamilyAndSetAdminDTO.class))).thenReturn(inputPersonDTO);
when(familyAssembler.toInputFamilyDTO(any(AddFamilyAndSetAdminDTO.class))).thenReturn(inputFamilyDTO);
when(createFamilyService.createFamilyAndAddAdmin(any(), any())).thenThrow(InvalidEmailException.class);
ResponseEntity expected = new ResponseEntity("Error: " + null, HttpStatus.UNPROCESSABLE_ENTITY);
ResponseEntity result = familyRESTController.createFamilyAndSetAdmin(invaliddto);
assertEquals(expected.getBody(), result.getBody());
assertEquals(expected.getStatusCode(), result.getStatusCode());
}
@Test
void familiesOptionsTest() {
OptionsDTO optionsDTO = new OptionsDTO();
Link linkToFamilyOptions = linkTo(methodOn(FamilyRESTController.class).familiesOptions()).withSelfRel();
Link linkToAddFamily = linkTo(methodOn(FamilyRESTController.class).createFamilyAndSetAdmin(new AddFamilyAndSetAdminDTO())).withRel("POST - Add new Family");
optionsDTO.add(linkToFamilyOptions);
optionsDTO.add(linkToAddFamily);
when(familiesOptionsService.getFamiliesOptions()).thenReturn(optionsDTO);
OptionsDTO expectedOptionsDTO = new OptionsDTO();
Link expectedLinkToFamilyOptions = linkTo(methodOn(FamilyRESTController.class).familiesOptions()).withSelfRel();
Link expectedLinkToAddFamily = linkTo(methodOn(FamilyRESTController.class).createFamilyAndSetAdmin(new AddFamilyAndSetAdminDTO())).withRel("POST - Add new Family");
expectedOptionsDTO.add(expectedLinkToFamilyOptions);
expectedOptionsDTO.add(expectedLinkToAddFamily);
HttpHeaders header = new HttpHeaders();
header.set("Allow", "POST, OPTIONS");
ResponseEntity expected = new ResponseEntity<>(optionsDTO, header, HttpStatus.OK);
ResponseEntity result = familyRESTController.familiesOptions();
assertEquals(result, expected);
}
@Test
void getFamilyTest() {
OutputFamilyDTO returnedDTO = new OutputFamilyDTO();
OutputFamilyDTO expected = new OutputFamilyDTO();
expected.setFamilyName("Ravens");
expected.setRegistrationDate("01/01/2021");
expected.setFamilyID("@rif<EMAIL>");
expected.setAdminID("<EMAIL>");
expected.add(linkTo(methodOn(FamilyRESTController.class).getFamilyOptions("<EMAIL>")).withSelfRel());
when(getFamilyDataService.getFamilyData("<EMAIL>")).thenReturn(returnedDTO);
ResponseEntity expectedEntity = new ResponseEntity(expected,HttpStatus.OK);
ResponseEntity result = familyRESTController.getFamily("<EMAIL>");
assertEquals(expectedEntity.toString(),result.toString());
}
@Test
void getFamilyOptionsTest() {
String familyID = <EMAIL>";
OptionsDTO options = new OptionsDTO();
Link optionOne = linkTo(methodOn(FamilyRESTController.class).getFamily(familyID)).withSelfRel();
Link optionTwo = linkTo(methodOn(FamilyRESTController.class).createRelation(new CreateRelationDTO(), familyID)).withRel("OPTIONS - relations");
Link optionThree = linkTo(methodOn(FamilyRESTController.class).getCategoriesOptions(familyID)).withRel("OPTIONS - categories");
options.add(optionOne);
options.add(optionTwo);
options.add(optionThree);
when(familyOptionsService.getFamilyOptions(familyID)).thenReturn(options);
// Expected
OptionsDTO exoectedOptions = new OptionsDTO();
Link exoectedOptionOne = linkTo(methodOn(FamilyRESTController.class).getFamily(familyID)).withSelfRel();
Link exoectedOptionTwo = linkTo(methodOn(FamilyRESTController.class).createRelation(new CreateRelationDTO(), familyID)).withRel("OPTIONS - relations");
Link exoectedOptionThree = linkTo(methodOn(FamilyRESTController.class).getCategoriesOptions(familyID)).withRel("OPTIONS - categories");
exoectedOptions.add(exoectedOptionOne);
exoectedOptions.add(exoectedOptionTwo);
exoectedOptions.add(exoectedOptionThree);
HttpHeaders header = new HttpHeaders();
header.set("Allow", "OPTIONS");
ResponseEntity expectedResponse = new ResponseEntity(exoectedOptions, header, HttpStatus.OK);
// Act
ResponseEntity resultResponse = familyRESTController.getFamilyOptions(familyID);
assertEquals(expectedResponse, resultResponse);
}
@Test
void getCategoriesOption() {
assertThrows(UnsupportedOperationException.class, () -> familyRESTController.getCategoriesOptions("<EMAIL>"));
}
@Test
void getCategoriesSuccess() {
String familyID = <EMAIL>";
OutputCategoryTreeDTO expectedOutputCategoryTreeDTO = new OutputCategoryTreeDTO();
Link expectedLink = linkTo(methodOn(FamilyRESTController.class).getCategories(familyID)).withSelfRel();
expectedOutputCategoryTreeDTO.add(expectedLink);
ResponseEntity expected = new ResponseEntity(expectedOutputCategoryTreeDTO, HttpStatus.OK);
when(getCustomCategoriesService.getCustomCategories(any(String.class))).thenReturn(new OutputCategoryTreeDTO());
ResponseEntity result = familyRESTController.getCategories(familyID);
assertEquals(result, expected);
}
@Test
void getCategoriesFail() {
String familyID = <EMAIL>";
ResponseEntity expected = new ResponseEntity("Error: Invalid ID", HttpStatus.BAD_REQUEST);
when(getCustomCategoriesService.getCustomCategories(any(String.class))).thenThrow(new IllegalArgumentException("Invalid ID"));
ResponseEntity result = familyRESTController.getCategories(familyID);
assertEquals(result, expected);
}
@Test
@DisplayName("Create Relation success")
void createRelationSuccessCase() {
CreateRelationDTO createRelationDTO = new CreateRelationDTO("<EMAIL>", "<EMAIL>", "BFF");
String familyID = createRelationDTO.getMemberOneID();
InputRelationDTO inputRelationDTO = new InputRelationDTO(createRelationDTO, "<EMAIL>");
OutputRelationDTO outputRelationDTO = new OutputRelationDTO("tonyze", "katia", "BFF", "3");
Mockito.when(familyAssembler.toInputRelationDTO(any(CreateRelationDTO.class), any(String.class))).thenReturn(inputRelationDTO);
Mockito.when(createRelationService.createRelation(any(InputRelationDTO.class))).thenReturn(outputRelationDTO);
Link optionsLink = linkTo(methodOn(FamilyRESTController.class).getFamilyOptions(familyID)).withSelfRel();
OutputRelationDTO expectedRelationDTO = outputRelationDTO.add(optionsLink);
ResponseEntity expected = new ResponseEntity(expectedRelationDTO, HttpStatus.CREATED);
ResponseEntity result = familyRESTController.createRelation(createRelationDTO, familyID);
assertNotNull(result);
assertEquals(expected, result);
}
@Test
@DisplayName("Create Relation failure")
void createRelationFailureCase() {
InputRelationDTO inputRelationDTO = new InputRelationDTO(null, null, "BFF", "@tony");
CreateRelationDTO createRelationDTO = new CreateRelationDTO(null, null, "BFF");
Mockito.when(familyAssembler.toInputRelationDTO(any(CreateRelationDTO.class), any(String.class))).thenReturn(inputRelationDTO);
Mockito.when(createRelationService.createRelation(any(InputRelationDTO.class))).thenThrow(IllegalArgumentException.class);
ResponseEntity expected = new ResponseEntity("Error: null", HttpStatus.UNPROCESSABLE_ENTITY);
ResponseEntity result = familyRESTController.createRelation(createRelationDTO, "@tony");
assertEquals(expected, result);
}
@Test
@DisplayName("Test for the retrieval of the list of a family members and their relations")
void getFamilyMemberAndRelationsTestValidFamilyID() {
when(getFamilyMembersAndRelationshipService.getFamilyMembersAndRelations(anyString())).thenReturn(new FamilyMemberAndRelationsListDTO());
FamilyMemberAndRelationsListDTO outputDTO = new FamilyMemberAndRelationsListDTO();
Link selfLink = linkTo(methodOn(FamilyRESTController.class).getFamilyMembersAndRelations("<EMAIL>")).withSelfRel();
outputDTO.add(selfLink);
ResponseEntity<FamilyMemberAndRelationsListDTO> expected = new ResponseEntity(outputDTO, HttpStatus.OK);
ResponseEntity<FamilyMemberAndRelationsListDTO> result = familyRESTController.getFamilyMembersAndRelations("<EMAIL>");
assertEquals(expected, result);
}
@Test
@DisplayName("Test for the retrieval of the list of a family members and their relations failing because the family is not registered")
void getFamilyMemberAndRelationsTestFamilyNotRegistered() {
when(getFamilyMembersAndRelationshipService.getFamilyMembersAndRelations(anyString())).thenThrow(IllegalArgumentException.class);
ResponseEntity<FamilyMemberAndRelationsListDTO> expected = new ResponseEntity("Error: null", HttpStatus.BAD_REQUEST);
ResponseEntity<FamilyMemberAndRelationsListDTO> result = familyRESTController.getFamilyMembersAndRelations("<EMAIL>");
assertEquals(expected, result);
}
@Test
@DisplayName("Test for the change of a relation between family members in a Family")
void changeRelationValidRelationInfo() {
String familyID = <EMAIL>";
String relationID = "123";
String relationshipDesignation = "Amante";
ChangeRelationDTO changeRelationDTO = new ChangeRelationDTO();
changeRelationDTO.setNewRelationDesignation(relationshipDesignation);
InputChangeRelationDTO inputChangeRelationDTO = new InputChangeRelationDTO(relationID, relationshipDesignation, familyID);
String memberOneID = "<EMAIL>";
String memberTwoID = "<EMAIL>";
OutputRelationDTO outputRelationDTO = new OutputRelationDTO(memberOneID, memberTwoID, relationshipDesignation, relationID);
Link selfLink = linkTo(methodOn(FamilyRESTController.class).getFamilyMembersAndRelations(familyID)).withSelfRel();
outputRelationDTO.add(selfLink);
when(relationAssembler.toInputChangeRelationDTO(any(ChangeRelationDTO.class), anyString(), anyString())).thenReturn(inputChangeRelationDTO);
when(changeRelationService.changeRelation(any(InputChangeRelationDTO.class))).thenReturn(outputRelationDTO);
ResponseEntity expected = new ResponseEntity(outputRelationDTO, HttpStatus.OK);
ResponseEntity result = familyRESTController.changeRelation(changeRelationDTO, familyID, relationID);
assertEquals(expected, result);
assertNotNull(result);
}
@Test
@DisplayName("Change Relation failure due familyID not existing")
void changeRelationInvalidFamilyID() {
String familyID = "123";
String relationID = "123";
String relationshipDesignation = "Amante";
ChangeRelationDTO changeRelationDTO = new ChangeRelationDTO();
changeRelationDTO.setNewRelationDesignation(relationshipDesignation);
InputChangeRelationDTO inputChangeRelationDTO = new InputChangeRelationDTO(relationID, relationshipDesignation, familyID);
when(relationAssembler.toInputChangeRelationDTO(any(ChangeRelationDTO.class), anyString(), anyString())).thenReturn(inputChangeRelationDTO);
when(changeRelationService.changeRelation(any(InputChangeRelationDTO.class))).thenThrow(IllegalArgumentException.class);
ResponseEntity expected = new ResponseEntity("Error: null", HttpStatus.NOT_MODIFIED);
ResponseEntity result = familyRESTController.changeRelation(changeRelationDTO, familyID, relationID);
assertEquals(expected, result);
assertNotNull(result);
}
@Test
void addCustomCategoryTestSuccess() {
String familyIDString = <EMAIL>";
String categoryNameString = "Batatas";
String parentIDString = "Sopa";
String categoryIDString = "13L";
CreateCategoryDTO createCategoryDTO = new CreateCategoryDTO();
createCategoryDTO.setCategoryDescription(categoryNameString);
createCategoryDTO.setParentCategory(parentIDString);
OutputCategoryDTO outputCategoryDTO = new OutputCategoryDTO();
outputCategoryDTO.setCategoryID(categoryIDString);
outputCategoryDTO.setCategoryName(categoryNameString);
outputCategoryDTO.setFamilyID(familyIDString);
outputCategoryDTO.setParentID(parentIDString);
Link selfLink = linkTo(methodOn(FamilyRESTController.class).getCustomCategory(familyIDString, categoryIDString)).withSelfRel();
outputCategoryDTO.add(selfLink);
when(categoryAssembler.toInputCustomCategoryDTO(any(CreateCategoryDTO.class), anyString())).thenReturn(new InputCustomCategoryDTO(categoryNameString, parentIDString, familyIDString));
when(createCustomCategoryService.createCustomCategory(any(InputCustomCategoryDTO.class))).thenReturn(outputCategoryDTO);
ResponseEntity<OutputCategoryDTO> expected = new ResponseEntity(outputCategoryDTO, HttpStatus.CREATED);
ResponseEntity<OutputCategoryDTO> result = familyRESTController.addCustomCategory(familyIDString, createCategoryDTO);
assertEquals(expected, result);
}
@Test
void addCustomCategoryTestFailureBlankParentCategory() {
String familyIDString = <EMAIL>";
String categoryNameString = "Batatas";
String parentIDString = "";
CreateCategoryDTO createCategoryDTO = new CreateCategoryDTO();
createCategoryDTO.setCategoryDescription(categoryNameString);
createCategoryDTO.setParentCategory(parentIDString);
when(categoryAssembler.toInputCustomCategoryDTO(any(CreateCategoryDTO.class), anyString())).thenReturn(new InputCustomCategoryDTO(categoryNameString, parentIDString, familyIDString));
when(createCustomCategoryService.createCustomCategory(any(InputCustomCategoryDTO.class))).thenThrow(IllegalArgumentException.class);
ResponseEntity<OutputCategoryDTO> expected = new ResponseEntity("Error: null", HttpStatus.UNPROCESSABLE_ENTITY);
ResponseEntity<OutputCategoryDTO> result = familyRESTController.addCustomCategory(familyIDString, createCategoryDTO);
assertEquals(expected, result);
}
@Test
void getFamilyTestFailureThrowsException() {
when(getFamilyDataService.getFamilyData(anyString())).thenThrow(new InvalidDataAccessApiUsageException(""));
ResponseEntity expected = new ResponseEntity("Error: ",HttpStatus.BAD_REQUEST);
ResponseEntity result = familyRESTController.getFamily("<EMAIL>");
assertEquals(expected,result);
}
@Test
void getCustomCategoryUnsupported() {
String familyIDString = <EMAIL>";
String categoryIDString = "13L";
assertThrows(UnsupportedOperationException.class, () -> familyRESTController.getCustomCategory(familyIDString, categoryIDString));
}
} |
ABM-Community-Ports/droidboot_device_planet-cosmocom | lib/libufdt/include/ufdt_types.h | /*
* Copyright (C) 2016 The Android Open Source 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.
*/
#ifndef UFDT_TYPES_H
#define UFDT_TYPES_H
#include <libfdt.h>
/* it has type : struct ufdt_node** */
#define for_each(it, node) \
if ((node) != NULL) \
for (it = (node)->nodes; it != (node)->nodes + (node)->mem_size; ++it) \
if (*it)
#define for_each_child(it, node) \
if (tag_of(node) == FDT_BEGIN_NODE) \
for ((it) = &(((struct fdt_node_ufdt_node *)node)->child); *it; \
it = &((*it)->sibling))
#define for_each_prop(it, node) \
for_each_child(it, node) if (tag_of(*it) == FDT_PROP)
#define for_each_node(it, node) \
for_each_child(it, node) if (tag_of(*it) == FDT_BEGIN_NODE)
/*
* Gets prop name from FDT requires complicated manipulation.
* To avoid the manipulation, the *name pointer in fdt_prop_ufdt_node
* is pointed to the final destination of the prop name in FDT.
* For the FDT_BEGIN_NODE name, it can be obtained from FDT directly.
*/
#define name_of(node) \
((tag_of(node) == FDT_BEGIN_NODE) \
? (((const struct fdt_node_header *)((node)->fdt_tag_ptr))->name) \
: (((const struct fdt_prop_ufdt_node *)node)->name))
struct ufdt_node {
fdt32_t *fdt_tag_ptr;
struct ufdt_node *sibling;
};
struct fdt_prop_ufdt_node {
struct ufdt_node parent;
const char *name;
};
struct fdt_node_ufdt_node {
struct ufdt_node parent;
struct ufdt_node *child;
struct ufdt_node **last_child_p;
};
struct phandle_table_entry {
uint32_t phandle;
struct ufdt_node *node;
};
struct static_phandle_table {
int len;
struct phandle_table_entry *data;
};
struct ufdt {
void **fdtps;
int mem_size_fdtps;
int num_used_fdtps;
struct ufdt_node *root;
struct static_phandle_table phandle_table;
};
typedef void func_on_ufdt_node(struct ufdt_node *, void *);
struct ufdt_node_closure {
func_on_ufdt_node *func;
void *env;
};
static uint32_t tag_of(const struct ufdt_node *node) {
if (!node) return FDT_END;
return fdt32_to_cpu(*node->fdt_tag_ptr);
}
#endif /* UFDT_TYPES_H */
|
frank256/lgui | src/lib/lgui/lgui_types.h | /* _ _
* | | (_)
* | | __ _ _ _ _
* | | / _` || | | || |
* | || (_| || |_| || |
* |_| \__, | \__,_||_|
* __/ |
* |___/
*
* Copyright (c) 2015-22 frank256
*
* License (BSD):
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LGUI_TYPES_H
#define LGUI_TYPES_H
#include <algorithm>
#include <cmath>
#include <algorithm>
namespace lgui {
enum Orientation {
Vertical, Horizontal
};
class PointF;
/** A basic point type, int version. */
class Point {
public:
using Scalar = int;
Point(Scalar x, Scalar y)
: mx(x), my(y) {}
Point()
: mx(0), my(0) {}
Scalar x() const { return mx; }
Scalar y() const { return my; }
void set_x(Scalar x) { mx = x; }
void set_y(Scalar y) { my = y; }
void set(Scalar x, Scalar y) {
mx = x;
my = y;
}
void operator+=(const Point& other) {
mx += other.mx;
my += other.my;
}
void operator-=(const Point& other) {
mx -= other.mx;
my -= other.my;
}
Point operator-() const {
return {-mx, -my};
}
bool operator==(const Point& other) const {
return (mx == other.mx) && (my == other.my);
}
bool operator!=(const Point& other) const {
return !operator==(other);
}
Scalar lengthsq() const {
return mx * mx + my * my;
}
friend inline Point operator+(const Point& a, const Point& b) {
return {a.x() + b.x(), a.y() + b.y()};
}
friend inline Point operator-(const Point& a, const Point& b) {
return {a.x() - b.x(), a.y() - b.y()};
}
explicit operator PointF() const;
private:
Scalar mx, my;
};
/** A basic point type, float version */
class PointF {
public:
using Scalar = float;
PointF(Scalar x, Scalar y)
: mx(x), my(y) {}
PointF()
: mx(0), my(0) {}
Scalar x() const { return mx; }
Scalar y() const { return my; }
void set_x(Scalar x) { mx = x; }
void set_y(Scalar y) { my = y; }
void set(Scalar x, Scalar y) {
mx = x;
my = y;
}
Scalar lengthsq() const {
return mx * mx + my * my;
}
void operator+=(const PointF& other) {
mx += other.mx;
my += other.my;
}
void operator-=(const PointF& other) {
mx -= other.mx;
my -= other.my;
}
PointF operator-() const {
return {-mx, -my};
}
bool operator==(PointF other) const {
return (mx == other.mx) && (my == other.my);
}
bool operator!=(PointF other) const {
return !operator==(other);
}
void operator*=(float scalar) {
mx *= scalar;
my *= scalar;
}
friend inline PointF operator+(PointF a, PointF b) {
return {a.x() + b.x(), a.y() + b.y()};
}
friend inline PointF operator-(PointF a, PointF b) {
return {a.x() - b.x(), a.y() - b.y()};
}
friend PointF operator*(PointF p, float scalar) {
return {p.mx * scalar, p.my * scalar};
}
friend PointF operator*(float scalar, PointF p) {
return {p.mx * scalar, p.my * scalar};
}
Point to_point() const {
return {Point::Scalar(mx), Point::Scalar(my)};
}
Point to_point_rounded() const {
return {Point::Scalar(std::roundf(mx)), Point::Scalar(std::roundf(my))};
}
private:
Scalar mx, my;
};
inline Point::operator PointF() const {
return {PointF::Scalar(mx), PointF::Scalar(my)};
}
/** A basic size class. */
class Size {
public:
using Scalar = int;
Size()
: mw(0), mh(0) {}
Size(Scalar w, Scalar h)
: mw(w), mh(h) {}
explicit Size(Point p)
: mw(p.x()), mh(p.y()) {}
Scalar w() const { return mw; }
Scalar h() const { return mh; }
void set_w(Scalar w) { mw = w; }
void set_h(Scalar h) { mh = h; }
void set(Scalar w, Scalar h) {
mw = w;
mh = h;
}
Point to_point() const {
return Point{mw, mh};
}
bool operator==(const Size& other) const {
return (mw == other.mw) && (mh == other.mh);
}
bool operator!=(const Size& other) const {
return !operator==(other);
}
friend Size operator+(Size a, Size b) {
return {a.mw + b.mw, a.mh + b.mh};
}
private:
Scalar mw, mh;
};
/** A basic rectangle class. */
class Rect {
public:
using Scalar = int;
using PointT = Point;
using SizeT = Size;
Rect()
: mpos(0, 0), msize(0, 0) {}
Rect(Scalar x, Scalar y, Scalar w, Scalar h)
: mpos(x, y), msize(w, h) {}
Rect(Scalar x, Scalar y, SizeT s)
: mpos(x, y), msize(s) {}
Rect(PointT p, Scalar w, Scalar h)
: mpos(p), msize(w, h) {}
Rect(PointT p, SizeT s)
: mpos(p), msize(s) {}
Scalar x() const { return mpos.x(); }
Scalar y() const { return mpos.y(); }
Scalar w() const { return msize.w(); }
Scalar h() const { return msize.h(); }
Scalar x1() const { return x(); }
Scalar y1() const { return y(); }
Scalar x2() const { return x() + msize.w() - 1; }
Scalar y2() const { return y() + msize.h() - 1; }
PointT pos() const { return mpos; }
SizeT size() const { return msize; }
bool contains(PointT p) const {
return contains(p.x(), p.y());
}
bool contains(PointF p) const {
return contains(p.x(), p.y());
}
bool contains(Scalar x, Scalar y) const {
return (x >= mpos.x() && x < mpos.x() + msize.w()) &&
(y >= mpos.y() && y < mpos.y() + msize.h());
}
bool contains(float x, float y) const {
return (x >= float(mpos.x()) && x < float(mpos.x()) + msize.w()) &&
(y >= float(mpos.y()) && y < float(mpos.y()) + msize.h());
}
bool overlaps(const Rect& other) const {
if (x() >= other.x() + other.w())
return false;
if (y() >= other.y() + other.h())
return false;
if (x() + w() < other.x())
return false;
if (y() + h() < other.y())
return false;
return true;
}
void translate(Scalar x, Scalar y) {
mpos.set(mpos.x() + x, mpos.y() + y);
}
void translate(PointT p) {
mpos.set(mpos.x() + p.x(), mpos.y() + p.y());
}
Rect translated(PointT p) const {
return Rect(mpos + p, msize);
}
Rect translated(Scalar x, Scalar y) const {
return Rect(mpos.x() + x, mpos.y() + y, msize);
}
/** Ensure that the rect is within `frame`, cutting it off in all directions if it isn't. */
void clip_to(const Rect& frame) {
if (x() < frame.x()) {
Scalar dx = frame.x() - x();
set_pos_x(frame.x());
set_width(std::max<Scalar>(w() - dx, 0));
}
if (y() < frame.y()) {
Scalar dy = frame.y() - y();
set_pos_y(frame.y());
set_height(std::max<Scalar>(h() - dy, 0));
}
if (x2() > frame.x2())
set_width(std::max<Scalar>(frame.x2() - x() + 1, 0));
if (y2() > frame.y2())
set_height(std::max<Scalar>(frame.y2() - y() + 1, 0));
}
/** Ensure that p is within the rectangle. */
void clip_point(PointT& p) const {
if (p.x() < x1())
p.set_x(x1());
else if (p.x() > x2())
p.set_x(x2());
if (p.y() < y1())
p.set_y(y1());
else if (p.y() > y2())
p.set_y(y2());
}
/** Return the point clipped to the rectangle. */
PointT clipped_point(PointT p) const {
PointT r = p;
clip_point(r);
return r;
}
void set_pos(PointT pos) { mpos = pos; }
void set_pos(Scalar x, Scalar y) { mpos = PointT(x, y); }
void set_pos_x(Scalar x) { mpos.set_x(x); }
void set_pos_y(Scalar y) { mpos.set_y(y); }
void set_size(SizeT size) { msize = size; }
void set_size(Scalar w, Scalar h) { msize = SizeT(w, h); }
void set_width(Scalar w) { msize.set_w(w); }
void set_height(Scalar h) { msize.set_h(h); }
/** Return a rectangle that is grown exactly s pixels into all four directions. */
Rect grown(Scalar s) const {
return Rect(mpos.x() - s, mpos.y() - s, msize.w() + 2 * s, msize.h() + 2 * s);
}
/** Return a rectangle that is shrunk exactly s pixels into all four directions. */
Rect shrunk(Scalar s) const {
return Rect(mpos.x() + s, mpos.y() + s, msize.w() - 2 * s, msize.h() - 2 * s);
}
Point center() const {
return mpos + Point(msize.w() / 2, msize.h() / 2);
}
bool operator==(const Rect& other) const {
return mpos == other.mpos && msize == other.msize;
}
bool operator!=(const Rect& other) const {
return !operator==(other);
}
private:
PointT mpos;
SizeT msize;
};
using Position = Point;
using PositionF = PointF;
/** A class representing basic padding in four directions. */
class Padding {
public:
Padding(int l, int t, int r, int b)
: mleft(l), mtop(t), mright(r), mbottom(b) {}
Padding(int horz, int vert)
: mleft(horz), mtop(vert), mright(horz), mbottom(vert) {}
explicit Padding(int everywhere)
: mleft(everywhere), mtop(everywhere),
mright(everywhere), mbottom(everywhere) {}
Padding()
: mleft(0), mtop(0), mright(0), mbottom(0) {}
int left() const { return mleft; }
int top() const { return mtop; }
int right() const { return mright; }
int bottom() const { return mbottom; }
Position left_top_offs() const {
return {mleft, mtop};
}
int horz() const { return mleft + mright; }
int vert() const { return mtop + mbottom; }
void set_left(int l) { mleft = l; }
void set_top(int t) { mtop = t; }
void set_right(int r) { mright = r; }
void set_bottom(int b) { mbottom = b; }
void set_horz(int horz) {
mleft = mright = horz;
}
void set_vert(int vert) {
mtop = mbottom = vert;
}
void set(int everywhere) {
mleft = mtop = mright = mbottom = everywhere;
}
void set(int horz, int vert) {
mleft = mright = horz;
mtop = mbottom = vert;
}
void set(int l, int t, int r, int b) {
mleft = l;
mtop = t;
mright = r;
mbottom = b;
}
Size add(const Size& s) const {
Size ret;
ret.set_w(s.w() + mleft + mright);
ret.set_h(s.h() + mtop + mbottom);
return ret;
}
Size sub(const Size& s) const {
Size ret;
ret.set_w(s.w() - mleft - mright);
ret.set_h(s.h() - mtop - mbottom);
return ret;
}
Rect add(const Rect& r) const {
return {r.x() - mleft, r.y() - mtop,
r.w() + mleft + mright, r.h() + mtop + mbottom};
}
Rect sub(const Rect& r) const {
return {r.x() + mleft, r.y() + mtop,
r.w() - mleft - mright, r.h() - mtop - mbottom};
}
/** Return a new size that will be adjusted to use this padding
* instead of old padding */
Size get_same_content_size(const Size& old_size,
const Padding& old_padding) const {
return add(old_padding.sub(old_size));
}
friend Size operator+(const Size& s, const Padding& p) {
return {s.w() + p.horz(), s.h() + p.vert()};
}
friend Size operator+(const Padding& p, const Size& s) {
return {s.w() + p.horz(), s.h() + p.vert()};
}
friend Size operator-(const Size& s, const Padding& p) {
return {s.w() - p.horz(), s.h() - p.vert()};
}
friend Size operator-(const Padding& p, const Size& s) {
return {s.w() - p.horz(), s.h() - p.vert()};
}
private:
int mleft, mtop, mright, mbottom;
};
using Margin = Padding;
}
#endif // LGUI_TYPES_H
|
JTarasovic/go-ripestat | client/rrc_info.go | <gh_stars>0
package client
const (
rrcInfoPath = "rrc-info/data.json"
)
// RRCInfo GETs information on collector nodes (RRCs) of the RIS network (http://ris.ripe.net).
// This includes geographical and topological location and information on collectors' peers.
func (c *Client) RRCInfo() (map[string]interface{}, error) {
return c.execute(rrcInfoPath, nil)
}
|
threepointone/built-devtools | front_end/panels/sources/sourcesPanel.css.js | <filename>front_end/panels/sources/sourcesPanel.css.js
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const styles = new CSSStyleSheet();
styles.replaceSync(
`/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009 <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
.scripts-debug-toolbar {
position: absolute;
top: 0;
width: 100%;
background-color: var(--color-background-elevation-1);
border-bottom: 1px solid var(--color-details-hairline);
overflow: hidden;
z-index: 1;
}
.scripts-debug-toolbar-drawer {
flex: 0 0 52px;
transition: margin-top 0.1s ease-in-out;
margin-top: -26px;
padding-top: 25px;
background-color: var(--color-background);
overflow: hidden;
white-space: nowrap;
}
.scripts-debug-toolbar-drawer.expanded {
margin-top: 0;
}
.scripts-debug-toolbar-drawer > [is=dt-checkbox] {
display: none;
padding-left: 3px;
height: 28px;
}
.scripts-debug-toolbar-drawer.expanded > [is=dt-checkbox] {
display: flex;
}
.cursor-auto {
cursor: auto;
}
.navigator-tabbed-pane {
background-color: var(--color-background-elevation-1);
}
/*# sourceURL=sourcesPanel.css */
`);
export default styles;
|
Harshpathakjnp/CCodings | bca class/main.c | <reponame>Harshpathakjnp/CCodings
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j,i=3;
j= ++i *++i *++i;
printf("j=%d,i=%d",j,i);
}
|
byung90/graphhopper | objc/SwaggerClient/Model/SWGSolutionUnassigned.h | #import <Foundation/Foundation.h>
#import "SWGObject.h"
/**
* GraphHopper Directions API
* You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various constraints like time window and capacity restrictions. Also it is possible to get all distances between all locations with our fast Matrix API.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#import "SWGDetail.h"
@protocol SWGDetail;
@class SWGDetail;
@protocol SWGSolutionUnassigned
@end
@interface SWGSolutionUnassigned : SWGObject
/* An array of ids of unassigned services [optional]
*/
@property(nonatomic) NSArray<NSString*>* services;
/* An array of ids of unassigned shipments [optional]
*/
@property(nonatomic) NSArray<NSString*>* shipments;
/* An array of ids of unassigned breaks [optional]
*/
@property(nonatomic) NSArray<NSString*>* breaks;
/* An array of details, i.e. reason for unassigned services or shipments [optional]
*/
@property(nonatomic) NSArray<SWGDetail>* details;
@end
|
ArcGIS/calcite-ui-icons-public | js/bringToFront32.js | export const bringToFront32 = "M30 12h-4v-1h3V3h-8v3h-1V2h10zM11 26v3H3v-8h3v-1H2v10h10v-4zM25 7H7v18h18z";
|
ViljoenFritz/nspack | scripts/edi_receive_check.rb | <gh_stars>1-10
# frozen_string_literal: true
# require 'logger'
# Scan a directory for EDI in files and process them.
class EdiReceiveCheck < BaseScript
attr_reader :in_dir, :out_dir, :cnt, :processed_files
def run
p 'EDI receive' if debug_mode
@in_dir = args.first
@out_dir = AppConst::EDI_RECEIVE_DIR
raise ArgumentError, 'Directory to check was not provided' unless @in_dir
raise ArgumentError, 'EDI_RECEIVE_DIR has not been set' unless @out_dir
p "Dirs: #{in_dir} -> #{out_dir}" if debug_mode
@cnt = 0
@processed_files = []
move_files
success
end
private
def success
if cnt.zero?
success_response('No files to process')
else
success_response(%(Processed #{cnt} file(s):\n#{processed_files.join("\n")}))
end
end
def move_files
Dir.glob("#{in_dir.chomp('/')}/*").each do |file|
next unless File.file?(file)
next if file.end_with?('.inuse')
puts "\nFound #{File.basename(file)}" if debug_mode
log("Processing: #{File.basename(file)}")
@cnt += 1
processed_files << file
action_file(file)
end
end
def action_file(file)
new_path = File.join(out_dir, File.basename(file))
puts "moving #{file} to #{new_path}" if debug_mode
log("Moving: #{file} to #{new_path}")
FileUtils.mv(file, new_path)
puts "Enqueuing #{new_path} for EdiApp::Job::ReceiveEdiIn" if debug_mode
log("Enqueuing #{new_path} for EdiApp::Job::ReceiveEdiIn")
Que.enqueue new_path, job_class: 'EdiApp::Job::ReceiveEdiIn', queue: AppConst::QUEUE_NAME
end
def log(msg)
logger.info msg
end
def logger
@logger ||= Logger.new(File.join(root_dir, 'log', 'edi_in.log'), 'weekly')
end
end
|
Zen-CODE/zenprojects | python/fastapi/library/app/routers/library/library_responses.py | from pydantic import BaseModel
from typing import List
class ArtistListModel(BaseModel):
"""
The list of artists in our music library.
"""
artists: List[str] = []
class AlbumListModel(BaseModel):
"""
The list of albums for a given artist.
"""
artist: str
albums: List[str] = []
class AlbumModel(BaseModel):
"""
The details of an album, including the full path to the cover art.
"""
artist: str
album: str
cover: str
class PathModel(BaseModel):
"""
The full file system path to the album.
"""
path: str
class TrackListModel(BaseModel):
"""
The listing of all the tracks on the specified album.
"""
artist: str
album: str
tracks: List[str] = []
class SearchModel(BaseModel):
"""
The results of an album search.
"""
artist: str
album: str
path: str
|
DeKal/illumina | cms/src/core/components/NavBar.js | import React from 'react'
import PropTypes from 'prop-types'
import { styled } from '@material-ui/core/styles'
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'
import IconButton from '@material-ui/core/IconButton'
import MenuIcon from '@material-ui/icons/Menu'
import Badge from '@material-ui/core/Badge'
import AccountCircle from '@material-ui/icons/AccountCircle'
import NotificationsIcon from '@material-ui/icons/Notifications'
import { pages } from 'core/const/pages'
const NavBar = ({ classes, history, open, openDrawer, closeDrawer }) => {
return (
<Container>
<AppBar position="static" className={classes.navbar}>
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="menu"
data-test-id="navbar-menu"
onClick={() => (open ? closeDrawer() : openDrawer())}
>
<MenuIcon />
</IconButton>
<Typography
variant="h1"
data-test-id="navbar-title"
className={classes.title}
onClick={() => {
history.push(pages.dashboard.url)
}}
>
Dashboard
</Typography>
<div>
<IconButton
aria-label="show 17 new notifications"
color="inherit"
className={classes.icon}
>
<Badge badgeContent={17} color="secondary">
<NotificationsIcon />
</Badge>
</IconButton>
<IconButton
edge="end"
aria-label="account of current user"
aria-haspopup="true"
color="inherit"
data-test-id="navbar-user-info"
className={classes.icon}
onClick={() => {
history.push(pages.profile.url)
}}
>
<AccountCircle />
</IconButton>
</div>
</Toolbar>
</AppBar>
</Container>
)
}
export default NavBar
NavBar.propTypes = {
classes: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
open: PropTypes.bool,
openDrawer: PropTypes.func,
closeDrawer: PropTypes.func
}
const Container = styled('div')({
flexGrow: 1
})
|
CaffeineShawn/gdutday-wechat | pages/grade/grade_static.js | <gh_stars>1-10
export const defaultGrade = [{
credit: "4.5",
examName: "下拉可以刷新哦",
examPole: "4.5",
examScore: "95",
examTime: "2018秋季",
readMethod: "必修",
}, {
credit: "4",
examName: "糯米鸡",
examPole: "3.5",
examScore: "85",
examTime: "2018秋季",
readMethod: "必修",
}, {
credit: "3.5",
examName: "鸡肉卷",
examPole: "2",
examScore: "70",
examTime: "2018秋季",
readMethod: "必修",
}, {
credit: "3",
examName: "铁板烧",
examPole: "2.5",
examScore: "75",
examTime: "2018秋季",
readMethod: "必修"
}, {
credit: "2",
examName: "鸡蛋灌饼",
examPole: "1.5",
examScore: "65",
examTime: "2018秋季",
readMethod: "选修"
}, {
credit: "1",
examName: "烤冷面",
examPole: "4.9",
examScore: "99",
examTime: "2019春季",
readMethod: "选修"
}, {
credit: "1.5",
examName: "手抓饼",
examPole: "2.7",
examScore: "77",
examTime: "2019春季",
readMethod: "必修"
}, {
credit: "1.5",
examName: "关东煮",
examPole: "0",
examScore: "0",
examTime: "2019春季",
readMethod: "必修"
}, {
credit: "4.5",
examName: "下拉可以刷新哦",
examPole: "4.5",
examScore: "95",
examTime: "2019秋季",
readMethod: "必修"
}, {
credit: "4",
examName: "糯米鸡",
examPole: "3.5",
examScore: "85",
examTime: "2019秋季",
readMethod: "必修"
}, {
credit: "3.5",
examName: "鸡肉卷",
examPole: "2",
examScore: "70",
examTime: "2019秋季",
readMethod: "必修"
}, {
credit: "3",
examName: "铁板烧",
examPole: "2.5",
examScore: "75",
examTime: "2019秋季",
readMethod: "必修"
}, {
credit: "2",
examName: "鸡蛋灌饼",
examPole: "1.5",
examScore: "65",
examTime: "2019秋季",
readMethod: "选修"
}, {
credit: "1",
examName: "烤冷面",
examPole: "4.9",
examScore: "99",
examTime: "2020春季",
readMethod: "选修"
}, {
credit: "1.5",
examName: "手抓饼",
examPole: "2.7",
examScore: "77",
examTime: "2020春季",
readMethod: "必修"
}, {
credit: "1.5",
examName: "关东煮",
examPole: "0",
examScore: "0",
examTime: "2020春季",
readMethod: "必修"
}];
export const colors = ['#f04864', '#FF7293', '#FFE655', '#33C8FD', '#40C769','#40C769']; |
Diorrr/leetcode | problems/easy/Solution217.java | <reponame>Diorrr/leetcode
package problems.easy;
import java.util.HashSet;
/**
* Problem: https://leetcode.com/problems/contains-duplicate/
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
class Solution217 {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
return true;
}
}
return false;
}
}
|
justmedia-pl/SportEvents | src/main/java/pl/justmedia/service/SecurityUserDetailsService.java | <gh_stars>0
package pl.justmedia.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import pl.justmedia.entity.User;
import pl.justmedia.entity.repositories.UserRepository;
import javax.transaction.Transactional;
import java.util.Optional;
@Service
@Transactional
public class SecurityUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String userLogin) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUserLogin(userLogin);
//check if optional exist and use lambda to throw exception
user.orElseThrow(()-> new UsernameNotFoundException("User not found !"));
//map object to instance of new object
return user.map(SecurityUserDetails::new).get();
}
}
|
wcnnkh/framework | mvc/src/main/java/io/basc/framework/mvc/HttpChannelInterceptor.java | package io.basc.framework.mvc;
import java.io.IOException;
public interface HttpChannelInterceptor {
Object intercept(HttpChannel httpChannel, HttpChannelInterceptorChain chain) throws IOException;
}
|
kalaytan/elastalert-operator | api/v1alpha1/elastalert_types.go | <filename>api/v1alpha1/elastalert_types.go
/*
Copyright 2021.
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 v1alpha1
import (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
const (
// +k8s:openapi-gen=true
ElastAlertPhraseFailed = "FAILED"
ElastAlertInitializing = "INITIALIZING"
// +k8s:openapi-gen=true
ElastAlertPhraseSucceeded = "RUNNING"
ElastAlertAvailableReason = "NewElastAlertAvailable"
ElastAlertAvailableType = "Progressing"
ElastAlertAvailableStatus = "True"
ElastAlertUnAvailableReason = "ElastAlertUnAvailable"
ElastAlertUnKnowReason = "ResourcesCreating"
ElastAlertUnAvailableType = "Stopped"
ElastAlertUnAvailableStatus = "False"
ElastAlertUnKnownStatus = "Unknown"
ResourcesCreating = "starting"
ActionSuccess = "success"
ActionFailed = "failed"
ElastAlertVersion = "v1.0"
ConfigSuffx = "-config"
RuleSuffx = "-rule"
RuleMountPath = "/etc/elastalert/rules"
ConfigMountPath = "/etc/elastalert"
ElastAlertObserveInterval = time.Minute
ElastAlertPollInterval = time.Second * 5
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// ElastalertSpec defines the desired state of Elastalert
// +k8s:openapi-gen=true
type ElastalertSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
PodTemplateSpec v1.PodTemplateSpec `json:"podTemplate,omitempty"`
Image string `json:"image,omitempty"`
Cert string `json:"cert,omitempty"`
ConfigSetting FreeForm `json:"config"`
Rule []FreeForm `json:"rule"`
// +optional
Alert FreeForm `json:"overall,omitempty"`
}
// +k8s:openapi-gen=true
// ElastalertStatus defines the observed state of Elastalert
type ElastalertStatus struct {
Version string `json:"version,omitempty"`
Phase string `json:"phase,omitempty"`
Condictions []metav1.Condition `json:"conditions,omitempty"`
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
// +k8s:openapi-gen=true
// +operator-sdk:gen-csv:customresourcedefinitions.displayName="Elastalert"
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Status",type="string",JSONPath=".status.phase",description="Elastalert instance's status"
// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".status.version",description="Elastalert Version"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp"
// Elastalert is the Schema for the elastalerts API
type Elastalert struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ElastalertSpec `json:"spec,omitempty"`
Status ElastalertStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// ElastalertList contains a list of Elastalert
type ElastalertList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Elastalert `json:"items"`
}
func init() {
SchemeBuilder.Register(&Elastalert{}, &ElastalertList{})
}
|
ryanloney/openvino-1 | tools/mo/openvino/tools/mo/ops/upsample.py | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import math
from openvino.tools.mo.front.common.layout import get_batch_dim, get_features_dim, get_height_dim, get_width_dim, shape_for_layout
from openvino.tools.mo.front.common.partial_infer.utils import dynamic_dimension, shape_array, dynamic_dimension_value
from openvino.tools.mo.graph.graph import Node, Graph
from openvino.tools.mo.ops.op import Op
class UpsampleOp(Op):
op = 'Upsample'
def __init__(self, graph: Graph, attrs: dict):
mandatory_props = {
'op': self.op,
'in_ports_count': 2,
'out_ports_count': 1,
'infer': UpsampleOp.upsample_infer
}
super().__init__(graph, mandatory_props, attrs)
def supported_attrs(self):
return [
'height_scale',
'width_scale',
'mode',
]
@staticmethod
def upsample_infer(node: Node):
node_name = node.soft_get('name', node.id)
layout = node.graph.graph['layout']
assert len(layout) == 4, 'Input tensor rank must be equal to 4 for node "{}"'.format(node_name)
input_shape = node.in_port(0).data.get_shape()
if len(node.in_nodes()) == 1:
in_height = input_shape[get_height_dim(layout, 4)]
in_width = input_shape[get_width_dim(layout, 4)]
assert node.has('width_scale') is not None and node.has('height_scale') is not None
if in_height is not dynamic_dimension:
out_height = math.floor(in_height * node.height_scale)
else:
out_height = dynamic_dimension
if in_width is not dynamic_dimension:
out_width = math.floor(in_width * node.width_scale)
else:
out_width = dynamic_dimension
node.out_port(0).data.set_shape(shape_for_layout(layout,
batch=input_shape[get_batch_dim(layout, 4)],
features=input_shape[get_features_dim(layout, 4)],
height=out_height,
width=out_width))
else:
scales = node.in_port(1).data.get_value()
assert scales is not None, 'The input with scales for node "{}" is not constant'.format(node_name)
eps = 1e-5 # This is to make rounding in case of very close number to round to closest instead of down
# generic output shape calculation to support 5D input shape case
output_shape = shape_array([dynamic_dimension for _ in range(len(input_shape))])
for idx in range(len(output_shape)):
if input_shape[idx] is not dynamic_dimension:
output_shape[idx] = int((input_shape[idx] + eps) * scales[idx])
else:
output_shape[idx] = dynamic_dimension_value
node.out_port(0).data.set_shape(output_shape)
|
JeroenKnoops/embeddedinfralib | infra/util/BoundedString.hpp | #ifndef INFRA_BOUNDED_STRING_HPP
#define INFRA_BOUNDED_STRING_HPP
// BoundedString is similar to std::string, except that it can contain a maximum number of characters
#include "infra/util/MemoryRange.hpp"
#include "infra/util/WithStorage.hpp"
#include <cstdlib>
#include <cstring>
#include <ostream>
#include <string>
namespace infra
{
template<class T>
class BoundedStringBase;
using BoundedString = BoundedStringBase<char>;
using BoundedConstString = BoundedStringBase<const char>;
template<class T>
class BoundedStringBase
{
public:
using NonConstT = typename std::remove_const<T>::type;
template<std::size_t Max>
using WithStorage = infra::WithStorage<BoundedStringBase, std::array<NonConstT, Max>>;
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
public:
static const size_type npos;
public:
BoundedStringBase();
explicit BoundedStringBase(MemoryRange<T> range);
BoundedStringBase(MemoryRange<NonConstT> range, size_type count);
BoundedStringBase(MemoryRange<NonConstT> range, size_type count, char ch);
BoundedStringBase(MemoryRange<NonConstT> range, const BoundedStringBase& other, size_type pos, size_type count = BoundedStringBase::npos);
BoundedStringBase(MemoryRange<NonConstT> range, const char* s, size_type count);
BoundedStringBase(MemoryRange<NonConstT> range, const char* s);
BoundedStringBase(MemoryRange<NonConstT> range, const std::string& s);
BoundedStringBase(T* s, size_type count);
BoundedStringBase(T* s); //TICS !INT#001
BoundedStringBase(const std::string& s); //TICS !INT#001
BoundedStringBase(std::string& s); //TICS !INT#001
template<class InputIterator>
BoundedStringBase(MemoryRange<NonConstT> range, InputIterator first, InputIterator last);
BoundedStringBase(MemoryRange<NonConstT> range, std::initializer_list<char> initializerList);
template<class U>
BoundedStringBase(MemoryRange<NonConstT> range, const BoundedStringBase<U>& other);
BoundedStringBase(const BoundedStringBase& other);
template<class U> //TICS !INT#001
BoundedStringBase(const BoundedStringBase<U>& other);
BoundedStringBase& operator=(const BoundedStringBase& other);
BoundedStringBase& operator=(const char* s);
BoundedStringBase& operator=(char ch);
BoundedStringBase& operator=(const std::string& s);
template<class U>
void AssignFromStorage(const BoundedStringBase<U>& other);
void AssignFromStorage(const char* s);
void AssignFromStorage(char ch);
void AssignFromStorage(const std::string& s);
BoundedStringBase& assign(size_type count, char ch);
template<class U>
BoundedStringBase& assign(const BoundedStringBase<U>& other);
template<class U>
BoundedStringBase& assign(const BoundedStringBase<U>& other, size_type pos, size_type count);
BoundedStringBase& assign(const char* s, size_type count);
BoundedStringBase& assign(const char* s);
BoundedStringBase& assign(const std::string& s);
template<class InputIterator>
BoundedStringBase& assign(InputIterator first, InputIterator last);
public:
reference operator[](size_type pos);
const_reference operator[](size_type pos) const;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
pointer data() const;
public:
iterator begin() const;
const_iterator cbegin() const;
iterator end() const;
const_iterator cend() const;
reverse_iterator rbegin() const;
const_reverse_iterator crbegin() const;
reverse_iterator rend() const;
const_reverse_iterator crend() const;
public:
bool empty() const;
bool full() const;
size_type size() const;
size_type max_size() const;
public:
void clear();
BoundedStringBase& insert(size_type index, size_type count, char ch);
BoundedStringBase& insert(size_type index, const char* s);
BoundedStringBase& insert(size_type index, const char* s, size_type count);
BoundedStringBase& insert(size_type index, const BoundedStringBase& other);
BoundedStringBase& insert(size_type index, const BoundedStringBase& other, size_type index_str, size_type count);
BoundedStringBase& insert(size_type index, const std::string& other);
BoundedStringBase& insert(size_type index, const std::string& other, size_type index_str, size_type count);
iterator insert(const_iterator pos, char ch);
iterator insert(const_iterator pos, size_type count, char ch);
template<class InputIterator>
iterator insert(const_iterator i, InputIterator first, InputIterator last);
BoundedStringBase& erase(size_type index = 0, size_type count = npos);
iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);
void push_back(char ch);
void pop_back();
BoundedStringBase& append(size_type count, char ch);
template<class U>
BoundedStringBase& append(const BoundedStringBase<U>& other);
template<class U>
BoundedStringBase& append(const BoundedStringBase<U>& other, size_type pos, size_type count);
BoundedStringBase& append(const char* s, size_type count);
BoundedStringBase& append(const char* s);
BoundedStringBase& append(const std::string& s);
template<class InputIterator>
BoundedStringBase& append(InputIterator first, InputIterator last);
template<class U>
BoundedStringBase& operator+=(const BoundedStringBase<U>& other);
BoundedStringBase& operator+=(char ch);
BoundedStringBase& operator+=(const char* s);
BoundedStringBase& operator+=(const std::string& s);
int compare(const BoundedStringBase& other) const;
int compare(size_type pos1, size_type count1, const BoundedStringBase& other) const;
int compare(size_type pos1, size_type count1, const BoundedStringBase& other, size_type pos2, size_type count2) const;
int compare(const char* s) const;
int compare(size_type pos1, size_type count1, const char* s) const;
int compare(size_type pos1, size_type count1, const char* s, size_type count2) const;
int compare(const std::string& s) const;
int compare(size_type pos1, size_type count1, const std::string& s) const;
int compare(size_type pos1, size_type count1, const std::string& s, size_type count2) const;
template<class U>
BoundedStringBase& replace(size_type pos, size_type count, const BoundedStringBase<U>& other);
template<class U>
BoundedStringBase& replace(const_iterator first, const_iterator last, const BoundedStringBase<U>& other);
template<class U>
BoundedStringBase& replace(size_type pos, size_type count, const BoundedStringBase<U>& other, size_type pos2, size_type count2);
template<class InputIterator>
BoundedStringBase& replace(const_iterator first, const_iterator last, InputIterator first2, InputIterator last2);
BoundedStringBase& replace(size_type pos, size_type count, const char* cstr, size_type count2);
BoundedStringBase& replace(const_iterator first, const_iterator last, const char* cstr, size_type count2);
BoundedStringBase& replace(size_type pos, size_type count, const char* cstr);
BoundedStringBase& replace(const_iterator first, const_iterator last, const char* cstr);
BoundedStringBase& replace(size_type pos, size_type count, const std::string& s, size_type count2);
BoundedStringBase& replace(const_iterator first, const_iterator last, const std::string& s, size_type count2);
BoundedStringBase& replace(size_type pos, size_type count, const std::string& s);
BoundedStringBase& replace(const_iterator first, const_iterator last, const std::string& s);
BoundedStringBase& replace(size_type pos, size_type count, size_type count2, char ch);
BoundedStringBase& replace(const_iterator first, const_iterator last, size_type count2, char ch);
public:
BoundedStringBase substr(size_type pos = 0, size_type count = npos);
BoundedStringBase<const T> substr(size_type pos = 0, size_type count = npos) const;
size_type copy(char* dest, size_type count, size_type pos = 0);
void resize(size_type count);
void resize(size_type count, char ch);
void shrink(size_type count);
void swap(BoundedStringBase& other);
public:
template<class U>
size_type find(const BoundedStringBase<U>& other, size_type pos = 0) const;
size_type find(const char* s, size_type pos, size_type count) const;
size_type find(const char* s, size_type pos = 0) const;
size_type find(char ch, size_type pos = 0) const;
template<class U>
size_type rfind(const BoundedStringBase<U>& other, size_type pos = npos) const;
size_type rfind(const char* s, size_type pos, size_type count) const;
size_type rfind(const char* s, size_type pos = npos) const;
size_type rfind(char ch, size_type pos = npos) const;
template<class U>
size_type find_first_of(const BoundedStringBase<U>& other, size_type pos = 0) const;
size_type find_first_of(const char* s, size_type pos, size_type count) const;
size_type find_first_of(const char* s, size_type pos = 0) const;
size_type find_first_of(char ch, size_type pos = 0) const;
template<class U>
size_type find_first_not_of(const BoundedStringBase<U>& other, size_type pos = 0) const;
size_type find_first_not_of(const char* s, size_type pos, size_type count) const;
size_type find_first_not_of(const char* s, size_type pos = 0) const;
size_type find_first_not_of(char ch, size_type pos = 0) const;
template<class U>
size_type find_last_of(const BoundedStringBase<U>& other, size_type pos = npos) const;
size_type find_last_of(const char* s, size_type pos, size_type count) const;
size_type find_last_of(const char* s, size_type pos = npos) const;
size_type find_last_of(char ch, size_type pos = npos) const;
template<class U>
size_type find_last_not_of(const BoundedStringBase<U>& other, size_type pos = npos) const;
size_type find_last_not_of(const char* s, size_type pos, size_type count) const;
size_type find_last_not_of(const char* s, size_type pos = npos) const;
size_type find_last_not_of(char ch, size_type pos = npos) const;
private:
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, size_type count, char ch);
template<class U>
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, const BoundedStringBase<U>& other);
template<class U>
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, const BoundedStringBase<U>& other, size_type pos, size_type count);
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, const char* s, size_type count);
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, const char* s);
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, const std::string& s);
template<class InputIterator>
static void AssignToRange(MemoryRange<NonConstT> range, size_type& length, InputIterator first, InputIterator last);
private:
void MoveUp(size_type start, size_type count);
void MoveDown(size_type start, size_type count);
int CompareImpl(const char* begin1, const char* end1, const char* begin2, const char* end2) const;
void ReplaceImpl(char* begin1, size_type count1, const char* begin2, size_type count2);
void ReplaceImpl(char* begin1, size_type count1, char ch, size_type count2);
private:
template<class U>
friend class BoundedStringBase;
MemoryRange<T> range;
size_type length = 0;
};
template<class T, class U>
bool operator==(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T, class U>
bool operator!=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T, class U>
bool operator<(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T, class U>
bool operator<=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T, class U>
bool operator>(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T, class U>
bool operator>=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs);
template<class T>
bool operator==(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator==(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator==(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator==(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
bool operator!=(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator!=(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator!=(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator!=(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
bool operator<(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator<(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator<(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator<(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
bool operator<=(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator<=(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator<=(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator<=(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
bool operator>(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator>(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator>(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator>(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
bool operator>=(const char* lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator>=(const BoundedStringBase<T>& lhs, const char* rhs);
template<class T>
bool operator>=(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
bool operator>=(const BoundedStringBase<T>& lhs, const std::string& rhs);
template<class T>
std::string operator+(const std::string& lhs, const BoundedStringBase<T>& rhs);
template<class T>
void swap(BoundedStringBase<T>& lhs, BoundedStringBase<T>& rhs);
template<class T>
BoundedStringBase<T> TrimLeft(BoundedStringBase<T> string);
template<class T>
MemoryRange<T> MakeRange(infra::BoundedStringBase<T>& container);
template<class T>
MemoryRange<const T> MakeRange(const infra::BoundedStringBase<T>& container);
template<class T, class U>
MemoryRange<T> StringAsMemoryRange(const infra::BoundedStringBase<U>& string);
template<class T, class U>
MemoryRange<const T> StringAsMemoryRange(const infra::BoundedStringBase<const U>& string);
template<class U>
MemoryRange<uint8_t> StringAsByteRange(const infra::BoundedStringBase<U>& string);
template<class U>
MemoryRange<const uint8_t> StringAsByteRange(const infra::BoundedStringBase<const U>& string);
BoundedString ByteRangeAsString(infra::MemoryRange<uint8_t> range);
BoundedConstString ByteRangeAsString(infra::MemoryRange<const uint8_t> range);
#ifdef CCOLA_HOST_BUILD //TICS !POR#021
// gtest uses PrintTo to display the contents of BoundedStringBase<T>
template<class T>
void PrintTo(const BoundedStringBase<T>& string, std::ostream* os)
{
*os << '\"';
for (char c : string)
*os << c;
*os << '\"';
}
template<class T, std::size_t Max>
void PrintTo(const typename BoundedStringBase<T>::template WithStorage<Max>& string, std::ostream* os)
{
*os << '\"';
for (char c : string)
*os << c;
*os << '\"';
}
#endif
//// Implementation ////
template<class T>
BoundedStringBase<T>::BoundedStringBase()
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<T> range)
: range(range)
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, size_type count)
: range(range)
, length(count)
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, size_type count, char ch)
: range(range)
{
AssignToRange(range, length, count, ch);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, const BoundedStringBase<T>& other, size_type pos, size_type count)
: range(range)
{
AssignToRange(range, length, other, pos, count);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, const char* s, size_type count)
: range(range)
{
AssignToRange(range, length, s, count);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, const char* s)
: range(range)
{
AssignToRange(range, length, s);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, const std::string& s)
: range(range)
{
AssignToRange(range, length, s);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(T* s, size_type count)
: range(s, s + count)
, length(count)
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(T* s)
: range(s, s + std::strlen(s))
, length(range.size())
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(const std::string& s)
: range(const_cast<char*>(s.data()), const_cast<char*>(s.data()) + s.size())
, length(s.size())
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(std::string& s)
: range(const_cast<char*>(s.data()), const_cast<char*>(s.data()) + s.size())
, length(s.size())
{}
template<class T>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, std::initializer_list<char> initializerList)
: range(range)
{
AssignToRange(range, length, initializerList.begin(), initializerList.end());
}
template<class T>
template<class U>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, const BoundedStringBase<U>& other)
: range(range)
{
AssignToRange(range, length, other);
}
template<class T>
BoundedStringBase<T>::BoundedStringBase(const BoundedStringBase<T>& other)
: range(other.range)
, length(other.length)
{}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator=(const BoundedStringBase<T>& other)
{
range = other.range;
length = other.length;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator=(const char* s)
{
return assign(s);
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator=(char ch)
{
return assign(1, ch);
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator=(const std::string& s)
{
return assign(s);
}
template<class T>
template<class U>
void BoundedStringBase<T>::AssignFromStorage(const BoundedStringBase<U>& other)
{
assign(other);
}
template<class T>
void BoundedStringBase<T>::AssignFromStorage(const char* s)
{
*this = s;
}
template<class T>
void BoundedStringBase<T>::AssignFromStorage(char ch)
{
*this = ch;
}
template<class T>
void BoundedStringBase<T>::AssignFromStorage(const std::string& s)
{
*this = s;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::assign(size_type count, char ch)
{
AssignToRange(range, length, count, ch);
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::assign(const BoundedStringBase<U>& other)
{
AssignToRange(range, length, other);
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::assign(const BoundedStringBase<U>& other, size_type pos, size_type count)
{
AssignToRange(range, length, other, pos, count);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::assign(const char* s, size_type count)
{
AssignToRange(range, length, s, count);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::assign(const char* s)
{
AssignToRange(range, length, s);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::assign(const std::string& s)
{
AssignToRange(range, length, s);
return *this;
}
template<class T>
template<class InputIterator>
BoundedStringBase<T>& BoundedStringBase<T>::assign(InputIterator first, InputIterator last)
{
AssignToRange(range, length, first, last);
return *this;
}
template<class T>
T& BoundedStringBase<T>::operator[](size_type pos)
{
return range[pos];
}
template<class T>
const T& BoundedStringBase<T>::operator[](size_type pos) const
{
return range[pos];
}
template<class T>
T& BoundedStringBase<T>::front()
{
return range.front();
}
template<class T>
const T& BoundedStringBase<T>::front() const
{
return range.front();
}
template<class T>
T& BoundedStringBase<T>::back()
{
return range[length - 1];
}
template<class T>
const T& BoundedStringBase<T>::back() const
{
return range[length - 1];
}
template<class T>
T* BoundedStringBase<T>::data() const
{
return range.begin();
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::begin() const
{
return range.begin();
}
template<class T>
typename BoundedStringBase<T>::const_iterator BoundedStringBase<T>::cbegin() const
{
return range.begin();
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::end() const
{
return range.begin() + length;
}
template<class T>
typename BoundedStringBase<T>::const_iterator BoundedStringBase<T>::cend() const
{
return range.begin() + length;
}
template<class T>
typename BoundedStringBase<T>::reverse_iterator BoundedStringBase<T>::rbegin() const
{
return reverse_iterator(range.begin() + length);
}
template<class T>
typename BoundedStringBase<T>::const_reverse_iterator BoundedStringBase<T>::crbegin() const
{
return reverse_iterator(range.begin() + length);
}
template<class T>
typename BoundedStringBase<T>::reverse_iterator BoundedStringBase<T>::rend() const
{
return reverse_iterator(range.begin());
}
template<class T>
typename BoundedStringBase<T>::const_reverse_iterator BoundedStringBase<T>::crend() const
{
return reverse_iterator(range.begin());
}
template<class T>
bool BoundedStringBase<T>::empty() const
{
return length == 0;
}
template<class T>
bool BoundedStringBase<T>::full() const
{
return length == max_size();
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::size() const
{
return length;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::max_size() const
{
return range.size();
}
template<class T>
void BoundedStringBase<T>::clear()
{
length = 0;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, size_type count, char ch)
{
assert(length + count <= max_size());
MoveUp(index, count);
for (; count != 0; --count)
range[index++] = ch;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const char* s)
{
return insert(index, s, std::strlen(s));
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const char* s, size_type count)
{
assert(length + count <= max_size());
MoveUp(index, count);
for (; count != 0; --count)
range[index++] = *s++;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const BoundedStringBase<T>& other)
{
assert(length + other.size() <= max_size());
MoveUp(index, other.size());
for (const_iterator i = other.begin(); i != other.end(); ++i)
range[index++] = *i;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const BoundedStringBase<T>& other, size_type index_str, size_type count)
{
assert(length + count <= max_size());
MoveUp(index, count);
const_iterator i = other.begin() + index_str;
for (; count != 0; --count)
range[index++] = *i++;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const std::string& other)
{
return insert(index, other.data(), other.size());
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::insert(size_type index, const std::string& other, size_type index_str, size_type count)
{
return insert(index, other.data() + index_str, count);
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::insert(const_iterator pos, char ch)
{
assert(length != max_size());
size_type index = pos - begin();
MoveUp(index, 1);
range[index++] = ch;
return begin() + index;
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::insert(const_iterator pos, size_type count, char ch)
{
assert(length + count <= max_size());
size_type index = pos - begin();
MoveUp(index, count);
for (; count != 0; --count)
range[index++] = ch;
return begin() + index;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::erase(size_type index, size_type count)
{
count = std::min(count, length - index);
MoveDown(index, count);
return *this;
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::erase(const_iterator position)
{
MoveDown(position - begin(), 1);
return begin() + (position - begin());
}
template<class T>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::erase(const_iterator first, const_iterator last)
{
MoveDown(first - begin(), std::distance(first, last));
return begin() + (first - begin());
}
template<class T>
void BoundedStringBase<T>::push_back(char ch)
{
assert(length != max_size());
range[length] = ch;
++length;
}
template<class T>
void BoundedStringBase<T>::pop_back()
{
assert(length > 0);
--length;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::append(size_type count, char ch)
{
assert(length + count <= max_size());
for (; count > 0; --count, ++length)
range[length] = ch;
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::append(const BoundedStringBase<U>& other)
{
assert(length + other.size() <= max_size());
for (const_iterator i = other.begin(); i != other.end(); ++i, ++length)
range[length] = *i;
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::append(const BoundedStringBase<U>& other, size_type pos, size_type count)
{
assert(length + count <= max_size());
for (const_iterator i = other.begin() + pos; i != other.begin() + pos + count; ++i, ++length)
range[length] = *i;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::append(const char* s, size_type count)
{
assert(length + count <= max_size());
for (const char* i = s; i != s + count; ++i, ++length)
range[length] = *i;
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::append(const char* s)
{
return append(s, std::strlen(s));
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::append(const std::string& s)
{
return append(s.data(), s.size());
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::operator+=(const BoundedStringBase<U>& other)
{
return append(other);
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator+=(char ch)
{
return append(1, ch);
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator+=(const char* s)
{
return append(s);
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::operator+=(const std::string& s)
{
return append(s);
}
template<class T>
int BoundedStringBase<T>::compare(const BoundedStringBase<T>& other) const
{
return CompareImpl(begin(), end(), other.begin(), other.end());
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const BoundedStringBase<T>& other) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, other.begin(), other.end());
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const BoundedStringBase<T>& other, size_type pos2, size_type count2) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, other.begin() + pos2, other.begin() + pos2 + count2);
}
template<class T>
int BoundedStringBase<T>::compare(const char* s) const
{
return CompareImpl(begin(), end(), s, s + std::strlen(s));
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const char* s) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, s, s + std::strlen(s));
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const char* s, size_type count2) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, s, s + count2);
}
template<class T>
int BoundedStringBase<T>::compare(const std::string& s) const
{
return CompareImpl(begin(), end(), s.data(), s.data() + s.size());
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const std::string& s) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, s.data(), s.data() + s.size());
}
template<class T>
int BoundedStringBase<T>::compare(size_type pos1, size_type count1, const std::string& s, size_type count2) const
{
return CompareImpl(begin() + pos1, begin() + pos1 + count1, s.data(), s.data() + count2);
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const BoundedStringBase<U>& other)
{
ReplaceImpl(begin() + pos, count, other.begin(), other.size());
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, const BoundedStringBase<U>& other)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), other.begin(), other.size());
return *this;
}
template<class T>
template<class U>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const BoundedStringBase<U>& other, size_type pos2, size_type count2)
{
ReplaceImpl(begin() + pos, count, other.begin(), count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const char* cstr, size_type count2)
{
ReplaceImpl(begin() + pos, count, cstr, count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, const char* cstr, size_type count2)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), cstr, count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const char* cstr)
{
ReplaceImpl(begin() + pos, count, cstr, std::strlen(cstr));
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, const char* cstr)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), cstr, std::strlen(cstr));
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const std::string& s, size_type count2)
{
ReplaceImpl(begin() + pos, count, s.data(), count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, const std::string& s, size_type count2)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), s.data(), count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, const std::string& s)
{
ReplaceImpl(begin() + pos, count, s.data(), s.size());
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, const std::string& s)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), s.data(), s.size());
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(size_type pos, size_type count, size_type count2, char ch)
{
ReplaceImpl(begin() + pos, count, ch, count2);
return *this;
}
template<class T>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, size_type count2, char ch)
{
ReplaceImpl(begin() + std::distance(cbegin(), first), std::distance(first, last), ch, count2);
return *this;
}
template<class T>
BoundedStringBase<T> BoundedStringBase<T>::substr(size_type pos, size_type count)
{
assert(pos <= length);
count = std::min(count, length - pos);
return BoundedStringBase<T>(begin() + pos, count);
}
template<class T>
BoundedStringBase<const T> BoundedStringBase<T>::substr(size_type pos, size_type count) const
{
assert(pos <= length);
count = std::min(count, length - pos);
return BoundedStringBase<const T>(begin() + pos, count);
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::copy(char* dest, size_type count, size_type pos)
{
assert(pos + count <= length);
std::copy(begin() + pos, begin() + pos + count, dest);
return count;
}
template<class T>
void BoundedStringBase<T>::resize(size_type count)
{
resize(count, char());
}
template<class T>
void BoundedStringBase<T>::resize(size_type count, char ch)
{
assert(count <= max_size());
if (count > length)
std::fill(end(), begin() + count, ch);
length = count;
}
template<class T>
void BoundedStringBase<T>::shrink(size_type count)
{
if (count < length)
length = count;
}
template<class T>
void BoundedStringBase<T>::swap(BoundedStringBase<T>& other)
{
using std::swap;
for (size_type i = 0; i < size() && i < other.size(); ++i)
swap(range[i], other.range[i]);
for (size_type i = size(); i < other.size(); ++i)
range[i] = other.range[i];
for (size_type i = other.size(); i < size(); ++i)
other.range[i] = range[i];
std::swap(length, other.length);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find(const BoundedStringBase<U>& other, size_type pos) const
{
return find(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find(const char* s, size_type pos, size_type count) const
{
assert(pos <= length);
for (const_iterator i = begin() + pos; i + count <= end(); ++i)
if (CompareImpl(i, i + count, s, s + count) == 0)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find(const char* s, size_type pos) const
{
return find(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find(char ch, size_type pos) const
{
return find(&ch, pos, 1);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::rfind(const BoundedStringBase<U>& other, size_type pos) const
{
pos = std::min(pos, length);
return rfind(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::rfind(const char* s, size_type pos, size_type count) const
{
pos = std::min(pos, length);
for (const_iterator i = std::min(begin() + pos, end() - count); i >= begin(); --i)
if (CompareImpl(i, i + count, s, s + count) == 0)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::rfind(const char* s, size_type pos) const
{
return rfind(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::rfind(char ch, size_type pos) const
{
return rfind(&ch, pos, 1);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_of(const BoundedStringBase<U>& other, size_type pos) const
{
return find_first_of(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_of(const char* s, size_type pos, size_type count) const
{
pos = std::min(pos, length);
for (const_iterator i = begin() + pos; i != end(); ++i)
if (std::find(s, s + count, *i) != s + count)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_of(const char* s, size_type pos) const
{
return find_first_of(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_of(char ch, size_type pos) const
{
return find_first_of(&ch, pos, 1);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_not_of(const BoundedStringBase<U>& other, size_type pos) const
{
return find_first_not_of(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_not_of(const char* s, size_type pos, size_type count) const
{
pos = std::min(pos, length);
for (const_iterator i = begin() + pos; i != end(); ++i)
if (std::find(s, s + count, *i) == s + count)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_not_of(const char* s, size_type pos) const
{
return find_first_not_of(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_first_not_of(char ch, size_type pos) const
{
return find_first_not_of(&ch, pos, 1);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_of(const BoundedStringBase<U>& other, size_type pos) const
{
return find_last_of(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_of(const char* s, size_type pos, size_type count) const
{
pos = std::min(pos, length);
for (const_iterator i = begin() + pos - 1; i >= begin(); --i)
if (std::find(s, s + count, *i) != s + count)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_of(const char* s, size_type pos) const
{
return find_last_of(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_of(char ch, size_type pos) const
{
return find_last_of(&ch, pos, 1);
}
template<class T>
template<class U>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_not_of(const BoundedStringBase<U>& other, size_type pos) const
{
return find_last_not_of(other.begin(), pos, other.size());
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_not_of(const char* s, size_type pos, size_type count) const
{
pos = std::min(pos, length);
for (const_iterator i = begin() + pos - 1; i >= begin(); --i)
if (std::find(s, s + count, *i) == s + count)
return i - begin();
return npos;
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_not_of(const char* s, size_type pos) const
{
return find_last_not_of(s, pos, std::strlen(s));
}
template<class T>
typename BoundedStringBase<T>::size_type BoundedStringBase<T>::find_last_not_of(char ch, size_type pos) const
{
return find_last_not_of(&ch, pos, 1);
}
template<class T>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, size_type count, char ch)
{
assert(count <= range.size());
length = count;
std::fill(range.begin(), range.begin() + length, ch);
}
template<class T>
template<class U>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, const BoundedStringBase<U>& other)
{
assert(other.size() <= range.size());
length = other.length;
std::copy(other.begin(), other.begin() + length, range.begin());
}
template<class T>
template<class U>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, const BoundedStringBase<U>& other, size_type pos, size_type count)
{
count = std::min(count, other.size());
assert(count <= range.size());
length = count;
std::copy(other.range.begin() + pos, other.range.begin() + pos + length, range.begin());
}
template<class T>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, const char* s, size_type count)
{
assert(count <= range.size());
length = count;
std::copy(s, s + length, range.begin());
}
template<class T>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, const char* s)
{
AssignToRange(range, length, s, std::strlen(s));
}
template<class T>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, const std::string& s)
{
AssignToRange(range, length, s.data(), s.size());
}
template<class T>
template<class InputIterator>
void BoundedStringBase<T>::AssignToRange(infra::MemoryRange<NonConstT> range, size_type& length, InputIterator first, InputIterator last)
{
for (length = 0; length != range.size() && first != last; ++length, ++first)
range[length] = *first;
}
template<class T>
void BoundedStringBase<T>::MoveUp(size_type start, size_type count)
{
std::memmove(range.begin() + start + count, range.begin() + start, length - start);
length += count;
}
template<class T>
void BoundedStringBase<T>::MoveDown(size_type start, size_type count)
{
std::memmove(range.begin() + start, range.begin() + start + count, length - start - count);
length -= count;
}
template<class T>
int BoundedStringBase<T>::CompareImpl(const char* begin1, const char* end1, const char* begin2, const char* end2) const
{
for (; begin1 != end1 && begin2 != end2; ++begin1, ++begin2)
if (*begin1 != *begin2)
return *begin1 < *begin2 ? -1 : 1;
if (begin1 != end1)
return 1;
if (begin2 != end2)
return -1;
return 0;
}
template<class T>
void BoundedStringBase<T>::ReplaceImpl(char* begin1, size_type count1, const char* begin2, size_type count2)
{
assert(length - count1 + count2 <= max_size());
std::memmove(begin1 + count2, begin1 + count1, length - count1 - (begin() - begin1));
std::memmove(begin1, begin2, count2);
length += count2 - count1;
}
template<class T>
void BoundedStringBase<T>::ReplaceImpl(char* begin1, size_type count1, char ch, size_type count2)
{
assert(length - count1 + count2 <= max_size());
std::memmove(begin1 + count2, begin1 + count1, length - count1 - (begin() - begin1));
std::fill(begin1, begin1 + count2, ch);
length += count2 - count1;
}
template<class T>
template<class U>
BoundedStringBase<T>::BoundedStringBase(const BoundedStringBase<U>& other)
: range(other.range)
, length(other.length)
{
T x = {}; // const char
U y; // char
y = x; // Test to see that this constructor is used for assigning a non-const string to a const string
(void)y;
}
template<class T>
template<class InputIterator>
BoundedStringBase<T>::BoundedStringBase(MemoryRange<NonConstT> range, InputIterator first, InputIterator last)
: range(range)
{
AssignToRange(range, length, first, last);
}
template<class T>
template<class InputIterator>
typename BoundedStringBase<T>::iterator BoundedStringBase<T>::insert(const_iterator i, InputIterator first, InputIterator last)
{
std::size_t additional = std::min(max_size() - length, static_cast<size_type>(std::distance(first, last)));
size_type index = i - begin();
MoveUp(index, additional);
for (; additional != 0; --additional)
range[index++] = *first++;
return &range[index];
}
template<class T>
template<class InputIterator>
BoundedStringBase<T>& BoundedStringBase<T>::append(InputIterator first, InputIterator last)
{
for (InputIterator i = first; i != last && length != max_size(); ++i, ++length)
range[length] = *i;
return *this;
}
template<class T>
template<class InputIterator>
BoundedStringBase<T>& BoundedStringBase<T>::replace(const_iterator first, const_iterator last, InputIterator first2, InputIterator last2)
{
size_type count = first - begin();
difference_type count2 = std::distance(first2, last2);
size_type replacementSize = count2 - std::max<difference_type>(length - count + count2 - max_size(), 0);
ReplaceImpl(begin() + count, last - first, first2, replacementSize);
return *this;
}
template<class T>
const typename BoundedStringBase<T>::size_type BoundedStringBase<T>::npos = std::numeric_limits<size_type>::max();
template<class T, class U>
bool operator==(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return lhs.size() == rhs.size()
&& std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
template<class T, class U>
bool operator!=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return !(lhs == rhs);
}
template<class T, class U>
bool operator<(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
template<class T, class U>
bool operator<=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return !(rhs < lhs);
}
template<class T, class U>
bool operator>(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return rhs < lhs;
}
template<class T, class U>
bool operator>=(const BoundedStringBase<T>& lhs, const BoundedStringBase<U>& rhs)
{
return !(lhs < rhs);
}
template<class T>
bool operator==(const char* lhs, const BoundedStringBase<T>& rhs)
{
return std::strlen(lhs) == rhs.size()
&& std::equal(rhs.begin(), rhs.end(), lhs);
}
template<class T>
bool operator==(const BoundedStringBase<T>& lhs, const char* rhs)
{
return lhs.size() == std::strlen(rhs)
&& std::equal(lhs.begin(), lhs.end(), rhs);
}
template<class T>
bool operator==(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return lhs.size() == rhs.size()
&& std::equal(rhs.begin(), rhs.end(), lhs.begin());
}
template<class T>
bool operator==(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return lhs.size() == rhs.size()
&& std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
template<class T>
bool operator!=(const char* lhs, const BoundedStringBase<T>& rhs)
{
return !(lhs == rhs);
}
template<class T>
bool operator!=(const BoundedStringBase<T>& lhs, const char* rhs)
{
return !(lhs == rhs);
}
template<class T>
bool operator!=(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return !(lhs == rhs);
}
template<class T>
bool operator!=(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return !(lhs == rhs);
}
template<class T>
bool operator<(const char* lhs, const BoundedStringBase<T>& rhs)
{
return std::lexicographical_compare(lhs, lhs + std::strlen(lhs), rhs.begin(), rhs.end());
}
template<class T>
bool operator<(const BoundedStringBase<T>& lhs, const char* rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs, rhs + std::strlen(rhs));
}
template<class T>
bool operator<(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return std::lexicographical_compare(lhs.data(), lhs.data() + lhs.size(), rhs.begin(), rhs.end());
}
template<class T>
bool operator<(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.data(), rhs.data() + rhs.size());
}
template<class T>
bool operator<=(const char* lhs, const BoundedStringBase<T>& rhs)
{
return !(rhs < lhs);
}
template<class T>
bool operator<=(const BoundedStringBase<T>& lhs, const char* rhs)
{
return !(rhs < lhs);
}
template<class T>
bool operator<=(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return !(rhs < lhs);
}
template<class T>
bool operator<=(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return !(rhs < lhs);
}
template<class T>
bool operator>(const char* lhs, const BoundedStringBase<T>& rhs)
{
return rhs < lhs;
}
template<class T>
bool operator>(const BoundedStringBase<T>& lhs, const char* rhs)
{
return rhs < lhs;
}
template<class T>
bool operator>(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return rhs < lhs;
}
template<class T>
bool operator>(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return rhs < lhs;
}
template<class T>
bool operator>=(const char* lhs, const BoundedStringBase<T>& rhs)
{
return !(lhs < rhs);
}
template<class T>
bool operator>=(const BoundedStringBase<T>& lhs, const char* rhs)
{
return !(lhs < rhs);
}
template<class T>
bool operator>=(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
return !(lhs < rhs);
}
template<class T>
bool operator>=(const BoundedStringBase<T>& lhs, const std::string& rhs)
{
return !(lhs < rhs);
}
template<class T>
std::string operator+(const std::string& lhs, const BoundedStringBase<T>& rhs)
{
std::string result(lhs);
result.append(rhs.begin(), rhs.end());
return result;
}
template<class T>
void swap(BoundedStringBase<T>& lhs, BoundedStringBase<T>& rhs)
{
lhs.swap(rhs);
}
template<class T>
BoundedStringBase<T> TrimLeft(BoundedStringBase<T> string)
{
for (auto i = 0; i != string.size(); ++i)
if (string[i] != ' ')
return string.substr(i);
return BoundedStringBase<T>();
}
template<class T>
MemoryRange<T> MakeRange(infra::BoundedStringBase<T>& container)
{
return MemoryRange<T>(container.begin(), container.end());
}
template<class T>
MemoryRange<const T> MakeRange(const infra::BoundedStringBase<T>& container)
{
return MemoryRange<const T>(container.begin(), container.end());
}
template<class T, class U>
MemoryRange<T> StringAsMemoryRange(const infra::BoundedStringBase<U>& string)
{
return MemoryRange<T>(reinterpret_cast<T*>(string.begin()), reinterpret_cast<T*>(string.end()));
}
template<class T, class U>
MemoryRange<const T> StringAsMemoryRange(const infra::BoundedStringBase<const U>& string)
{
return MemoryRange<const T>(reinterpret_cast<const T*>(string.begin()), reinterpret_cast<const T*>(string.end()));
}
template<class U>
MemoryRange<uint8_t> StringAsByteRange(const infra::BoundedStringBase<U>& string)
{
return StringAsMemoryRange<uint8_t>(string);
}
template<class U>
MemoryRange<const uint8_t> StringAsByteRange(const infra::BoundedStringBase<const U>& string)
{
return StringAsMemoryRange<uint8_t>(string);
}
}
#endif
|
burdiuz/js-embedded-debug | subscriber/src/communication/message-port.js | <reponame>burdiuz/js-embedded-debug
import { Command } from 'message/command';
import { composeMessage, readMessage } from 'message/message';
export const factory = ({ source, target }) => {
const send = (command, data = null) => {
const str = composeMessage(command, data);
target.postMessage(str, '*');
};
return {
initialize: (callback) => {
source.addEventListener('message', (event) => {
const message = readMessage(event);
if (message) {
callback(message);
}
});
send(Command.INIT_FRAME);
},
send,
};
};
|
durtto/cherryonext | src/netbox/core/RangeField.js | <reponame>durtto/cherryonext
// $Id$
/** Create a new RangeField
* A range field is a widget used to edit ranges. It's a trigger field that has in the popup 2 Ext.form.TextField (or classes derived by a TextField)
* to allow the user to enter the from and the to end points of a range
* @extends Ext.form.TriggerField
* @constructor
* @param {Object} config Configuration options
* <ul>
* <li> fromConfig The config for the from object</li>
* <li> toConfig The config for the from object</li>
* <li> textCls The Class to use as from and to (for example Ext.form.TextField)</li>
* <li> minListWidth The min width (in pixel) of the popup. Optional. Default 20 </li>
* <li> fieldSize The size of the field (in number of characters). Optional. Default 20</li>
* </ul>
*/
Ext.define('Ext.ux.netbox.core.RangeField', {
extend: 'Ext.form.field.Trigger',
constructor: function(config) {
this.textCls=config.textCls;
this.fromConfig=config.fromConfig;
this.toConfig=config.toConfig;
if(config.minListWidth){
this.minListWidth=config.minListWidth;
} else {
this.minListWidth=100;
}
if(config.fieldSize){
this.defaultAutoCreate.size=config.fieldSize;
}
Ext.ux.netbox.core.RangeField.superclass.constructor.call(this,config);
},
fromText : 'da',
toText : 'a',
defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
editable: false,
rangeValue: null,
initComponent: function () {
Ext.ux.netbox.core.RangeField.superclass.initComponent.call(this);
},
onTriggerClick: function(){
if(this.disabled){
return;
}
if(this.menu == null){
this.menu = Ext.create('Ext.ux.netbox.core.RangeMenu',{textCls:this.textCls,
fromCfg:this.fromConfig,
toCfg:this.toConfig,
fieldValidateFunc:Ext.bind(this.validate,this),
width: this.getWidth()});
}
if (this.menuListeners) {
this.menu.on(Ext.apply({}, this.menuListeners, {scope:this}));
}
this.menu.setWidth(this.getWidth());
this.menu.showBy(this);
this.menu.setValue(this.rangeValue);
},
getValue: function(){
if(this.menu !== undefined)
this.rangeValue=this.menu.getValue();
return(this.rangeValue);
},
setValue: function(val){
if (!Ext.isArray(val)) {
val = ["",""];
}
var valueFrom = (val[0] === undefined || val[0]==null)? "" : val[0];
var valueTo = (val[1] === undefined || val[0]==null)? "" : val[1];
formattedValue=this.fromText+": "+valueFrom+", "+this.toText+": "+valueTo;
Ext.ux.netbox.core.RangeField.superclass.setValue.call(this, formattedValue);
this.rangeValue=val;
if(this.menu!=null){
this.menu.setValue(this.rangeValue);
}
},
markInvalid: function(msg){
Ext.ux.netbox.core.RangeField.superclass.markInvalid.call(this,msg);
if(this.menu){
this.menu.markInvalid(msg);
}
},
clearInvalid: function(){
Ext.ux.netbox.core.RangeField.superclass.clearInvalid.call(this);
if(this.menu){
this.menu.clearInvalidFields();
}
},
validateBlur: function(e){
return(this.menu && this.menu.getEl() && !this.menu.getEl().contains(e.target));
}
});
|
PuetzD/platform | src/Administration/Resources/app/administration/src/app/component/base/sw-button-group/index.js | import './sw-button-group.scss';
import template from './sw-button-group.html.twig';
const { Component } = Shopware;
/**
* @status ready
* @description The <u>sw-button-group</u> is a container element for sw-button and sw-context-button elements.
* @example-type static
* @component-example
* <sw-button-group>
* <sw-button>Button 1</sw-button>
* <sw-button>Button 2</sw-button>
* <sw-button>Button 3</sw-button>
* </sw-button-group>
*/
Component.register('sw-button-group', {
template,
props: {
block: {
type: Boolean,
required: false,
default: false,
},
splitButton: {
type: Boolean,
required: false,
default: false,
},
},
computed: {
buttonGroupClasses() {
return {
'sw-button-group--block': this.block,
'sw-button-group--split': this.splitButton,
};
},
},
});
|
karthikv1392/ML-Service-Discovery | user-service/src/main/java/it/univaq/disim/numismatic/stubservice/controller/model/RolesType.java |
package it.univaq.disim.numismatic.stubservice.controller.model;
import lombok.Data;
import java.util.List;
@Data
public class RolesType {
private List<String> role;
}
|
danish2210/quran.com-api | spec/models/audio/recitation_spec.rb | # == Schema Information
#
# Table name: audio_recitations
#
# id :bigint not null, primary key
# arabic_name :string
# description :text
# file_formats :string
# home :integer
# name :string
# relative_path :string
# torrent_filename :string
# torrent_info_hash :string
# torrent_leechers :integer default(0)
# torrent_seeders :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
# recitation_style_id :integer
# resource_content_id :integer
# section_id :integer
#
# Indexes
#
# index_audio_recitations_on_recitation_style_id (recitation_style_id)
#
require 'rails_helper'
RSpec.describe Audio::Recitation, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
|
SoapyMan/oolua | unit_tests/bind_classes/expose_class_enums.cpp | #include "expose_class_enums.h"
#include "oolua_dsl_export.h"
OOLUA_EXPORT_NO_FUNCTIONS(ClassWithEnums)
|
sitewhere/sitewhere-java-api | sitewhere-java-model/src/main/java/com/sitewhere/rest/model/device/event/DeviceCommandInvocation.java | <gh_stars>1-10
/**
* Copyright © 2014-2021 The SiteWhere 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.sitewhere.rest.model.device.event;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.sitewhere.spi.device.event.CommandInitiator;
import com.sitewhere.spi.device.event.CommandTarget;
import com.sitewhere.spi.device.event.DeviceEventType;
import com.sitewhere.spi.device.event.IDeviceCommandInvocation;
/**
* Implementation of {@link IDeviceCommandInvocation}.
*/
@JsonIgnoreProperties
@JsonInclude(Include.NON_NULL)
public class DeviceCommandInvocation extends DeviceEvent implements IDeviceCommandInvocation, Serializable {
/** For Java serialization */
private static final long serialVersionUID = -7389600825785131041L;
/** Type of actor that initiated the command */
private CommandInitiator initiator;
/** Id of actor that initiated the command */
private String initiatorId;
/** Type of actor that will receive the command */
private CommandTarget target;
/** Id of actor that will receive the command */
private String targetId;
/** Unique id of command to execute */
private UUID deviceCommandId;
/** Values to use for command parameters */
private Map<String, String> parameterValues = new HashMap<String, String>();
public DeviceCommandInvocation() {
super(DeviceEventType.CommandInvocation);
}
/*
* (non-Javadoc)
*
* @see com.sitewhere.spi.device.event.IDeviceCommandInvocation#getInitiator()
*/
@Override
public CommandInitiator getInitiator() {
return initiator;
}
public void setInitiator(CommandInitiator initiator) {
this.initiator = initiator;
}
/*
* (non-Javadoc)
*
* @see com.sitewhere.spi.device.event.IDeviceCommandInvocation#getInitiatorId()
*/
@Override
public String getInitiatorId() {
return initiatorId;
}
public void setInitiatorId(String initiatorId) {
this.initiatorId = initiatorId;
}
/*
* (non-Javadoc)
*
* @see com.sitewhere.spi.device.event.IDeviceCommandInvocation#getTarget()
*/
@Override
public CommandTarget getTarget() {
return target;
}
public void setTarget(CommandTarget target) {
this.target = target;
}
/*
* (non-Javadoc)
*
* @see com.sitewhere.spi.device.event.IDeviceCommandInvocation#getTargetId()
*/
@Override
public String getTargetId() {
return targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
/*
* @see
* com.sitewhere.spi.device.event.IDeviceCommandInvocation#getDeviceCommandId()
*/
@Override
public UUID getDeviceCommandId() {
return deviceCommandId;
}
public void setDeviceCommandId(UUID deviceCommandId) {
this.deviceCommandId = deviceCommandId;
}
/*
* (non-Javadoc)
*
* @see com.sitewhere.spi.device.event.IDeviceCommandInvocation#
* getParameterValues()
*/
@Override
public Map<String, String> getParameterValues() {
return parameterValues;
}
public void setParameterValues(Map<String, String> parameterValues) {
this.parameterValues = parameterValues;
}
} |
MarginC/kame | netbsd/sys/arch/shark/stand/ofwboot/netif_of.h | /* $NetBSD: netif_of.h,v 1.1 2003/03/13 15:36:07 drochner Exp $ */
int netif_of_open(struct of_dev *);
void netif_of_close(int);
|
ssshammi/real-time-3d-rendering-with-directx-and-hlsl | source/7.2_Gaussian_Blurring/GaussianBlurDemo.h | <reponame>ssshammi/real-time-3d-rendering-with-directx-and-hlsl<filename>source/7.2_Gaussian_Blurring/GaussianBlurDemo.h
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <map>
#include "DrawableGameComponent.h"
#include "FullScreenRenderTarget.h"
#include "GaussianBlur.h"
namespace Rendering
{
class DiffuseLightingDemo;
class GaussianBlurDemo final : public Library::DrawableGameComponent
{
public:
GaussianBlurDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
GaussianBlurDemo(const GaussianBlurDemo&) = delete;
GaussianBlurDemo(GaussianBlurDemo&&) = default;
GaussianBlurDemo& operator=(const GaussianBlurDemo&) = default;
GaussianBlurDemo& operator=(GaussianBlurDemo&&) = default;
~GaussianBlurDemo();
std::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;
float BlurAmount() const;
void SetBlurAmount(float blurAmount);
virtual void Initialize() override;
virtual void Update(const Library::GameTime& gameTime) override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
std::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;
Library::FullScreenRenderTarget mRenderTarget;
Library::GaussianBlur mGaussianBlur;
};
} |
kamentr/API_Restaurant | src/main/java/net/kodar/restaurantapi/data/entities/IngredientStatus.java | package net.kodar.restaurantapi.data.entities;
import java.io.Serializable;
import javax.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=true)
@Entity
@Table(name="ingredient_status")
@NamedQuery(name="IngredientStatus.findAll", query="SELECT i FROM IngredientStatus i")
public class IngredientStatus extends NamedPersistent implements Serializable {
private static final long serialVersionUID = 1L;
} |
ogesaku/quark-common | src/main/java/com/coditory/quark/common/collection/Maps.java | package com.coditory.quark.common.collection;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.coditory.quark.common.check.Args.checkNotNull;
import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Collectors.toUnmodifiableMap;
import static java.util.stream.Collectors.toUnmodifiableSet;
public final class Maps {
private Maps() {
throw new UnsupportedOperationException("Do not instantiate utility class");
}
public static <K, V> Map<V, K> invert(Map<K, V> map) {
checkNotNull(map, "map");
Map<V, K> result = new LinkedHashMap<>();
for (Entry<K, V> entry : map.entrySet()) {
if (!result.containsKey(entry.getValue())) {
result.put(entry.getValue(), entry.getKey());
}
}
return unmodifiableMap(result);
}
public static <K, V> Map<K, V> nullToEmpty(@Nullable Map<K, V> map) {
return map == null ? Map.of() : map;
}
@Nullable
public static <K, V> Map<K, V> emptyToNull(@Nullable Map<K, V> map) {
return map == null || map.isEmpty() ? null : map;
}
public static <K, V, K2, V2> Map<K2, V2> map(Map<K, V> map, Function<Map.Entry<K, V>, Map.Entry<K2, V2>> mapper) {
checkNotNull(map, "map");
checkNotNull(mapper, "mapper");
return map.entrySet().stream()
.map(mapper)
.collect(toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
}
public static <K, V, R> Map<R, V> mapKeys(Map<K, V> map, Function<K, R> mapper) {
checkNotNull(map, "map");
checkNotNull(mapper, "mapper");
return map.entrySet().stream()
.collect(toUnmodifiableMap(entry -> mapper.apply(entry.getKey()), Entry::getValue));
}
public static <K, V, R> Map<K, R> mapValues(Map<K, V> map, Function<V, R> mapper) {
checkNotNull(map, "map");
checkNotNull(mapper, "mapper");
return map.entrySet().stream()
.collect(toUnmodifiableMap(Entry::getKey, entry -> mapper.apply(entry.getValue())));
}
public static <K, V> Map<K, V> filter(Map<K, V> map, Predicate<Entry<K, V>> predicate) {
checkNotNull(map, "map");
checkNotNull(predicate, "predicate");
return map.entrySet().stream()
.filter(predicate)
.collect(toUnmodifiableMap(Entry::getKey, Entry::getValue));
}
public static <K, V> Map<K, V> filterByKey(Map<K, V> map, Predicate<K> predicate) {
checkNotNull(map, "map");
checkNotNull(predicate, "predicate");
return map.entrySet().stream()
.filter(entry -> predicate.test(entry.getKey()))
.collect(toUnmodifiableMap(Entry::getKey, Entry::getValue));
}
public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
checkNotNull(map, "map");
checkNotNull(predicate, "predicate");
return map.entrySet().stream()
.filter(entry -> predicate.test(entry.getValue()))
.collect(toUnmodifiableMap(Entry::getKey, Entry::getValue));
}
public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) {
checkNotNull(map, "map");
checkNotNull(key, "key");
checkNotNull(value, "value");
Map<K, V> result = new LinkedHashMap<>(map);
result.put(key, value);
return unmodifiableMap(result);
}
public static <K, V> Map<K, V> putAll(Map<K, V> mapA, Map<K, V> mapB) {
checkNotNull(mapA, "mapA");
checkNotNull(mapB, "mapB");
Map<K, V> result = new LinkedHashMap<>(mapA);
result.putAll(mapB);
return unmodifiableMap(result);
}
public static <K, V> Map<K, V> remove(Map<K, V> map, K key) {
checkNotNull(map, "map");
checkNotNull(key, "key");
Map<K, V> result = new LinkedHashMap<>(map);
result.remove(key);
return unmodifiableMap(result);
}
public static <K, V> Map<K, V> removeAll(Map<K, V> map, Collection<K> keys) {
checkNotNull(map, "map");
checkNotNull(keys, "keys");
Map<K, V> result = new LinkedHashMap<>(map);
keys.forEach(result::remove);
return unmodifiableMap(result);
}
public static <K, V> MapBuilder<K, V> builder() {
return new MapBuilder<>();
}
public static <K, V> MapBuilder<K, V> builder(int size) {
return new MapBuilder<>(size);
}
public static <K, V> MapBuilder<K, V> builderWith(K key, V value) {
return new MapBuilder<K, V>()
.put(key, value);
}
public static class MapBuilder<K, V> {
private final Map<K, V> map;
private MapBuilder(int size) {
map = new LinkedHashMap<>(size);
}
private MapBuilder() {
map = new LinkedHashMap<>();
}
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
public Map<K, V> build() {
return unmodifiableMap(map);
}
}
}
|
ScalablyTyped/SlinkyTyped | a/arcgis-js-api/src/main/scala/typingsSlinky/arcgisJsApi/esri/SegmentDrawActionProperties.scala | <reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.arcgisJsApi.esri
import typingsSlinky.arcgisJsApi.arcgisJsApiStrings.click
import typingsSlinky.arcgisJsApi.arcgisJsApiStrings.freehand
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait SegmentDrawActionProperties extends DrawActionProperties {
/**
* The drawing mode.
*
* [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-views-draw-SegmentDrawAction.html#mode)
*/
var mode: js.UndefOr[freehand | click] = js.native
}
object SegmentDrawActionProperties {
@scala.inline
def apply(): SegmentDrawActionProperties = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[SegmentDrawActionProperties]
}
@scala.inline
implicit class SegmentDrawActionPropertiesMutableBuilder[Self <: SegmentDrawActionProperties] (val x: Self) extends AnyVal {
@scala.inline
def setMode(value: freehand | click): Self = StObject.set(x, "mode", value.asInstanceOf[js.Any])
@scala.inline
def setModeUndefined: Self = StObject.set(x, "mode", js.undefined)
}
}
|
ate47/rdf4j | compliance/rio/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleParserTest.java | /*******************************************************************************
* Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.rio.turtle;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.helpers.BasicParserSettings;
import org.eclipse.rdf4j.rio.ntriples.NTriplesParser;
import org.eclipse.rdf4j.testsuite.rio.turtle.TurtleParserTestCase;
import junit.framework.Test;
/**
* JUnit test for the Turtle parser that uses the tests that are available
* <a href="https://dvcs.w3.org/hg/rdf/file/09a9da374a9f/rdf-turtle/">online</a>.
*/
public class TurtleParserTest extends TurtleParserTestCase {
public static Test suite() throws Exception {
return new TurtleParserTest().createTestSuite();
}
@Override
protected RDFParser createTurtleParser() {
RDFParser result = new TurtleParser();
result.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true);
return result;
}
@Override
protected RDFParser createNTriplesParser() {
return new NTriplesParser();
}
}
|
cheeepsan/ure-test | src/main/java/ure/commands/CommandHotbar9.java | <filename>src/main/java/ure/commands/CommandHotbar9.java
package ure.commands;
public class CommandHotbar9 extends CommandHotbar {
public static final String id = "HOTBAR_9";
public CommandHotbar9() { super(id, 9); }
}
|
dasec/ForTrace | src/fortrace/botnet/net/proto/genericmessage_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: genericmessage.proto
from __future__ import absolute_import
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
# @@protoc_insertion_point(imports)
from . import messagetypes_pb2
import six
DESCRIPTOR = _descriptor.FileDescriptor(
name='genericmessage.proto',
package='',
serialized_pb='\n\x14genericmessage.proto\x1a\x12messagetypes.proto\"y\n\x0eGenericMessage\x12\"\n\x0cmessage_type\x18\x01 \x02(\x0e\x32\x0c.MessageType\x12\x12\n\nmessage_id\x18\x02 \x02(\x04\x12\x1d\n\x0erequest_answer\x18\x03 \x01(\x08:\x05\x66\x61lse*\x05\x08\x64\x10\xd0\x0f*\t\x08\xd0\x0f\x10\x80\x80\x80\x80\x02P\x00')
_GENERICMESSAGE = _descriptor.Descriptor(
name='GenericMessage',
full_name='GenericMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='message_type', full_name='GenericMessage.message_type', index=0,
number=1, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='message_id', full_name='GenericMessage.message_id', index=1,
number=2, type=4, cpp_type=4, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='request_answer', full_name='GenericMessage.request_answer', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=True,
extension_ranges=[(100, 2000), (2000, 536870912), ],
serialized_start=44,
serialized_end=165,
)
_GENERICMESSAGE.fields_by_name['message_type'].enum_type = messagetypes_pb2._MESSAGETYPE
DESCRIPTOR.message_types_by_name['GenericMessage'] = _GENERICMESSAGE
class GenericMessage(six.with_metaclass(_reflection.GeneratedProtocolMessageType, _message.Message)):
DESCRIPTOR = _GENERICMESSAGE
# @@protoc_insertion_point(class_scope:GenericMessage)
# @@protoc_insertion_point(module_scope)
|
JamesCao2048/BlizzardData | Corpus/swt/149.java | <gh_stars>1-10
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.examples.paint;
import org.eclipse.jface.action.*;
import org.eclipse.jface.resource.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.part.*;
/**
* The view for the paint application.
* All rendering happens inside the area created by createPartControl().
*
* @see ViewPart
*/
public class PaintView extends ViewPart {
PaintExample instance = null;
/**
* Constructs a Paint view.
*/
public PaintView() {
}
/**
* Creates the example.
*
* @see ViewPart#createPartControl
*/
@Override
public void createPartControl(Composite parent) {
instance = new PaintExample(parent);
instance.createGUI(parent);
/*** Add toolbar contributions ***/
final IActionBars actionBars = getViewSite().getActionBars();
IToolBarManager toolbarManager = actionBars.getToolBarManager();
Tool tools[] = PaintExample.tools;
String group = tools[0].group;
toolbarManager.add(new GroupMarker(group));
for (int i = 0; i < tools.length; i++) {
Tool tool = tools[i];
if (!tool.group.equals(group)) {
toolbarManager.add(new Separator());
toolbarManager.add(new GroupMarker(tool.group));
}
group = tool.group;
PaintAction action = new PaintAction(tool);
toolbarManager.appendToGroup(group, action);
if (i == PaintExample.Default_tool || i == PaintExample.Default_fill || i == PaintExample.Default_linestyle) {
action.setChecked(true);
}
}
actionBars.updateActionBars();
instance.setDefaults();
}
/**
* Called when the View is to be disposed
*/
@Override
public void dispose() {
instance.dispose();
instance = null;
super.dispose();
}
/**
* Returns the Display.
*
* @return the display we're using
*/
public Display getDisplay() {
return instance.getDisplay();
}
/**
* Called when we must grab focus.
*
* @see org.eclipse.ui.part.ViewPart#setFocus
*/
@Override
public void setFocus() {
instance.setFocus();
}
/**
* Action set glue.
*/
class PaintAction extends Action {
private int style;
private Runnable action;
public PaintAction(Tool tool) {
super();
String id = tool.group + '.' + tool.name;
setId(id);
style = tool.type == SWT.RADIO ? IAction.AS_RADIO_BUTTON : IAction.AS_PUSH_BUTTON;
action = tool.action;
setText(PaintExample.getResourceString(id + ".label"));
setToolTipText(PaintExample.getResourceString(id + ".tooltip"));
setDescription(PaintExample.getResourceString(id + ".description"));
setImageDescriptor(ImageDescriptor.createFromFile(
PaintExample.class,
PaintExample.getResourceString(id + ".image")));
}
@Override
public int getStyle() { return style; }
@Override
public void run() { action.run(); }
}
} |
fedlearn-jdt/fedlearn-core | core/src/test/java/com/jdt/fedlearn/core/encryption/differentialPrivacy/TestObjectivePerturbDPImpl.java | <filename>core/src/test/java/com/jdt/fedlearn/core/encryption/differentialPrivacy/TestObjectivePerturbDPImpl.java<gh_stars>10-100
package com.jdt.fedlearn.core.encryption.differentialPrivacy;
import com.jdt.fedlearn.core.type.DifferentialPrivacyType;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestObjectivePerturbDPImpl {
@Test
public void testGenerateNoises(){
IDifferentialPrivacy dp = DifferentialPrivacyFactory.createDifferentialPrivacy(DifferentialPrivacyType.OBJECTIVE_PERTURB);
dp.init(3, 100, 1000, 0.2, 1e-8, 0.1, 0.1, 666);
dp.generateNoises();
double[] noises = dp.getNoises();
Assert.assertEquals(noises.length, 3);
for(double noise: noises){
System.out.println(noise);
}
dp.init(3, 100, 1000, 0, 0, 0 ,0, 666);
dp.generateNoises();
noises = dp.getNoises();
Assert.assertEquals(noises.length, 3);
}
@Test
public void testAddNoises(){
IDifferentialPrivacy dp = DifferentialPrivacyFactory.createDifferentialPrivacy(DifferentialPrivacyType.OBJECTIVE_PERTURB);
double[] origin = new double[]{0.2, 0.5, 0.6};
dp.init(origin.length, 100, 1000, 0.2, 1e-8, 0.1, 0.1, 666);
dp.generateNoises();
double[] noises = dp.getNoises();
Assert.assertEquals(noises.length, origin.length);
for(double noise: noises){
System.out.println(noise);
}
dp.addNoises(origin, origin);
origin = new double[0];
dp.init(origin.length, 100, 1000, 0.2, 1e-8, 0.1, 0.1, 666);
dp.generateNoises();
noises = dp.getNoises();
Assert.assertEquals(noises.length, origin.length);
dp.addNoises(origin, origin);
}
@Test
public void testAdd2DNoises(){
IDifferentialPrivacy dp = DifferentialPrivacyFactory.createDifferentialPrivacy(DifferentialPrivacyType.OBJECTIVE_PERTURB);
dp.init(6, 100, 1000, 0.2, 1e-8, 0.1, 0.1, 666);
dp.generateNoises();
double[] noises = dp.getNoises();
Assert.assertEquals(noises.length, 6);
for(double noise: noises){
System.out.println(noise);
}
double[][] origin = new double[][]{{1}, {1}};
double[][] copy = new double[][]{{1}, {1}};
int index = 1;
dp.addNoises(origin, origin, index);
for(int i = 0; i < origin.length; i++){
for(int j = 0; j < origin[i].length; j++){
System.out.println(origin[i][j]);
Assert.assertEquals(origin[i][j], copy[i][j] - noises[index * origin.length + i] / 1000);
}
}
}
}
|
LuciusKyle/LeetCode | 0162_Find_Peak_Element/0162.cc |
#include <vector>
using std::vector;
class Solution {
public:
int findPeakElement(const vector<int>& nums) {
size_t lower_index = 0;
size_t upper_index = nums.size() - 1;
if (isPeak(lower_index, nums)) return lower_index;
if (isPeak(upper_index, nums)) return upper_index;
while (upper_index - lower_index > 1) {
const size_t mid_index = (lower_index + upper_index) / 2;
if (isPeak(mid_index, nums)) return mid_index;
if (nums[mid_index - 1] < nums[mid_index])
lower_index = mid_index;
else
upper_index = mid_index;
}
if (isPeak(lower_index, nums)) return lower_index;
if (isPeak(upper_index, nums)) return upper_index;
return 0;
}
private:
bool isPeak(const size_t index, const vector<int>& nums) {
if (index == 0) return nums[1] < nums[0];
if (index == nums.size() - 1) return nums[index - 1] < nums[index];
return nums[index - 1] < nums[index] && nums[index + 1] < nums[index];
}
};
int main(int argc, char const *argv[])
{
Solution sln;
int rtn = sln.findPeakElement({0, 1});
return 0;
}
|
Silver-birder/rapidus-cp | examples/call.js | const x = 10
function a(x) {
return {
b: function(x) {
console.log(":", x)
}
}
}
new a(x)
/*
New(
Call(
Identifier("a"),
[Identifier("x")]
)
)
*/
a.b(x)
/*
Call(
Member(
Identifier("a"),
"b"
),
[Identifier("x")]
),
*/
a(x)
/*
Call(
Identifier("a"),
[Identifier("x")]
)
*/ |
zorancuc/pizza_hero | app/containers/Activity/Activities/ActivityItem.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
export default function ActivityItem({ image, timeStamp, detail, detailTo }) {
return (
<div className="activity-item">
<div className="activity-info">
<div className="activity-image">
<img src={image} alt="" />
</div>
<div className="activity-details">
<div className="activity-time-stamp">{timeStamp}</div>
{detail}
</div>
</div>
<Link to={`/${detailTo}`} className="view-details-button w-inline-block">
<div>View Details</div>
</Link>
</div>
);
}
ActivityItem.propTypes = {
image: PropTypes.string,
timeStamp: PropTypes.string,
detail: PropTypes.object,
detailTo: PropTypes.string,
};
|
TheShellLand/crossover-source | gnutls/gnutls/lib/crypto-api.h | <filename>gnutls/gnutls/lib/crypto-api.h
/*
* Copyright (C) 2000-2016 Free Software Foundation, Inc.
* Copyright (C) 2016-2017 Red Hat, Inc.
*
* Author: <NAME>
*
* This file is part of GnuTLS.
*
* The GnuTLS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_LIB_CRYPTO_API_H
#define GNUTLS_LIB_CRYPTO_API_H
#include <gnutls_int.h>
inline static
int _gnutls_aead_cipher_init(gnutls_aead_cipher_hd_t handle,
gnutls_cipher_algorithm_t cipher,
const gnutls_datum_t * key)
{
const cipher_entry_st* e;
e = cipher_to_entry(cipher);
if (e == NULL || e->type != CIPHER_AEAD)
return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
return
_gnutls_cipher_init(&handle->ctx_enc, e, key,
NULL, 1);
}
inline static
void _gnutls_aead_cipher_deinit(gnutls_aead_cipher_hd_t handle)
{
api_aead_cipher_hd_st *h = handle;
_gnutls_cipher_deinit(&h->ctx_enc);
}
#endif /* GNUTLS_LIB_CRYPTO_API_H */
|
RGCbetty/Henkou | resources/js/components/RegistrationComponents/HenkouStatusHeader.js | <reponame>RGCbetty/Henkou
import React from 'react';
import { Button } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
const headers = [
{
title: 'Sequence',
dataIndex: 'sequence',
key: '1',
width: 70,
align: 'center',
fixed: 'left'
},
{
title: 'Received Date',
width: 140,
dataIndex: 'received_date',
key: '2',
align: 'center',
fixed: 'left'
},
{
title: 'Product / Process',
key: '3',
width: 300,
dataIndex: 'product_name',
align: 'center',
fixed: 'left'
},
{
title: 'Department',
width: 120,
dataIndex: 'department',
key: '4',
align: 'center'
},
{
title: 'Section',
width: 200,
dataIndex: 'section',
key: '5',
align: 'center'
},
{
title: 'Team',
width: 150,
dataIndex: 'team',
key: '6',
align: 'center'
},
{
title: 'Start',
key: '7',
width: 150,
dataIndex: 'start_date',
align: 'center',
width: 150,
render: (text, row, index) => (text ? <b>{text}</b> : <></>)
// render:
},
{
title: 'Pending',
key: '8',
width: 70,
dataIndex: 'house_type',
align: 'center',
render: () => <Button type="primary" shape="circle" icon={<EyeOutlined />} />
},
{
title: 'Finish',
key: '9',
dataIndex: 'finished_date',
align: 'center',
width: 150,
render: (text, row, index) => (text ? <b>{text}</b> : <></>)
},
{
title: 'Days in Process',
key: '10',
width: 100,
dataIndex: 'sequence',
align: 'center'
}
];
export default headers;
|
khamutov/intellij-scala | scala/scala-impl/src/org/jetbrains/plugins/scala/lang/resolve/processor/BaseProcessor.scala | package org.jetbrains.plugins.scala
package lang
package resolve
package processor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Key
import com.intellij.psi._
import com.intellij.psi.scope._
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.api._
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScTypeProjection
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScTypeAlias
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameter
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypedDefinition
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.imports.usages.ImportUsed
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScObject, ScTemplateDefinition}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiManager
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.synthetic.{ScSyntheticFunction, SyntheticClasses}
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.TypeDefinitionMembers
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.api._
import org.jetbrains.plugins.scala.lang.psi.types.api.designator.{ScDesignatorType, ScProjectionType, ScThisType}
import org.jetbrains.plugins.scala.lang.psi.types.recursiveUpdate.ScSubstitutor
import org.jetbrains.plugins.scala.lang.psi.types.result._
import org.jetbrains.plugins.scala.lang.resolve.processor.BaseProcessor.RecursionState
import org.jetbrains.plugins.scala.project.ProjectContext
import scala.collection.Set
object BaseProcessor {
def unapply(p: BaseProcessor) = Some(p.kinds)
val FROM_TYPE_KEY: Key[ScType] = Key.create("from.type.key")
val UNRESOLVED_TYPE_PARAMETERS_KEY: Key[Seq[TypeParameter]] = Key.create("unresolved.type.parameters.key")
val COMPOUND_TYPE_THIS_TYPE_KEY: Key[Option[ScType]] = Key.create("compound.type.this.type.key")
val FORWARD_REFERENCE_KEY: Key[java.lang.Boolean] = Key.create("forward.reference.key")
def isImplicitProcessor(processor: PsiScopeProcessor): Boolean = {
processor match {
case b: BaseProcessor => b.isImplicitProcessor
case _ => false
}
}
//todo ugly recursion breakers, maybe we need general for type? What about performance?
private case class RecursionState(visitedProjections: Set[PsiNamedElement],
visitedTypeParameter: Set[TypeParameterType]) {
def add(projection: PsiNamedElement): RecursionState =
copy(visitedProjections = visitedProjections + projection)
def add(tpt: TypeParameterType): RecursionState =
copy(visitedTypeParameter = visitedTypeParameter + tpt)
}
private object RecursionState {
val empty: RecursionState = RecursionState(Set.empty, Set.empty)
}
}
abstract class BaseProcessor(val kinds: Set[ResolveTargets.Value])
(implicit val projectContext: ProjectContext) extends PsiScopeProcessor {
protected var candidatesSet: Set[ScalaResolveResult] = Set.empty
def isImplicitProcessor: Boolean = false
def changedLevel: Boolean = true
protected var accessibility = true
def doNotCheckAccessibility() {accessibility = false}
override final def execute(element: PsiElement, state: ResolveState): Boolean = element match {
case namedElement: PsiNamedElement if ResolveUtils.kindMatches(namedElement, kinds) => execute(namedElement)(state)
case _ => true
}
protected def execute(namedElement: PsiNamedElement)
(implicit state: ResolveState): Boolean
def candidates: Array[ScalaResolveResult] = {
val set = candidatesS
val size = set.size
val res = JavaArrayFactoryUtil.ScalaResolveResultFactory.create(size)
if (size == 0) return res
val iter = set.iterator
var count = 0
while (iter.hasNext) {
val next = iter.next()
res(count) = next
count += 1
}
res
}
def candidatesS: Set[ScalaResolveResult] = candidatesSet
//todo: fix this ugly performance improvement
private var classKind = true
def setClassKind(classKind: Boolean) {
this.classKind = classKind
}
def getClassKind: Boolean = {
classKind && getClassKindInner
}
def getClassKindInner: Boolean = {
(kinds contains ResolveTargets.CLASS) ||
(kinds contains ResolveTargets.OBJECT) ||
(kinds contains ResolveTargets.METHOD)
}
//java compatibility
object MyElementClassHint extends ElementClassHint {
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
def shouldProcess(kind: DeclarationKind): Boolean = {
kind match {
case null => true
case DeclarationKind.PACKAGE => kinds contains ResolveTargets.PACKAGE
case DeclarationKind.CLASS if classKind =>
(kinds contains ResolveTargets.CLASS) || (kinds contains ResolveTargets.OBJECT) ||
(kinds contains ResolveTargets.METHOD) //case classes get 'apply' generated
case DeclarationKind.VARIABLE => (kinds contains ResolveTargets.VAR) || (kinds contains ResolveTargets.VAL)
case DeclarationKind.FIELD => (kinds contains ResolveTargets.VAR) || (kinds contains ResolveTargets.VAL)
case DeclarationKind.METHOD => kinds contains ResolveTargets.METHOD
case _ => false
}
}
}
override def getHint[T](hintKey: Key[T]): T = {
hintKey match {
case ElementClassHint.KEY => MyElementClassHint.asInstanceOf[T]
case _ => null.asInstanceOf[T]
}
}
def processType(t: ScType, place: PsiElement, state: ResolveState = ResolveState.initial()): Boolean =
processTypeImpl(t, place, state)(RecursionState.empty)
private def processTypeImpl(t: ScType, place: PsiElement,
state: ResolveState = ResolveState.initial(),
updateWithProjectionSubst: Boolean = true)
(implicit recState: RecursionState): Boolean = {
ProgressManager.checkCanceled()
t match {
case ScDesignatorType(clazz: PsiClass) if clazz.qualifiedName == "java.lang.String" =>
val plusMethod: ScType => ScSyntheticFunction = SyntheticClasses.get(place.getProject).stringPlusMethod
if (plusMethod != null) execute(plusMethod(t), state) //add + method
case _ =>
}
t match {
case ScThisType(clazz) =>
clazz.selfType match {
case None =>
processElement(clazz, ScSubstitutor.empty, place, state)
case Some(ScThisType(`clazz`)) =>
//to prevent SOE, let's process Element
processElement(clazz, ScSubstitutor.empty, place, state)
case Some(ScProjectionType(_, element)) if recState.visitedProjections.contains(element) =>
//recursion detected
true
case Some(selfType) =>
val clazzType = clazz.getTypeWithProjections().getOrElse(return true)
if (selfType.conforms(clazzType)) {
val newState =
state.put(BaseProcessor.COMPOUND_TYPE_THIS_TYPE_KEY, Some(t))
.put(ScSubstitutor.key, ScSubstitutor(ScThisType(clazz)))
processTypeImpl(selfType, place, newState)
}
else if (clazzType.conforms(selfType)) {
processElement(clazz, ScSubstitutor.empty, place, state)
}
else {
val glb = selfType.glb(clazzType)
val newState = state.put(BaseProcessor.COMPOUND_TYPE_THIS_TYPE_KEY, Some(t))
processTypeImpl(glb, place, newState)
}
}
case d@ScDesignatorType(e: PsiClass) if d.asInstanceOf[ScDesignatorType].isStatic && !e.isInstanceOf[ScTemplateDefinition] =>
//not scala from scala
var break = true
for (method <- e.getMethods if break && method.hasModifierProperty("static")) {
if (!execute(method, state)) break = false
}
for (cl <- e.getInnerClasses if break && cl.hasModifierProperty("static")) {
if (!execute(cl, state)) break = false
}
for (field <- e.getFields if break && field.hasModifierProperty("static")) {
if (!execute(field, state)) break = false
}
if (!break) return false
TypeDefinitionMembers.processEnum(e, execute(_, state))
case ScDesignatorType(o: ScObject) =>
processElement(o, ScSubstitutor.empty, place, state)
case ScDesignatorType(e: ScTypedDefinition) if place.isInstanceOf[ScTypeProjection] =>
val result: TypeResult =
e match {
case p: ScParameter => p.getRealParameterType
case _ => e.`type`()
}
result match {
case Right(tp) => processTypeImpl(tp, place, state)
case _ => true
}
case ScDesignatorType(e) =>
processElement(e, ScSubstitutor.empty, place, state)
case tpt: TypeParameterType =>
processTypeImpl(tpt.upperType, place, state, updateWithProjectionSubst = false)
case j: JavaArrayType =>
implicit val elementScope = place.elementScope
processTypeImpl(j.getParameterizedType.getOrElse(return true), place, state)
case p@ParameterizedType(designator, typeArgs) =>
designator match {
case tpt: TypeParameterType =>
if (recState.visitedTypeParameter.contains(tpt)) return true
val newState = state.put(ScSubstitutor.key, ScSubstitutor(p))
val substedType = p.substitutor.subst(ParameterizedType(tpt.upperType, typeArgs))
processTypeImpl(substedType, place, newState)(recState.add(tpt))
case _ => p.extractDesignatedType(expandAliases = false) match {
case Some((des, subst)) =>
processElement(des, subst, place, state)
case None => true
}
}
case proj@ScProjectionType(_, _) if proj.actualElement.isInstanceOf[ScTypeAlias] =>
val ta = proj.actualElement.asInstanceOf[ScTypeAlias]
val subst = proj.actualSubst
val upper = ta.upperBound.getOrElse(return true)
processTypeImpl(subst.subst(upper), place, state.put(ScSubstitutor.key, ScSubstitutor.empty))(recState.add(ta))
case proj@ScProjectionType(_, _) =>
val s: ScSubstitutor =
if (updateWithProjectionSubst)
ScSubstitutor(proj) followed proj.actualSubst
else proj.actualSubst
val actualElement = proj.actualElement
processElement(actualElement, s, place, state)(recState.add(actualElement))
case lit: ScLiteralType =>
processType(lit.wideType, place, state)
case StdType(name, tSuper) =>
SyntheticClasses.get(place.getProject).byName(name) match {
case Some(c) =>
if (!c.processDeclarations(this, state, null, place) ||
!(tSuper match {
case Some(ts) => processTypeImpl(ts, place)
case _ => true
})) return false
case None => //nothing to do
}
val scope = place.resolveScope
val obj: PsiClass = ScalaPsiManager.instance(place.getProject).getCachedClass(scope, "java.lang.Object").orNull
if (obj != null) {
val namesSet = Set("hashCode", "toString", "equals", "getClass")
val methods = obj.getMethods.iterator
while (methods.hasNext) {
val method = methods.next()
if (name == "AnyRef" || namesSet.contains(method.name)) {
if (!execute(method, state)) return false
}
}
}
true
case comp@ScCompoundType(_, _, _) =>
TypeDefinitionMembers.processDeclarations(comp, this, state, null, place)
case ex: ScExistentialType =>
processTypeImpl(ex.quantified, place, state.put(ScSubstitutor.key, ScSubstitutor.empty))
case ScExistentialArgument(_, _, _, upper) =>
processTypeImpl(upper, place, state)
case _ => true
}
}
private def processElement(e: PsiNamedElement, s: ScSubstitutor, place: PsiElement, state: ResolveState)
(implicit recState: RecursionState): Boolean = {
val subst = state.get(ScSubstitutor.key)
val compound = state.get(BaseProcessor.COMPOUND_TYPE_THIS_TYPE_KEY) //todo: looks like ugly workaround
val newSubst =
compound match {
case Some(_) => subst
case _ => if (subst != null) subst followed s else s
}
e match {
case ta: ScTypeAlias =>
if (recState.visitedProjections.contains(ta)) return true
val newState = state.put(ScSubstitutor.key, ScSubstitutor.empty)
processTypeImpl(s.subst(ta.upperBound.getOrAny), place, newState)(recState.add(ta))
//need to process scala way
case clazz: PsiClass =>
TypeDefinitionMembers.processDeclarations(clazz, BaseProcessor.this, state.put(ScSubstitutor.key, newSubst), null, place)
case des: ScTypedDefinition =>
val typeResult: TypeResult =
des match {
case p: ScParameter => p.getRealParameterType
case _ => des.`type`()
}
typeResult match {
case Right(tp) =>
val newState = state.put(ScSubstitutor.key, ScSubstitutor.empty)
processTypeImpl(newSubst subst tp, place, newState, updateWithProjectionSubst = false)
case _ => true
}
case pack: ScPackage =>
pack.processDeclarations(BaseProcessor.this, state.put(ScSubstitutor.key, newSubst), null, place)
case des =>
des.processDeclarations(BaseProcessor.this, state.put(ScSubstitutor.key, newSubst), null, place)
}
}
protected def getSubst(state: ResolveState): ScSubstitutor = {
val subst: ScSubstitutor = state.get(ScSubstitutor.key)
if (subst == null) ScSubstitutor.empty else subst
}
protected def getImports(state: ResolveState): Set[ImportUsed] = {
val used = state.get(ImportUsed.key)
if (used == null) Set[ImportUsed]() else used
}
protected def getFromType(state: ResolveState): Option[ScType] = {
state.get(BaseProcessor.FROM_TYPE_KEY).toOption
}
protected def isForwardReference(state: ResolveState): Boolean = {
val res: java.lang.Boolean = state.get(BaseProcessor.FORWARD_REFERENCE_KEY)
if (res != null) res
else false
}
} |
jbb-project/jbb | domain-services/jbb-permissions/src/main/java/org/jbb/permissions/impl/acl/DefaultPermissionMatrixService.java | <reponame>jbb-project/jbb
/*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.permissions.impl.acl;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.jbb.lib.eventbus.JbbEventBus;
import org.jbb.permissions.api.PermissionMatrixService;
import org.jbb.permissions.api.exceptions.PermissionRoleNotFoundException;
import org.jbb.permissions.api.identity.SecurityIdentity;
import org.jbb.permissions.api.matrix.PermissionMatrix;
import org.jbb.permissions.api.matrix.PermissionTable;
import org.jbb.permissions.api.permission.Permission;
import org.jbb.permissions.api.permission.PermissionType;
import org.jbb.permissions.api.permission.PermissionValue;
import org.jbb.permissions.api.role.PermissionRoleDefinition;
import org.jbb.permissions.impl.PermissionCaches;
import org.jbb.permissions.impl.acl.dao.AclEntryRepository;
import org.jbb.permissions.impl.acl.model.AclEntryEntity;
import org.jbb.permissions.impl.acl.model.AclPermissionCategoryEntity;
import org.jbb.permissions.impl.acl.model.AclPermissionEntity;
import org.jbb.permissions.impl.acl.model.AclPermissionTypeEntity;
import org.jbb.permissions.impl.acl.model.AclSecurityIdentityEntity;
import org.jbb.permissions.impl.role.RoleTranslator;
import org.jbb.permissions.impl.role.dao.AclActiveRoleRepository;
import org.jbb.permissions.impl.role.dao.AclRoleRepository;
import org.jbb.permissions.impl.role.model.AclActiveRoleEntity;
import org.jbb.permissions.impl.role.model.AclRoleEntity;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class DefaultPermissionMatrixService implements PermissionMatrixService {
private final PermissionTypeTranslator permissionTypeTranslator;
private final SecurityIdentityTranslator securityIdentityTranslator;
private final RoleTranslator roleTranslator;
private final PermissionTableTranslator permissionTableTranslator;
private final PermissionTranslator permissionTranslator;
private final AclEntryRepository aclEntryRepository;
private final AclActiveRoleRepository aclActiveRoleRepository;
private final AclRoleRepository aclRoleRepository;
private final PermissionCaches permissionCaches;
private final JbbEventBus eventBus;
private final PermissionChangedEventCreator eventCreator;
@Override
public PermissionMatrix getPermissionMatrix(PermissionType permissionType,
SecurityIdentity securityIdentity) {
AclPermissionTypeEntity permissionTypeEntity = permissionTypeTranslator
.toEntity(permissionType);
AclSecurityIdentityEntity securityIdentityEntity = securityIdentityTranslator
.toEntity(securityIdentity)
.orElseThrow(() -> new IllegalArgumentException("Security identity doesn't exist"));
Optional<AclActiveRoleEntity> activeRoleEntity = aclActiveRoleRepository
.findActiveByPermissionTypeAndSecurityIdentity(
permissionTypeEntity, securityIdentityEntity
);
Optional<PermissionRoleDefinition> assignedRole = activeRoleEntity
.map(activeRole -> roleTranslator.toApiModel(activeRole.getRole()));
Optional<PermissionTable> permissionTable = Optional.empty();
if (!activeRoleEntity.isPresent()) {
List<AclEntryEntity> aclEntries = Lists.newArrayList();
for (AclPermissionCategoryEntity category : permissionTypeEntity.getCategories()) {
for (AclPermissionEntity permission : category.getPermissions()) {
AclEntryEntity aclEntry = aclEntryRepository
.findBySecurityIdentityAndPermission(securityIdentityEntity, permission)
.orElse(defaultNegativeEntry(securityIdentityEntity, permission));
aclEntries.add(aclEntry);
}
}
permissionTable = Optional.of(permissionTableTranslator.toApiModel(aclEntries));
}
return PermissionMatrix.builder()
.permissionType(permissionType)
.securityIdentity(securityIdentity)
.assignedRole(assignedRole)
.permissionTable(permissionTable)
.build();
}
private AclEntryEntity defaultNegativeEntry(AclSecurityIdentityEntity securityIdentityEntity,
AclPermissionEntity permission) {
return AclEntryEntity.builder()
.securityIdentity(securityIdentityEntity)
.permission(permission)
.entryValue(PermissionValue.NO)
.build();
}
@Override
@Transactional
public void setPermissionMatrix(PermissionMatrix matrix) {
permissionCaches.clearCaches();
AclPermissionTypeEntity permissionType = permissionTypeTranslator
.toEntity(matrix.getPermissionType());
AclSecurityIdentityEntity securityIdentity = securityIdentityTranslator
.toEntity(matrix.getSecurityIdentity())
.orElseThrow(() -> new IllegalArgumentException("Security identity doesn't exist"));
Optional<PermissionRoleDefinition> assignedRoleOptional = matrix.getAssignedRole();
Optional<PermissionTable> permissionTableOptional = matrix.getPermissionTable();
if (assignedRoleOptional.isPresent() && permissionTableOptional.isPresent()) {
throw new IllegalArgumentException(
"Matrix can't have assigned role and own permission table");
} else if (!assignedRoleOptional.isPresent() && !permissionTableOptional.isPresent()) {
throw new IllegalArgumentException(
"Matrix should have assigned role or permission table");
}
assignedRoleOptional
.ifPresent(role -> setRoleForMatrix(role, permissionType, securityIdentity));
permissionTableOptional.ifPresent(
table -> setPermissionTableForMatrix(table, permissionType, securityIdentity));
eventBus.post(eventCreator.create(matrix));
}
private void setRoleForMatrix(PermissionRoleDefinition role,
AclPermissionTypeEntity permissionType,
AclSecurityIdentityEntity securityIdentity) {
// clean up current table
for (AclPermissionCategoryEntity category : permissionType.getCategories()) {
for (AclPermissionEntity permission : category.getPermissions()) {
aclEntryRepository
.deleteAllBySecurityIdentityAndPermission(securityIdentity, permission);
}
}
// create or update active role
AclRoleEntity roleEntity = aclRoleRepository.findById(role.getId())
.orElseThrow(() -> new PermissionRoleNotFoundException(role.getId()));
AclActiveRoleEntity aclActiveRole = aclActiveRoleRepository
.findActiveByPermissionTypeAndSecurityIdentity(permissionType, securityIdentity)
.orElse(AclActiveRoleEntity.builder().securityIdentity(securityIdentity).build());
aclActiveRole.setRole(roleEntity);
aclActiveRoleRepository.save(aclActiveRole);
}
private void setPermissionTableForMatrix(PermissionTable permissionTable,
AclPermissionTypeEntity permissionType,
AclSecurityIdentityEntity securityIdentity) {
// clean up active role
aclActiveRoleRepository.findActiveByPermissionTypeAndSecurityIdentity(
permissionType, securityIdentity).ifPresent(aclActiveRoleRepository::delete);
// create or update table
Set<Permission> permissions = permissionTable.getPermissions();
Set<AclPermissionEntity> permissionEntities = permissions.stream()
.map(permissionTranslator::toEntity)
.collect(Collectors.toSet());
Set<AclEntryEntity> permissionEntries = permissionEntities.stream()
.map(permissionEntity -> aclEntryRepository
.findBySecurityIdentityAndPermission(securityIdentity, permissionEntity)
.orElse(AclEntryEntity.builder()
.securityIdentity(securityIdentity)
.permission(permissionEntity)
.build()
)
).collect(Collectors.toSet());
permissionEntries.forEach(entry -> updatePermissionValue(entry, permissions));
aclEntryRepository.saveAll(permissionEntries);
}
private void updatePermissionValue(AclEntryEntity entry, Set<Permission> permissions) {
PermissionValue newPermissionValue = permissions.stream()
.filter(p -> p.getDefinition().getCode().equals(entry.getPermission().getCode()))
.map(Permission::getValue).findFirst().orElse(PermissionValue.NO);
entry.setEntryValue(newPermissionValue);
}
}
|
esean/stl_voro_fill | sw/vtk_scripts/TubesFromSplines/TubesFromSplines.cxx | // todo:
// - compute min/max distance across all faces, then we can use this to adjust knob to min needed
#define NmStl 1 // 1=just one STL putput, 4= output this number STL files
#define NmStl_Arr 4
#include "../common/vtk_common.h"
#include <vtkSmartPointer.h>
#include <vtkVersion.h>
#include <vtkParametricFunctionSource.h>
#include <vtkTupleInterpolator.h>
#include <vtkTubeFilter.h>
#include <vtkParametricSpline.h>
#include <vtkDoubleArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkTriangleFilter.h>
#include <vtkSTLWriter.h>
#include <vtkAppendPolyData.h>
#include <vtkCleanPolyData.h>
#include <vtkCellLocator.h>
#include <sys/time.h>
#define CFG_DO_RENDER 0 // always gens an STL, but 1=display on screen, 0=not
#define FCN_RESOLUTION 2 // (3=low, 10=high perf ) defines how detailed are curves
#define PIPE_SIDES 2 // (10=low, 20=high perf) how many sides define outline of pipe
#define FCN_RESOLUTION_HP 3 // high-performance
#define PIPE_SIDES_HP 6 // high-performance
#define MIN_LCL_RAD 0.1
/////////////
// todo: make class
#define mUNDEF -1000 // probably can't get that in model x,y,z
typedef struct {
double sum;
int cnt;
double min,max;
} anAvg;
typedef struct {
anAvg x,y,z;
} aPtAvg;
void aPtAvg_clear(aPtAvg *pt) {
pt->x.sum = pt->x.cnt = 0.0;
pt->x.min = pt->x.max = mUNDEF;
pt->y.sum = pt->y.cnt = 0.0;
pt->y.min = pt->y.max = mUNDEF;
pt->z.sum = pt->z.cnt = 0.0;
pt->z.min = pt->z.max = mUNDEF;
}
void aPtAvg_add_x(aPtAvg *pt, double sum) {
pt->x.sum += sum;
pt->x.cnt++;
if ((sum > pt->x.max) || (pt->x.max == mUNDEF)) pt->x.max = sum;
if ((sum < pt->x.min) || (pt->x.min == mUNDEF)) pt->x.min = sum;
}
void aPtAvg_add_y(aPtAvg *pt, double sum) {
pt->y.sum += sum;
pt->y.cnt++;
if ((sum > pt->y.max) || (pt->y.max == mUNDEF)) pt->y.max = sum;
if ((sum < pt->y.min) || (pt->y.min == mUNDEF)) pt->y.min = sum;
}
void aPtAvg_add_z(aPtAvg *pt, double sum) {
pt->z.sum += sum;
pt->z.cnt++;
if ((sum > pt->z.max) || (pt->z.max == mUNDEF)) pt->z.max = sum;
if ((sum < pt->z.min) || (pt->z.min == mUNDEF)) pt->z.min = sum;
}
void aPtAvg_add_xyz(aPtAvg *pt, double x, double y, double z) {
// printf("### DBG: %f,%f,%f\n",x,y,z);
aPtAvg_add_x(pt,x);
aPtAvg_add_y(pt,y);
aPtAvg_add_z(pt,z);
// printf("### DBG: delX = %f %f\n",pt->x.min,pt->x.max);
// printf("### DBG: delY = %f %f\n",pt->y.min,pt->y.max);
// printf("### DBG: delZ = %f %f\n",pt->z.min,pt->z.max);
}
void aPtAvg_get_avgs(aPtAvg *pt, double *x, double *y, double *z, double *delx, double *dely, double *delz) {
*x = pt->x.sum / pt->x.cnt;
*y = pt->y.sum / pt->y.cnt;
*z = pt->z.sum / pt->z.cnt;
*delx = pt->x.max - pt->x.min;
*dely = pt->y.max - pt->y.min;
*delz = pt->z.max - pt->z.min;
}
/////////////
//typedef struct {
// float x,y,z;
//} aPt;
void find_midpoint_along_line_from(aPt p1, aPt p2, aPt &ret) {
ret.x = (p1.x + p2.x)/2.0;
ret.y = (p1.y + p2.y)/2.0;
ret.z = (p1.z + p2.z)/2.0;
}
void find_spline_points(aPt p1, aPt p2, aPt p3,
aPt &ret1, aPt &ret2, aPt &ret3) {
find_midpoint_along_line_from(p1,p2,ret1);
find_midpoint_along_line_from(p2,p3,ret3);
aPt xx;
find_midpoint_along_line_from(ret1,ret3,xx);
find_midpoint_along_line_from(xx,p2,ret2);
}
void calc_stat_spline(aPtAvg *aptavg, aPt p1, aPt p2, aPt p3, aPt *min, aPt *max, aPt *ret_middle) {
// printf("calc_stat_spline(%f,%f,%f,%f,%f,%f,%f,%f,%f);\n",p1.x,p1.y,p1.z,p2.x,p2.y,p2.z,p3.x,p3.y,p3.z);
max->x = std::max(max->x,p1.x);
max->x = std::max(max->x,p2.x);
max->x = std::max(max->x,p3.x);
min->x = std::min(min->x,p1.x);
min->x = std::min(min->x,p2.x);
min->x = std::min(min->x,p3.x);
max->y = std::max(max->y,p1.y);
max->y = std::max(max->y,p2.y);
max->y = std::max(max->y,p3.y);
min->y = std::min(min->y,p1.y);
min->y = std::min(min->y,p2.y);
min->y = std::min(min->y,p3.y);
max->z = std::max(max->z,p1.z);
max->z = std::max(max->z,p2.z);
max->z = std::max(max->z,p3.z);
min->z = std::min(min->z,p1.z);
min->z = std::min(min->z,p2.z);
min->z = std::min(min->z,p3.z);
// add_spline()...
// p1.x *= scaling; p1.y *= scaling; p1.z *= scaling;
// p2.x *= scaling; p2.y *= scaling; p2.z *= scaling;
// p3.x *= scaling; p3.y *= scaling; p3.z *= scaling;
aPt r1,r2,r3;
find_spline_points(p1,p2,p3,r1,r2,r3);
// points->InsertNextPoint(r1.x,r1.y,r1.z);
// points->InsertNextPoint(r2.x,r2.y,r2.z);
// points->InsertNextPoint(r3.x,r3.y,r3.z);
ret_middle->x = r2.x;
ret_middle->y = r2.y;
ret_middle->z = r2.z;
aPtAvg_add_xyz(aptavg,r2.x, r2.y, r2.z);
}
void add_spline(vtkPoints *points, double scaling, aPtAvg *aptavg, aPt p1, aPt p2, aPt p3, aPt *ret_middle) {
// printf("add_spline(points,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f);\n",scaling,p1.x,p1.y,p1.z,p2.x,p2.y,p2.z,p3.x,p3.y,p3.z);
p1.x *= scaling; p1.y *= scaling; p1.z *= scaling;
p2.x *= scaling; p2.y *= scaling; p2.z *= scaling;
p3.x *= scaling; p3.y *= scaling; p3.z *= scaling;
aPt r1,r2,r3;
find_spline_points(p1,p2,p3,r1,r2,r3);
points->InsertNextPoint(r1.x,r1.y,r1.z);
points->InsertNextPoint(r2.x,r2.y,r2.z);
points->InsertNextPoint(r3.x,r3.y,r3.z);
ret_middle->x = r2.x;
ret_middle->y = r2.y;
ret_middle->z = r2.z;
aPtAvg_add_xyz(aptavg,r2.x, r2.y, r2.z);
}
int parse_line(char *ln, aPt &p1, aPt &p2, aPt &p3) {
return sscanf(ln,"%f,%f,%f,%f,%f,%f,%f,%f,%f", &p1.x, &p1.y, &p1.z,
&p2.x, &p2.y, &p2.z, &p3.x, &p3.y, &p3.z);
}
int min(int x, int y) {
return (x > y) ? y : x;
}
int max(int x, int y) {
return (x < y) ? y : x;
}
void usage(char* str) {
shared_print_version();
printf("\nUSAGE: %s {[OPTIONS]} [REQUIRED ARGS]\n",str);
printf("\n{[OPTIONS]}:\n");
printf("\t[-i [IN CSV]]\t print stats about input [IN_CSV]\n");
printf("\t[-p]\t high performance render (anything for 3d printing)\n");
printf("\n[REQUIRED ARGS]:\n");
printf("\t[IN CSV] [inner pipe diameter] [outside pipe diameter scaling factor] [output STL name] [overall x,y,z scaling factor]\n");
printf("Scaling is applied to point in [IN CSV] and to [pipe diameter].\n");
printf("Example:\n");
printf("\t%s -p cad_small-cylinder.csv 1 0 $PWD/out.stl 1\n",str);
printf("\n");
}
int main(int argc, char *argv[])
{
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
if (argc == 1) {
usage(argv[0]);
return EXIT_FAILURE;
}
int argc_cnt = 1;
bool just_show_file_into_quit = false;
if (!strcmp(argv[argc_cnt],"-i")) {
argc_cnt++;
just_show_file_into_quit = true;
} else if ( argc < 6 ) {
usage(argv[0]);
return 1;
}
int mFCN_RESOLUTION = FCN_RESOLUTION;
int mPIPE_SIDES = PIPE_SIDES;
if (!strcmp(argv[argc_cnt],"-p")) {
argc_cnt++;
mFCN_RESOLUTION = FCN_RESOLUTION_HP;
mPIPE_SIDES = PIPE_SIDES_HP;
}
char* in_fn = argv[argc_cnt++];
FILE* file = fopen(in_fn,"r");
if (!file) {
fprintf(stderr, "ERROR: file(%s) could not open file!\n",in_fn);
return 2;
}
printf("# DEBUGCFG: IN FILE = %s\n",in_fn);
double rad;
double pipe_rad_scaling;
char* out_stl;
double scaling = 1.0;
if (!just_show_file_into_quit) {
rad = atof(argv[argc_cnt++]);
pipe_rad_scaling = atof(argv[argc_cnt++]);
out_stl = argv[argc_cnt++];
scaling = atof(argv[argc_cnt++]);
rad *= scaling;
printf("# DEBUGCFG: PIPE DIAMETER = %f\n",rad);
printf("# DEBUGCFG: PIPE DIAMETER SCALING = %f\n",pipe_rad_scaling);
printf("# DEBUGCFG: SCALING = %f x\n",scaling);
printf("# DEBUGCFG: OUT STL = %s\n",out_stl);
printf("# DEBUGCFG: NUMBER STL FILES OUTPUT = %d, array = %d\n",NmStl,NmStl_Arr);
}
// Setup render window, renderer, and interactor
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindow->AddRenderer(renderer);
renderWindowInteractor->SetRenderWindow(renderWindow);
vtkSmartPointer<vtkAppendPolyData> appendFilter[NmStl_Arr];
for (int i=0; i < NmStl_Arr; ++i)
appendFilter[i] = vtkSmartPointer<vtkAppendPolyData>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
//
//-----------------------------------
// calculate stats, file total spline/face/cell counts, min/max for each x/y/z so we know center axis vector
//-----------------------------------
//
char line[1024];
bool added_splines = false;
int total_splines, total_cells, total_faces;
total_splines = total_cells = total_faces = 0;
aPt model_min = {0,0,0};
aPt model_max = {0,0,0};
aPtAvg avg_face_xyz;
aPtAvg_clear(&avg_face_xyz);
double max_dist;
printf("## DELTAS(x,y,z,sz_vec): # x,y,z,sz_vec,face_min,face_max\n");
aPt ret_middle;
aPt start;
double face_min = 1e+6;
double face_max = 0;
while (fgets(line, sizeof(line), file)) {
for (uint16_t i=0; i<strlen(line); ++i)
if ((line[i] == '\r') || (line[i] == '\n')) line[i] = 0;
aPt p1,p2,p3;
int cnt = parse_line(line,p1,p2,p3);
if (cnt == 9)
{
// todo: should add scaling to this call to be consistent, then don't need mess below
calc_stat_spline(&avg_face_xyz,p1,p2,p3,&model_min,&model_max,&ret_middle);
if (!added_splines)
start = ret_middle;
else
{
double dx = ret_middle.x - start.x;
double dy = ret_middle.y - start.y;
double dz = ret_middle.z - start.z;
double start_dist = std::sqrt(dx*dx + dy*dy + dz*dz);
face_min = (start_dist < face_min) ? start_dist : face_min;
face_max = (start_dist > face_max) ? start_dist : face_max;
}
added_splines = true;
total_splines++;
}
else if ( (cnt == 1) && added_splines)
{
added_splines = false;
total_faces++;
double x,y,z;
double delx,dely,delz;
aPtAvg_get_avgs(&avg_face_xyz, &x,&y,&z, &delx,&dely,&delz);
// todo: mess referedto
double dist = sqrt(x*x*scaling*scaling + y*y*scaling*scaling);
aPtAvg_clear(&avg_face_xyz);
if (dist > max_dist) max_dist = dist;
// printf("## CALC: %f,%f,%f => %f (%f)\n",x,y,z,dist,max_dist);
double sz_vec = sqrt(delx*delx + dely*dely + delz*delz);
printf("## FACE %d DELTAS(x,y,z,sz_vec): %f,%f,%f,%f,%f,%f\n",total_faces,
delx,dely,delz,
sz_vec,
face_min,face_max);
face_min = 1e+6;
face_max = 0;
}
else if (cnt == -1)
{
added_splines = false;
total_cells++;
}
}
printf("# TOTAL splines = %d, faces = %d, cells = %d\n",total_splines,total_faces,total_cells);
printf("# x(%f,%f) y(%f,%f) z(%f,%f) max_dist = %f\n",model_min.x,model_max.x,
model_min.y,model_max.y,
model_min.z,model_max.z,
max_dist/scaling);
if (just_show_file_into_quit) return(0);
//
//-----------------------------------
// now draw the file
//-----------------------------------
//
rewind(file);
int now_splines, now_cells, now_faces;
now_splines = now_cells = now_faces = 0;
int print_stat_cnt = 0;
added_splines = false;
double min_tube_radius = 0.0;
while (fgets(line, sizeof(line), file)) {
for (uint16_t i=0; i<strlen(line); ++i)
if ((line[i] == '\r') || (line[i] == '\n')) line[i] = 0;
aPt p1,p2,p3;
int cnt = parse_line(line,p1,p2,p3);
if (cnt == 9)
{
added_splines = true;
now_splines++;
add_spline(points,scaling,&avg_face_xyz,p1,p2,p3,&ret_middle);
}
else if ( (cnt == 1) && added_splines)
{
added_splines = false;
// printf("# draw all pipes\n");
now_faces++;
// Fit a spline to the points
vtkSmartPointer<vtkParametricSpline> spline = vtkSmartPointer<vtkParametricSpline>::New();
spline->SetPoints(points);
vtkSmartPointer<vtkParametricFunctionSource> functionSource = vtkSmartPointer<vtkParametricFunctionSource>::New();
functionSource->SetParametricFunction(spline);
functionSource->SetUResolution(mFCN_RESOLUTION * points->GetNumberOfPoints());
functionSource->Update();
points->Reset();
double lcl_rad = rad;
double x,y,z;
double delx,dely,delz;
aPtAvg_get_avgs(&avg_face_xyz, &x,&y,&z, &delx,&dely,&delz);
double dist = sqrt(x*x + y*y);
// 012417: assumes model is a cylinder with half-sphere on top, when z is in
// that tip, reduce pipe radius for distance
if (z > (model_max.z - x/2))
dist = sqrt(x*x + y*y + z*z);
lcl_rad = rad - (rad * pipe_rad_scaling) * (dist/max_dist);
// printf("## %f,%f,%f => %f dist / %f max_dist = %f lcl_rad\n",x,y,z,dist,max_dist,lcl_rad);
aPtAvg_clear(&avg_face_xyz);
double sz_vec = sqrt(delx*delx + dely*dely + delz*delz);
// Generate the radius scalars
vtkSmartPointer<vtkDoubleArray> tubeRadius = vtkSmartPointer<vtkDoubleArray>::New();
unsigned int n = functionSource->GetOutput()->GetNumberOfPoints();
tubeRadius->SetNumberOfTuples(n);
tubeRadius->SetName("TubeRadius");
for (unsigned int i = 0; i < n; ++i)
tubeRadius->SetTuple1(i, lcl_rad);
// printf("# LCL_RAD %f\n",lcl_rad);
min_tube_radius = (min_tube_radius == 0.0) ? lcl_rad : std::min(min_tube_radius,lcl_rad);
if (lcl_rad < MIN_LCL_RAD) {
fprintf(stderr,"ERROR: tube radius %f less than min value %f\n",lcl_rad,MIN_LCL_RAD);
exit(1);
}
// Add the scalars to the polydata
vtkSmartPointer<vtkPolyData> tubePolyData = vtkSmartPointer<vtkPolyData>::New();
tubePolyData = functionSource->GetOutput();
tubePolyData->GetPointData()->AddArray(tubeRadius);
tubePolyData->GetPointData()->SetActiveScalars("TubeRadius");
// todo: only need to compute the colors[] for which index of NmStl we are filling
int nV = n;
vtkSmartPointer<vtkUnsignedCharArray> colors[NmStl_Arr];
for (int i=0; i < NmStl_Arr; ++i) {
colors[i] = vtkSmartPointer<vtkUnsignedCharArray>::New();
colors[i]->SetName("Colors");
colors[i]->SetNumberOfComponents(3);
colors[i]->SetNumberOfTuples(nV);
int v,x,b;
#if NmStl == 1
v = 128;
x = 191;
b = 64;
#else
#define CLR_MIN 50
double g = CLR_MIN + (((255 * 3)-CLR_MIN) * (double)i / (double)NmStl_Arr);
v = min((int)g,255);
x = min(max((int)g-255,0),255);
b = min(max((int)g-255*2,0),255);
#endif
v = min(v,255);
x = min(x,255);
b = min(b,255);
// printf("# DBG CLR %d: %d %d %d\n",i,v,x,b);
for (int j = 0; j < nV ;j++)
colors[i]->InsertTuple3(j,v,x,b);
}
// Create the tubes
vtkSmartPointer<vtkTubeFilter> tuber = vtkSmartPointer<vtkTubeFilter>::New();
#if VTK_MAJOR_VERSION <= 5
tuber->SetInput(tubePolyData);
#else
tuber->SetInputData(tubePolyData);
#endif
tuber->SetNumberOfSides(mPIPE_SIDES);
tuber->SetVaryRadiusToVaryRadiusByAbsoluteScalar();
//--------------
// Setup actors and mappers
vtkSmartPointer<vtkPolyDataMapper> tubeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
tubeMapper->SetInputConnection(tuber->GetOutputPort());
tubeMapper->SetScalarRange(tubePolyData->GetScalarRange());
vtkSmartPointer<vtkActor> tubeActor = vtkSmartPointer<vtkActor>::New();
tubeActor->SetMapper(tubeMapper);
vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New();
triangleFilter->SetInputConnection(tuber->GetOutputPort());
triangleFilter->Update();
tubeMapper->ScalarVisibilityOn();
tubeMapper->SetScalarModeToUsePointFieldData();
tubeMapper->SelectColorArray("Colors");
vtkSmartPointer<vtkPolyData> input1 = vtkSmartPointer<vtkPolyData>::New();
input1->ShallowCopy(triangleFilter->GetOutput());
// // Create the tree
// vtkSmartPointer<vtkCellLocator> cellLocator =
// vtkSmartPointer<vtkCellLocator>::New();
// cellLocator->SetDataSet(tuber->GetOutput());
// cellLocator->BuildLocator();
//
//// printf("#># %f %f %f\n",ret_middle.x,ret_middle.y,ret_middle.z);
// double testPoint[3] = {ret_middle.x, ret_middle.y, ret_middle.z};
//
// //Find the closest points to TestPoint
// double closestPoint[3];//the coordinates of the closest point will be returned here
// double closestPointDist2; //the squared distance to the closest point will be returned here
// vtkIdType cellId; //the cell id of the cell containing the closest point will be returned here
// int subId; //this is rarely used (in triangle strips only, I believe)
// cellLocator->FindClosestPoint(testPoint, closestPoint, cellId, subId, closestPointDist2);
//
// std::cout << "Coordinates of closest point: " << closestPoint[0] << " " << closestPoint[1] << " " << closestPoint[2] << std::endl;
// std::cout << "Squared distance to closest point: " << closestPointDist2 << std::endl;
// std::cout << "CellId: " << cellId << std::endl;
//
//-----------------------------------
// decide which STL to place
//-----------------------------------
//
if ((NmStl>3) && (delx < 0.25) && (dely > 0.25))
{
appendFilter[3]->AddInputData(input1);
appendFilter[3]->Update();
tubePolyData->GetPointData()->AddArray(colors[3]);
}
else if ((NmStl>2) && delz < 1.0)
{
appendFilter[2]->AddInputData(input1);
appendFilter[2]->Update();
tubePolyData->GetPointData()->AddArray(colors[2]);
}
else if ((NmStl>1) && sz_vec >= 3.0)
{
appendFilter[1]->AddInputData(input1);
appendFilter[1]->Update();
tubePolyData->GetPointData()->AddArray(colors[1]);
}
else if ((NmStl>0) )
{
appendFilter[0]->AddInputData(input1);
appendFilter[0]->Update();
tubePolyData->GetPointData()->AddArray(colors[0]);
}
//
//-----------------------------------
//
renderer->AddActor(tubeActor);
}
else if (cnt == -1)
{
added_splines = false;
now_cells++;
// printf("# empty line - one voronoi cell is complete\n");
}
// else
// printf("# ignore - found 'draw_all_pipes' but no points had been added, probably start of next voronoi cell draw_pipes in csv");
if (print_stat_cnt++ >= 100) {
print_stat_cnt = 0;
gettimeofday(&tv2, NULL);
double secs_so_far = (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec);
int remaining_splines = total_splines - now_splines;
double projTotalTime = secs_so_far * ((double)total_splines / (double)now_splines);
double projRemainingTime = projTotalTime - secs_so_far;
printf ("# STAT: %f seconds, %f remaining: %d / %d splines, %d / %d faces, %d / %d cells, min_radius %f\n",
secs_so_far, projRemainingTime,
now_splines, total_splines,
now_faces, total_faces,
now_cells, total_cells,
min_tube_radius);
}
}
// input CSV file needs to end with a line containing just one number, so we call "draw_all_pipes()"
if (added_splines)
{
fprintf(stderr,"ERROR: Your input CSV file is mis-formatted. You need to call draw all pipes!\n");
fprintf(stderr,"ERROR: Edit your input CSV file and add a line at the end, with a single number, such as,\n");
fprintf(stderr,"0\n");
exit(1);
}
//
//-----------------------------------
// Output STL file(s)
//-----------------------------------
//
// Remove any duplicate points and out STL
// need #num STL
vtkSmartPointer<vtkCleanPolyData> cleanFilter[NmStl_Arr];
for (int i=0; i < NmStl; ++i) {
cleanFilter[i] = vtkSmartPointer<vtkCleanPolyData>::New();
cleanFilter[i]->SetInputConnection(appendFilter[i]->GetOutputPort());
cleanFilter[i]->Update();
// make STL output
vtkSmartPointer<vtkSTLWriter> stlWriter = vtkSmartPointer<vtkSTLWriter>::New();
char new_str[512];
sprintf(new_str,"%s-%d.stl",out_stl,i);
stlWriter->SetFileName(new_str);
stlWriter->SetFileTypeToBinary();
stlWriter->SetInputConnection(cleanFilter[i]->GetOutputPort());
stlWriter->Write();
}
gettimeofday(&tv2, NULL);
printf ("# STAT: %f seconds: STL written\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
#if CFG_DO_RENDER
// go!
renderer->SetBackground(.4, .5, .6);
renderWindow->Render();
renderWindowInteractor->Start();
#endif
return EXIT_SUCCESS;
}
|
pierreprinetti/gophercloud | openstack/loadbalancer/v2/quotas/testing/fixtures.go | package testing
import "github.com/pierreprinetti/gophercloud/v3/openstack/loadbalancer/v2/quotas"
const GetResponseRaw_1 = `
{
"quota": {
"loadbalancer": 15,
"listener": 30,
"member": -1,
"pool": 15,
"healthmonitor": 30,
"l7policy": 100,
"l7rule": -1
}
}
`
const GetResponseRaw_2 = `
{
"quota": {
"load_balancer": 15,
"listener": 30,
"member": -1,
"pool": 15,
"health_monitor": 30,
"l7policy": 100,
"l7rule": -1
}
}
`
var GetResponse = quotas.Quota{
Loadbalancer: 15,
Listener: 30,
Member: -1,
Pool: 15,
Healthmonitor: 30,
L7Policy: 100,
L7Rule: -1,
}
const UpdateRequestResponseRaw_1 = `
{
"quota": {
"loadbalancer": 20,
"listener": 40,
"member": 200,
"pool": 20,
"healthmonitor": -1,
"l7policy": 50,
"l7rule": 100
}
}
`
const UpdateRequestResponseRaw_2 = `
{
"quota": {
"load_balancer": 20,
"listener": 40,
"member": 200,
"pool": 20,
"health_monitor": -1,
"l7policy": 50,
"l7rule": 100
}
}
`
var UpdateResponse = quotas.Quota{
Loadbalancer: 20,
Listener: 40,
Member: 200,
Pool: 20,
Healthmonitor: -1,
L7Policy: 50,
L7Rule: 100,
}
|
odontome/app | app/models/subscription.rb | <reponame>odontome/app<gh_stars>1-10
# frozen_string_literal: true
class Subscription < ApplicationRecord
belongs_to :practice
enum status: {
trialing: 'trialing',
active: 'active',
past_due: 'past_due',
canceled: 'canceled',
}
ACCESS_GRANTING_STATUSES = ['trialing', 'active', 'past_due']
scope :active_or_trialing, -> { where(status: ACCESS_GRANTING_STATUSES) }
scope :recent, -> { order("current_period_end DESC NULLS LAST") }
def active_or_trialing?
ACCESS_GRANTING_STATUSES.include?(status)
end
def is_trialing?
status == 'trialing'
end
def days_to_next_payment
days_left_in_subscription = (current_period_end.to_date - Time.now.to_date).to_i
end
def is_trial_expiring?
is_trialing? && days_to_next_payment <= 14
end
def is_trial_expired?
is_trialing? && days_to_next_payment <= 0
end
def assign_stripe_attrs(stripe_sub)
assign_attributes(
status: stripe_sub.status,
cancel_at_period_end: stripe_sub.cancel_at_period_end,
current_period_start: Time.at(stripe_sub.current_period_start),
current_period_end: Time.at(stripe_sub.current_period_end)
)
end
end
|
PedroCorreiaLuis/Tick-Tock | test/api/controllers/TaskFunctionalSuite.scala | <gh_stars>0
package api.controllers
import java.util.UUID
import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, Materializer}
import api.dtos.{FileDTO, TaskDTO}
import api.services.{PeriodType, SchedulingType}
import database.repositories.{FileRepository, FileRepositoryImpl, TaskRepository, TaskRepositoryImpl}
import org.scalatest.{AsyncWordSpec, BeforeAndAfterAll, BeforeAndAfterEach}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.{Application, Mode}
import play.api.inject.Injector
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.Json
import api.utils.DateUtils._
import api.utils.UUIDGenerator
import play.api.test.FakeRequest
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import api.validators.Error._
import play.api.libs.json.JsArray
import slick.jdbc.MySQLProfile.api._
import database.mappings.FileMappings._
import database.mappings.TaskMappings._
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.Duration
import play.api.test.Helpers._
import slick.jdbc.meta.MTable
class TaskFunctionalSuite extends PlaySpec with GuiceOneAppPerSuite with BeforeAndAfterAll with BeforeAndAfterEach{
/**
* new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
* new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
* new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
* new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
*/
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
lazy val appBuilder: GuiceApplicationBuilder = new GuiceApplicationBuilder()
val dtbase: Database = appBuilder.injector.instanceOf[Database]
implicit val fileRepo: FileRepository = appBuilder.injector.instanceOf[FileRepository]
implicit val taskRepo: TaskRepository = appBuilder.injector.instanceOf[TaskRepository]
implicit val uuidGen: UUIDGenerator = appBuilder.injector.instanceOf[UUIDGenerator]
implicit val actorSystem: ActorSystem = ActorSystem()
implicit val mat: Materializer = ActorMaterializer()
val LOCALHOST = "localhost:9000"
val taskUUID1: String = UUID.randomUUID().toString
val taskUUID2: String = UUID.randomUUID().toString
val taskUUID3: String = UUID.randomUUID().toString
val taskUUID4: String = UUID.randomUUID().toString
val fileUUID1: String = UUID.randomUUID().toString
val fileUUID2: String = UUID.randomUUID().toString
val fileUUID3: String = UUID.randomUUID().toString
val fileUUID4: String = UUID.randomUUID().toString
val id = uuidGen.generateUUID
override def beforeAll = {
val result = for {
_ <- dtbase.run(createFilesTableAction)
_ <- fileRepo.insertInFilesTable(FileDTO(fileUUID1, "test1", getCurrentDateTimestamp))
_ <- fileRepo.insertInFilesTable(FileDTO(fileUUID2, "test2", getCurrentDateTimestamp))
_ <- fileRepo.insertInFilesTable(FileDTO(fileUUID3, "test3", getCurrentDateTimestamp))
res <- fileRepo.insertInFilesTable(FileDTO(fileUUID4, "test4", getCurrentDateTimestamp))
} yield res
Await.result(result, Duration.Inf)
Await.result(dtbase.run(createTasksTableAction), Duration.Inf)
println(Await.result(dtbase.run(MTable.getTables), Duration.Inf))
println(Await.result(fileRepo.selectAllFiles, Duration.Inf))
}
override def afterAll = {
Await.result(dtbase.run(dropTasksTableAction), Duration.Inf)
Await.result(dtbase.run(dropFilesTableAction), Duration.Inf)
}
override def afterEach = {
Await.result(taskRepo.deleteAllTasks, Duration.Inf)
}
"GET /" should {
"receive a GET request" in {
val fakeRequest = FakeRequest(GET, "/")
.withHeaders(HOST -> LOCALHOST)
val result = route(app, fakeRequest)
status(result.get) mustBe OK
}
}
"POST /task" should {
"receive a POST request with a JSON body with the correct data and insert it into the database. (no date)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "RunOnce"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with the correct data and insert it into the database. (yyyy-MM-dd HH:mm:ss date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "RunOnce",
"startDateAndTime": "2019-07-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with the correct data and insert it into the database. (dd-MM-yyyy HH:mm:ss date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "RunOnce",
"startDateAndTime": "01-07-2019 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with the correct data and insert it into the database. (yyyy/MM/dd HH:mm:ss date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "RunOnce",
"startDateAndTime": "2019/07/01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with the correct data and insert it into the database. (dd/MM/yyyy HH:mm:ss date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "RunOnce",
"startDateAndTime": "01/07/2019 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with the correct data and insert it into the database. (max delay exceeded)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "RunOnce",
"startDateAndTime": "2030-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct data and insert it into the database. (with timezone)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "RunOnce",
"startDateAndTime": "2030-01-01 00:00:00",
"timezone": "EST"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
val task = Await.result(taskRepo.selectTask(id), Duration.Inf)
task.isDefined mustBe true
task.get.startDateAndTime.toString mustBe "Some(Tue Jan 01 05:00:00 GMT 2030)"
}
"receive a POST request with a JSON body with incorrect data. (wrong file name)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "Unknown",
"taskType": "RunOnce",
"startDateAndTime": "2019-07-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidFileName).toString + "]"
}
"receive a POST request with a JSON body with incorrect data. (wrong date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "RunOnce",
"startDateAndTime": "01:07:2019 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidStartDateFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect data. (wrong date values)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "RunOnce",
"startDateAndTime": "2019-14-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidStartDateFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect data. (wrong time values)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "RunOnce",
"startDateAndTime": "2019-07-01 25:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidStartDateFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect data. (given date already happened)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "RunOnce",
"startDateAndTime": "2015-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidStartDateValue).toString + "]"
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (with endDateAndTime) (Minutely) (yyyy-MM-dd HH:mm:ss date format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "2020-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (with occurrences) (Minutely)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (Hourly)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Hourly",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (Daily)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Daily",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (Weekly)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Weekly",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (Monthly)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Monthly",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (Yearly)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Yearly",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (dd-MM-yyyy HH:mm:ss endDate format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "01-01-2020 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (yyyy/MM/dd HH:mm:ss endDate format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "2020/01/01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (dd/MM/yyyy HH:mm:ss endDate format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "01/01/2020 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
}
"receive a POST request with a JSON body with correct periodic task data and insert it into the database. (with timezone)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "01-01-2020 00:00:00",
"timezone": "PST"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 1)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
val task = Await.result(taskRepo.selectTask(id), Duration.Inf)
task.isDefined mustBe true
task.get.startDateAndTime.get mustBe "Some(Mon Jul 01 08:00:00 BST 2019)"
task.get.endDateAndTime.get mustBe "Some(Wed Jan 01 08:00:00 GMT 2020)"
}
"receive a POST request with a JSON body with incorrect periodic task data. (missing Periodic fields)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (invalid task type)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Unknown",
"startDateAndTime": "2019-07-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat).toString + "," + Json.toJsObject(invalidTaskType).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (negative period)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": -1,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidPeriod).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (wrong endDate format)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "2020:01:01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidEndDateFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (given endDate already happened)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-01-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "2019-01-15 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidStartDateValue).toString + "," + Json.toJsObject(invalidEndDateValue).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (given endDate happens before startDate)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"endDateAndTime": "2019-06-15 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidEndDateValue).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (negative occurrences)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2,
"occurrences": -1
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidOccurrences).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (missing periodType field)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test2",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"period": 2,
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (missing period field)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test3",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat).toString + "]"
}
"receive a POST request with a JSON body with incorrect periodic task data. (missing endDate/occurrences)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 2
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat).toString + "]"
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with exclusionDate)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day and dayOfWeek)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day and dayType)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek and dayType)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek and dayType)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with exclusionDate and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with dayOfWeek, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with day, dayOfWeek, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with correct exclusions and insert it into the database. (with multiple exclusions)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with no arguments)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with an unknown parameter)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionId)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with taskId)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionDate and day)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionDate and dayOfWeek)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionDate and dayType)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionDate and month)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with exclusionDate and year)" in {
}
"receive a POST request with a JSON body with the correct periodic task data with incorrect exclusions. (with only criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with schedulingDate)" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
.withJsonBody(Json.parse("""
{
"fileName": "test1",
"taskType": "Personalized",
"startDateAndTime": "2019-07-01 00:00:00",
"schedulings": {
"schedulingDate": ""
}
}
"""))
val routeOption = route(app, fakeRequest)
val result = for{
routeResult <- routeOption.get
selectResult <- taskRepo.selectAllTasks
} yield (routeResult, selectResult)
val bodyText = contentAsString(routeOption.get)
result.map(tuple => tuple._2.size mustBe 0)
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day and dayOfWeek)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day and dayType)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day and month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek and dayType)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek and month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType and month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with month and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType, month, year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType and month)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, month and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType, month and year)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType, month and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with dayOfWeek, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with day, dayOfWeek, dayType, month, year and criteria)" in {
}
"receive a POST request with a JSON body with the correct personalized task data and insert it into the database. (with multiple schedulings)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with no scheduling)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with a scheduling with no parameters)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with a scheduling with an unknown parameter)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with schedulingId)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with taskId)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with exclusionDate and day)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with exclusionDate and dayOfWeek)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with exclusionDate and dayType)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with exclusionDate and month)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with exclusionDate and year)" in {
}
"receive a POST request with a JSON body with incorrect personalized task data. (with only criteria)" in {
}
}
"GET /task" should {
"receive a GET request with no tasks inserted" in {
val fakeRequest = FakeRequest(GET, "/task")
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
Await.result(routeOption.get, Duration.Inf)
val bodyText = contentAsString(routeOption.get)
status(routeOption.get) mustBe OK
bodyText mustBe "[]"
}
"receive a GET request of all tasks after inserting 3 tasks" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for{
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val fakeRequest = FakeRequest(GET, "/task")
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
Await.result(routeOption.get, Duration.Inf)
val bodyText = contentAsString(routeOption.get)
status(routeOption.get) mustBe OK
bodyText mustBe "[" + Json.toJsObject(dto1) + "," + Json.toJsObject(dto2) + "," + Json.toJsObject(dto3) + "]"
}
}
"GET /task/:id" should {
"receive a GET request with an existing id for a specific task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2" // id corresponding to dto2
val fakeRequest = FakeRequest(GET, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
Await.result(routeOption.get, Duration.Inf)
val bodyText = contentAsString(routeOption.get)
status(routeOption.get) mustBe OK
bodyText mustBe Json.toJsObject(dto2).toString
}
"receive a GET request with a non-existing id." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd4" // id that doesn't correspond to any dto
val fakeRequest = FakeRequest(GET, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
Await.result(routeOption.get, Duration.Inf)
val bodyText = contentAsString(routeOption.get)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe Json.toJsObject(invalidEndpointId).toString
}
}
"PATCH /task/:id" should {
"receive a PATCH request with a non-existing id." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd4" // id that doesn't correspond to any dto
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId":"newUUID"
}
"""))
val routeOption = route(app, fakeRequest)
Await.result(routeOption.get, Duration.Inf)
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidEndpointId) + "]"
val task = Await.result(taskRepo.selectTask("newUUID"), Duration.Inf)
task.isDefined mustBe false
}
"receive a PATCH request changing the taskId value of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId":"11231bd5-6f92-496c-9fe7-75bc180467b0"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{
elem => elem.isDefined mustBe true
val resultDto = TaskDTO("11231bd5-6f92-496c-9fe7-75bc180467b0", "test1", SchedulingType.RunOnce)
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
"receive a PATCH request changing the fileName of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
Await.result(taskRepo.selectTask(id), Duration.Inf).isDefined mustBe true
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"fileName":"test4"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO("asd1", "test4", SchedulingType.RunOnce)
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
"receive a PATCH request changing the taskType of a periodic task to RunOnce." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskType":"RunOnce"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO(id, "test2", SchedulingType.RunOnce, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the taskType of a single run task to Periodic and fail. (doesn't have the other needed parameters)." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskType":"Periodic"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidUpdateTaskFormat) + "]"
task.map{ elem =>
elem.isDefined mustBe true
elem.get mustBe Json.toJsObject(dto1).toString
}
}
"receive a PATCH request changing the taskType of a single run task to Periodic and succeed. (by adding all other needed Periodic parameters)" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskType":"Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Hourly",
"period": 1,
"endDateAndTime": "2020-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO("asd1", "test1", SchedulingType.Periodic, Some(stringToDateFormat("2019-07-01 00:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Hourly), Some(1), Some(stringToDateFormat("2020-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the startDate of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"startDateAndTime":"2019-07-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = dto2.copy(startDateAndTime = Some(stringToDateFormat("2019-07-01 00:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the periodType of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"periodType":"Hourly"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = dto2.copy(periodType = Some(PeriodType.Hourly))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the period of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"period": 5
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDto = dto2.copy(period = Some(5))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the endDate of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"endDateAndTime":"2050-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = dto2.copy(endDateAndTime = Some(stringToDateFormat("2050-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe resultDto
}
}
"receive a PATCH request changing the endDate of a task that already has an occurrences field. (replaces occurrences with the endDate)" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd3"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"endDateAndTime":"2050-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDTO = dto3.copy(endDateAndTime = Some(stringToDateFormat("2050-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")), totalOccurrences = None, currentOccurrences = None)
elem.get mustBe Json.toJsObject(resultDTO).toString
}
}
"receive a PATCH request changing the occurrences of a task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd3"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = dto3.copy(totalOccurrences = Some(5), currentOccurrences = Some(5))
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
"receive a PATCH request changing the occurrences of a task that already has an endDate field. (replaces endDate with the occurrences)" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd2"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"occurrences": 5
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDTO = dto2.copy(endDateAndTime = None, totalOccurrences = Some(5), currentOccurrences = Some(5))
elem.get mustBe Json.toJsObject(dto2).toString
}
}
"receive a PATCH request changing multiple values of a RunOnce task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId":"11231bd5-6f92-496c-9fe7-75bc180467b0",
"fileName":"test4",
"taskType":"RunOnce",
"startDateAndTime":"2050-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO("11231bd5-6f92-496c-9fe7-75bc180467b0", "test4", SchedulingType.RunOnce, Some(stringToDateFormat("2050-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
"receive a PATCH request changing multiple values of a Periodic task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd3"
val fakeRequest = FakeRequest(PATCH, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId":"11231bd5-6f92-496c-9fe7-75bc180467b0",
"fileName":"test4",
"taskType":"Periodic",
"startDateAndTime":"2050-01-01 00:00:00",
"periodType":"Yearly",
"period":2,
"occurrences":6
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask(id)
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map{ elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO("11231bd5-6f92-496c-9fe7-75bc180467b0", "test4", SchedulingType.Periodic, Some(stringToDateFormat("2050-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Yearly), Some(2), None, Some(6), Some(6))
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
}
"PUT /task/:id" should {
"receive a PUT request with a non-existing id and a given correct task" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "11231bd5-6f92-496c-9fe7-75bc180467b0"
val fakeRequest = FakeRequest(PUT, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 5,
"endDateAndTime": "2020-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map(elem => elem.isDefined mustBe true)
}
"receive a PUT request with a non-existing id and a given incorrect task. (missing endDate)" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "11231bd5-6f92-496c-9fe7-75bc180467b0"
val fakeRequest = FakeRequest(PUT, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 5
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat) + "]"
task.map(elem => elem.isDefined mustBe false)
}
"receive a PUT request with a non-existing id and a given incorrect task. (has taskId)" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd4"
val fakeRequest = FakeRequest(PUT, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId": "11231bd5-6f92-496c-9fe7-75bc180467b0",
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 5
}
"""))
val routeOption = route(app, fakeRequest)
val tasks = for{
_ <- routeOption.get
task1 <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
task2 <- taskRepo.selectTask("asd4")
} yield (task1, task2)
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat) + "]"
tasks.map { elem =>
elem._1.isDefined mustBe false
elem._2.isDefined mustBe false
}
}
"receive a PUT request replacing a task with the given id with a given correct task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PUT, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId": "11231bd5-6f92-496c-9fe7-75bc180467b0",
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 5,
"endDateAndTime": "2020-01-01 00:00:00"
}
"""))
val routeOption = route(app, fakeRequest)
val task = for {
_ <- routeOption.get
res <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe OK
bodyText mustBe "Task received => http://" + LOCALHOST + "/task/" + id
task.map { elem =>
elem.isDefined mustBe true
val resultDto = TaskDTO("11231bd5-6f92-496c-9fe7-75bc180467b0", "test4", SchedulingType.Periodic, Some(stringToDateFormat("2019-07-01 00:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Minutely), Some(5), Some(stringToDateFormat("2020-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")))
elem.get mustBe Json.toJsObject(resultDto).toString
}
}
"receive a PUT request replacing a task with the given id with a given incorrect task." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
val dto2 = TaskDTO("asd2", "test2", SchedulingType.Periodic, Some(stringToDateFormat("2020-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Daily), Some(2), Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")))
val dto3 = TaskDTO("asd3", "test3", SchedulingType.Periodic, Some(stringToDateFormat("2030-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss")), Some(PeriodType.Monthly), Some(1), None, Some(12), Some(12))
val result = for {
_ <- taskRepo.insertInTasksTable(dto1)
_ <- taskRepo.insertInTasksTable(dto2)
res <- taskRepo.insertInTasksTable(dto3)
} yield res
Await.result(result, Duration.Inf)
val id = "asd1"
val fakeRequest = FakeRequest(PUT, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
.withBody(Json.parse("""
{
"taskId": "11231bd5-6f92-496c-9fe7-75bc180467b0",
"fileName": "test4",
"taskType": "Periodic",
"startDateAndTime": "2019-07-01 00:00:00",
"periodType": "Minutely",
"period": 5
}
"""))
val routeOption = route(app, fakeRequest)
val task = for{
_ <- routeOption.get
res <- taskRepo.selectTask("11231bd5-6f92-496c-9fe7-75bc180467b0")
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe "[" + Json.toJsObject(invalidCreateTaskFormat) + "]"
task.map { elem =>
elem.isDefined mustBe true
elem.get mustBe Json.toJsObject(dto1).toString
}
}
}
"DELETE /task/:id" should {
"receive a PUT request with a non-existing id" in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
Await.result(taskRepo.insertInTasksTable(dto1), Duration.Inf)
val initialResult = Await.result(taskRepo.selectAllTasks, Duration.Inf)
initialResult.size mustBe 1
val id = "asd2"
val fakeRequest = FakeRequest(DELETE, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
val tasks = for {
_ <- routeOption.get
res <- taskRepo.selectAllTasks
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe BAD_REQUEST
bodyText mustBe Json.toJsObject(invalidEndpointId).toString
tasks.map(elem => elem.size mustBe 1)
}
"receive a DELETE request to delete a task with the given id." in {
val dto1 = TaskDTO("asd1", "test1", SchedulingType.RunOnce)
Await.result(taskRepo.insertInTasksTable(dto1), Duration.Inf)
val initialResult = Await.result(taskRepo.selectAllTasks, Duration.Inf)
initialResult.size mustBe 1
val id = "asd1"
val fakeRequest = FakeRequest(DELETE, "/task/" + id)
.withHeaders(HOST -> LOCALHOST)
val routeOption = route(app, fakeRequest)
val tasks = for{
_ <- routeOption.get
res <- taskRepo.selectAllTasks
} yield res
val bodyText = contentAsString(routeOption.get)
println(bodyText)
status(routeOption.get) mustBe NO_CONTENT
bodyText mustBe ""
tasks.map(elem => elem.size mustBe 0)
}
}
/*"TaskController#GETtask" should {
"receive a GET request" in {
val fakeRequest = FakeRequest(POST, "/task")
.withHeaders(HOST -> LOCALHOST)
val result = route(app, fakeRequest)
val bodyText: String = contentAsString(result.get)
println(bodyText)
status(result.get) mustBe OK
}
}*/
}
|
ktotheoz/pixellight | Base/PLCore/include/PLCore/Tools/ChecksumCRC32.h | <filename>Base/PLCore/include/PLCore/Tools/ChecksumCRC32.h
/*********************************************************\
* File: ChecksumCRC32.h *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
#ifndef __PLCORE_CHECKSUMCRC32_H__
#define __PLCORE_CHECKSUMCRC32_H__
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "PLCore/Container/Array.h"
#include "PLCore/Tools/Checksum.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLCore {
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* CRC32 (cyclic redundancy check) checksum
*
* @remarks
* This implementation is using the official polynomial (0x04C11DB7) used by CRC32 in
* PKZip, WinZip and Ethernet. Often times the polynomial shown reversed as 0xEDB88320.
*
* @note
* - CRC32 produces a 32-bit/4-byte hash
*/
class ChecksumCRC32 : public Checksum {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*/
PLCORE_API ChecksumCRC32();
/**
* @brief
* Destructor
*/
PLCORE_API virtual ~ChecksumCRC32();
/**
* @brief
* Returns the current CRC32 checksum
*
* @return
* Current CRC32 checksum
*/
PLCORE_API uint32 GetChecksum() const;
/**
* @brief
* Returns the checksum of a given buffer
*
* @param[in] pnBuffer
* Buffer to create the checksum from (MUST be valid!)
* @param[in] nNumOfBytes
* Number of bytes of the given buffer (MUST be valid!)
*
* @return
* The checksum of the given buffer
*/
PLCORE_API uint32 GetChecksum(const uint8 *pnBuffer, uint32 nNumOfBytes);
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
private:
/**
* @brief
* Initializes the CRC32 table
*/
void Init();
/**
* @brief
* Reflection part of the the CRC32 table initialization
*
* @param[in] nReflection
* Reflection value
* @param[in] nCharacter
* Character to reflect
*
* @return
* The reflected character
*
* @remarks
* Reflection is a requirement for the official CRC-32 standard.
*/
uint32 Reflect(uint32 nReflection, char nCharacter) const;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
static Array<uint32> m_lstCRC32Table; /**< Static CRC32 table */
uint32 m_nCRC32; /**< Current CRC32 checksum */
//[-------------------------------------------------------]
//[ Private virtual Checksum functions ]
//[-------------------------------------------------------]
private:
virtual void Update(const uint8 nInput[], uint32 nInputLen) override;
virtual String Final() override;
virtual void Reset() override;
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLCore
#endif // __PLCORE_CHECKSUMCRC32_H__
|
rajatsangrame/MovieApp | app/src/main/java/com/rajatsangrame/movie/util/Utils.java | package com.rajatsangrame.movie.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import com.rajatsangrame.movie.data.Repository;
import com.rajatsangrame.movie.data.db.movie.MovieDB;
import com.rajatsangrame.movie.data.db.tv.TVDB;
import com.rajatsangrame.movie.data.model.ApiResponse;
import com.rajatsangrame.movie.data.model.movie.Movie;
import com.rajatsangrame.movie.data.model.movie.MovieDetail;
import com.rajatsangrame.movie.data.model.search.SearchResult;
import com.rajatsangrame.movie.data.model.tv.TV;
import com.rajatsangrame.movie.data.model.tv.TvDetail;
import com.rajatsangrame.movie.data.rest.Category;
import com.rajatsangrame.movie.data.rest.RetrofitApi;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Single;
public class Utils {
private static final String TAG = "Utils";
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void hideKeyboard(Context context) {
// Check if no view has focus:
InputMethodManager inputManager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(0, 0);
}
public static List<Movie> getListResult(ApiResponse<Movie> apiResponse) {
return apiResponse.getResults();
}
public static List<SearchResult> prepareListForSearchAdapter(ApiResponse<SearchResult> apiResponse) {
List<SearchResult> outputResult = new ArrayList<>();
if (apiResponse == null || apiResponse.getResults() == null) {
return outputResult;
}
List<SearchResult> apiSearchList = clearRawEntries(apiResponse);
List<String> itemType = new ArrayList<>();
for (SearchResult movie : apiSearchList) {
String type = movie.getMediaType();
if (!itemType.contains(type)) {
itemType.add(type);
}
}
for (String type : itemType) {
SearchResult dummy = new SearchResult();
dummy.setItemType(Constants.HEADER);
dummy.setMediaType(type);
outputResult.add(dummy);
for (SearchResult itr : apiSearchList) {
itr.setItemType(Constants.ITEM);
if (itr.getMediaType().equals(type)) {
outputResult.add(itr);
}
}
}
return outputResult;
}
private static List<SearchResult> clearRawEntries(ApiResponse<SearchResult> apiResponse) {
List<SearchResult> list = new ArrayList<>();
for (SearchResult itr : apiResponse.getResults()) {
if (itr.getMediaType().equals("person") || itr.getBackdropPath() != null) {
Log.i(TAG, "clearRawEntries: " + itr.getBackdropPath());
list.add(itr);
}
}
return list;
}
public static Single<ApiResponse<Movie>> getSingleMovie(RetrofitApi retrofitApi, Category category, long key) {
switch (category) {
case NOW_PLAYING:
return retrofitApi.getNowPlaying(key);
case TOP_RATED_MOVIE:
return retrofitApi.getTopRatedMovie(key);
default:
//POPULAR
return retrofitApi.getPopularMovies(key);
}
}
public static Single<ApiResponse<TV>> getSingleTV(RetrofitApi retrofitApi, Category category, long key) {
switch (category) {
case TOP_TV:
return retrofitApi.getTopRatedTv(key);
default:
//POPULAR
return retrofitApi.getPopularTv(key);
}
}
public static List<MovieDB> getMovieList(ApiResponse<Movie> apiResponse, Category category) {
List<MovieDB> dbList = new ArrayList<>();
if (apiResponse == null || apiResponse.getResults() == null)
return dbList;
for (Movie movie : apiResponse.getResults()) {
MovieDB db = new MovieDB(
movie.getId(),
movie.getTitle(),
category.name(),
movie.getPosterPath(),
movie.getBackdropPath(),
movie.getOverview(),
movie.getPopularity(),
movie.getVoteAverage(),
System.currentTimeMillis());
dbList.add(db);
}
return dbList;
}
public static List<TVDB> getTVList(ApiResponse<TV> apiResponse, Category category) {
List<TVDB> dbList = new ArrayList<>();
if (apiResponse == null || apiResponse.getResults() == null)
return dbList;
for (TV tv : apiResponse.getResults()) {
TVDB db = new TVDB(
tv.getId(),
tv.getName(),
category.name(),
tv.getPosterPath(),
tv.getBackdropPath(),
tv.getOverview(),
tv.getPopularity(),
tv.getVoteAverage(),
System.currentTimeMillis()
);
dbList.add(db);
}
return dbList;
}
public static MovieDB getMovieDB(MovieDetail movieDetail) {
int id = movieDetail.getId();
MovieDB movieDB = new MovieDB(id);
movieDB.setPosterPath(movieDetail.getPosterPath());
movieDB.setBackdropPath(movieDetail.getBackdropPath());
movieDB.setTitle(movieDetail.getTitle());
movieDB.setOriginalTitle(movieDetail.getOriginalTitle());
movieDB.setPopularity(movieDetail.getPopularity());
movieDB.setVoteAverage(movieDetail.getVoteAverage());
movieDB.setOverview(movieDetail.getOverview());
movieDB.setGenres(movieDetail.getGenres());
movieDB.setProductionCompanies(movieDetail.getProductionCompanies());
movieDB.setSpokenLanguages(movieDetail.getSpokenLanguages());
movieDB.setVoteCount(movieDetail.getVoteCount());
movieDB.setRuntime(movieDetail.getRuntime());
movieDB.setReleaseDate(movieDetail.getReleaseDate());
movieDB.setImdbId(movieDetail.getImdbId());
movieDB.setHomepage(movieDetail.getHomepage());
return movieDB;
}
public static TVDB getTVDB(TvDetail tvDetail) {
int id = tvDetail.getId();
TVDB tvdb = new TVDB(id);
tvdb.setPosterPath(tvDetail.getPosterPath());
tvdb.setBackdropPath(tvDetail.getBackdropPath());
tvdb.setName(tvDetail.getName());
tvdb.setOriginalName(tvDetail.getOriginalName());
tvdb.setPopularity(tvDetail.getPopularity());
tvdb.setVoteAverage(tvDetail.getVoteAverage());
tvdb.setOverview(tvDetail.getOverview());
tvdb.setVoteCount(tvDetail.getVoteCount());
tvdb.setGenres(tvDetail.getGenres());
tvdb.setProductionCompanies(tvDetail.getProductionCompanies());
tvdb.setFirstAirDate(tvDetail.getFirstAirDate());
tvdb.setSeasons(tvDetail.getSeasons());
tvdb.setNumberOfEpisodes(tvDetail.getNumberOfEpisodes());
tvdb.setNumberOfSeasons(tvDetail.getNumberOfSeasons());
return tvdb;
}
public static MovieDB updateMovieDB(MovieDB oldItem, MovieDB newItem) {
newItem.setFetchCategory(oldItem.getFetchCategory());
newItem.setEntryTimeStamp(oldItem.getEntryTimeStamp());
newItem.setSaved(oldItem.isSaved());
newItem.setSavedTime(oldItem.getSavedTime());
return newItem;
}
public static TVDB updateTVDB(TVDB oldItem, TVDB newItem) {
newItem.setFetchCategory(oldItem.getFetchCategory());
newItem.setEntryTimeStamp(oldItem.getEntryTimeStamp());
newItem.setSaved(oldItem.isSaved());
newItem.setSavedTime(oldItem.getSavedTime());
return newItem;
}
public static MovieDB getMovieDetail(MovieDetail movieDetail) {
return getMovieDB(movieDetail);
}
public static TVDB getTVDetail(TvDetail tvDetail) {
return getTVDB(tvDetail);
}
}
|
Paul-Ferrell/hpctoolkit | src/lib/support/HashTableSortedIterator.cpp | // -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *
/******************************************************************************
* *
* File: C++ Hash Table Sorted Iterator Utility *
* Author: <NAME> *
* Date: March 1993 *
* *
* See the include file HashTable.h for an explanation of the *
* data and functions in the HashTable class. *
* *
* Programming Environment Project *
* *
*****************************************************************************/
//************************** System Include Files ***************************
#include <iostream>
//*************************** User Include Files ****************************
//*************************** Forward Declarations **************************
//***************************************************************************
#include "HashTable.hpp"
#include "QuickSort.hpp"
/*************** HashTableSortedIterator public member functions *************/
//
//
HashTableSortedIterator::HashTableSortedIterator(const HashTable* theHashTable,
EntryCompareFunctPtr const _EntryCompare)
{
sortedEntries = (void **) NULL;
hashTable = (HashTable*) theHashTable;
EntryCompare = _EntryCompare;
HashTableSortedIterator::Reset();
return;
}
//
//
HashTableSortedIterator::~HashTableSortedIterator ()
{
if (sortedEntries) delete [] sortedEntries;
return;
}
//
//
void HashTableSortedIterator::operator ++(int)
{
currentEntryNumber++;
return;
}
bool HashTableSortedIterator::IsValid() const
{
return (currentEntryNumber < numberOfSortedEntries);
}
//
//
void* HashTableSortedIterator::Current () const
{
if (currentEntryNumber < numberOfSortedEntries)
{
if (sortedEntries) return (void*)sortedEntries[currentEntryNumber];
else return (void*)NULL;
}
else
{
return (void*)NULL;
}
}
//
//
void HashTableSortedIterator::Reset ()
{
HashTableIterator anIterator(hashTable);
QuickSort localQuickSort;
currentEntryNumber = 0;
if (sortedEntries) delete [] sortedEntries;
numberOfSortedEntries = hashTable->NumberOfEntries();
sortedEntries = new void* [numberOfSortedEntries];
for (int i = 0; i < numberOfSortedEntries; i++, anIterator++)
{
sortedEntries[i] = anIterator.Current();
}
localQuickSort.Create(sortedEntries, EntryCompare);
localQuickSort.Sort(0, numberOfSortedEntries-1);
localQuickSort.Destroy();
return;
}
|
YoranSys/gravitee-management-rest-api | gravitee-rest-api-portal/gravitee-rest-api-portal-rest/src/test/java/io/gravitee/rest/api/portal/rest/resource/auth/OAuth2AuthenticationResourceTest.java | <reponame>YoranSys/gravitee-management-rest-api
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.portal.rest.resource.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.gravitee.common.http.HttpStatusCode;
import io.gravitee.rest.api.model.UserEntity;
import io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity;
import io.gravitee.rest.api.model.configuration.identity.IdentityProviderType;
import io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity;
import io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity;
import io.gravitee.rest.api.portal.rest.model.Token;
import io.gravitee.rest.api.portal.rest.resource.AbstractResourceTest;
import io.gravitee.rest.api.service.exceptions.EmailRequiredException;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static javax.ws.rs.client.Entity.form;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.*;
/**
* @author <NAME> (<EMAIL> at <EMAIL>)
* @author <NAME> (nicolas.geraud at graviteesource.com)
* @author GraviteeSource Team
*/
public class OAuth2AuthenticationResourceTest extends AbstractResourceTest {
private final static String USER_SOURCE_OAUTH2 = "oauth2";
@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
protected String contextPath() {
return "auth/oauth2/"+USER_SOURCE_OAUTH2;
}
private SocialIdentityProviderEntity identityProvider = null;
@Before
public void init() {
identityProvider = new SocialIdentityProviderEntity() {
@Override
public String getId() {
return USER_SOURCE_OAUTH2;
}
@Override
public IdentityProviderType getType() {
return IdentityProviderType.OIDC;
}
@Override
public String getAuthorizationEndpoint() {
return null;
}
@Override
public String getTokenEndpoint() {
return "http://localhost:" + wireMockRule.port() + "/token";
}
@Override
public String getUserInfoEndpoint() {
return "http://localhost:" + wireMockRule.port() + "/userinfo";
}
@Override
public List<String> getRequiredUrlParams() {
return null;
}
@Override
public List<String> getOptionalUrlParams() {
return null;
}
@Override
public List<String> getScopes() {
return null;
}
@Override
public String getDisplay() {
return null;
}
@Override
public String getColor() {
return null;
}
@Override
public String getClientSecret() {
return "the_client_secret";
}
private Map<String, String> userProfileMapping = new HashMap<>();
@Override
public Map<String, String> getUserProfileMapping() {
return userProfileMapping;
}
private List<GroupMappingEntity> groupMappings = new ArrayList<>();
@Override
public List<GroupMappingEntity> getGroupMappings() {
return groupMappings;
}
private List<RoleMappingEntity> roleMappings = new ArrayList<>();
@Override
public List<RoleMappingEntity> getRoleMappings() {
return roleMappings;
}
@Override
public boolean isEmailRequired() {
return true;
}
};
when(socialIdentityProviderService.findById(USER_SOURCE_OAUTH2)).thenReturn(identityProvider);
cleanEnvironment();
cleanRolesGroupMapping();
reset(userService, groupService, roleService, membershipService);
}
private void cleanEnvironment() {
identityProvider.getUserProfileMapping().clear();
}
private void cleanRolesGroupMapping() {
identityProvider.getGroupMappings().clear();
identityProvider.getRoleMappings().clear();
}
@Test
public void shouldConnectUser() throws Exception {
// -- MOCK
//mock environment
mockDefaultEnvironment();
//mock oauth2 exchange authorisation code for access token
mockExchangeAuthorizationCodeForAccessToken();
//mock oauth2 user info call
mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
//mock DB find user by name
UserEntity userEntity = mockUserEntity();
userEntity.setId("<EMAIL>");
userEntity.setSource(USER_SOURCE_OAUTH2);
userEntity.setSourceId("<EMAIL>");
userEntity.setPicture("http://example.com/janedoe/me.jpg");
when(userService.createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString())).thenReturn(userEntity);
//mock DB user connect
when(userService.connect(userEntity.getId())).thenReturn(userEntity);
// -- CALL
final MultivaluedMap<String, String> payload =
createPayload("the_client_id","http://localhost/callback","CoDe");
Response response = target().request().post(form(payload));
// -- VERIFY
verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString());
verify(userService, times(1)).connect(userEntity.getSourceId());
assertEquals(HttpStatusCode.OK_200, response.getStatus());
// verify response body
// verifyUserInResponseBody(response);
// verify jwt token
verifyJwtToken(response);
}
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
Token responseToken = response.readEntity(Token.class);
assertEquals("BEARER", responseToken.getTokenType().name());
String token = responseToken.getToken();
Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT jwt = jwtVerifier.verify(token);
assertEquals(jwt.getSubject(),"<EMAIL>");
assertEquals("Jane", jwt.getClaim("firstname").asString());
assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString());
assertEquals("<EMAIL>", jwt.getClaim("sub").asString());
assertEquals("<EMAIL>", jwt.getClaim("email").asString());
assertEquals("Doe", jwt.getClaim("lastname").asString());
}
private void verifyJwtTokenIsNotPresent(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
assertNull(response.getCookies().get(HttpHeaders.AUTHORIZATION));
}
private MultivaluedMap<String, String> createPayload(String clientId, String redirectUri, String code) {
final MultivaluedMap<String, String> payload = new MultivaluedHashMap<>();
payload.add("client_id", clientId);
payload.add("redirect_uri", redirectUri);
payload.add("code", code);
return payload;
}
private UserEntity mockUserEntity() {
UserEntity createdUser = new UserEntity();
createdUser.setId("<EMAIL>");
createdUser.setSource(USER_SOURCE_OAUTH2);
createdUser.setSourceId("<EMAIL>");
createdUser.setLastname("Doe");
createdUser.setFirstname("Jane");
createdUser.setEmail("<EMAIL>");
createdUser.setPicture("http://example.com/janedoe/me.jpg");
return createdUser;
}
@Test
public void shouldNotConnectUserOn401UserInfo() throws Exception {
// -- MOCK
//mock environment
mockDefaultEnvironment();
//mock oauth2 exchange authorisation code for access token
mockExchangeAuthorizationCodeForAccessToken();
//mock oauth2 user info call
mockUserInfo(WireMock.unauthorized().withBody(IOUtils.toString(read("/oauth2/json/user_info_401_response_body.json"), Charset.defaultCharset())));
// -- CALL
final MultivaluedMap<String, String> payload =
createPayload("the_client_id","http://localhost/callback","CoDe");
Response response = target().request().post(form(payload));
// -- VERIFY
verify(userService, times(0)).createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString());
verify(userService, times(0)).connect(anyString());
assertEquals(HttpStatusCode.UNAUTHORIZED_401, response.getStatus());
// verify jwt token not present
assertFalse(response.getCookies().containsKey(HttpHeaders.AUTHORIZATION));
}
@Test
public void shouldNotConnectUserWhenMissingMailInUserInfo() throws Exception {
// -- MOCK
//mock environment
mockWrongEnvironment();
//mock oauth2 exchange authorisation code for access token
mockExchangeAuthorizationCodeForAccessToken();
//mock oauth2 user info call
mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
when(userService.createOrUpdateUserFromSocialIdentityProvider(refEq(identityProvider),anyString())).thenThrow(new EmailRequiredException(USER_NAME));
// -- CALL
final MultivaluedMap<String, String> payload =
createPayload("the_client_id","http://localhost/callback","CoDe");
Response response = target().request().post(form(payload));
// -- VERIFY
verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString());
verify(userService, times(0)).connect(anyString());
assertEquals(HttpStatusCode.BAD_REQUEST_400, response.getStatus());
// verify jwt token not present
assertFalse(response.getCookies().containsKey(HttpHeaders.AUTHORIZATION));
}
private void mockUserInfo(ResponseDefinitionBuilder responseDefinitionBuilder) throws IOException {
stubFor(
get("/userinfo")
.withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON_TYPE.toString()))
.withHeader(HttpHeaders.AUTHORIZATION, equalTo("Bearer 2YotnFZFEjr1zCsicMWpAA"))
.willReturn(responseDefinitionBuilder));
}
private void mockExchangeAuthorizationCodeForAccessToken() throws IOException {
String tokenRequestBody = ""
+ "code=CoDe&"
+ "grant_type=&"
+ "redirect_uri=http%3A%2F%2Flocalhost%2Fcallback&"
+ "client_secret=the_client_secret&"
+ "client_id=the_client_id&"
+ "code_verifier=";
stubFor(
post("/token")
.withHeader(HttpHeaders.ACCEPT, equalTo(MediaType.APPLICATION_JSON_TYPE.toString()))
.withRequestBody(equalTo(tokenRequestBody))
.willReturn(okJson(IOUtils.toString(read("/oauth2/json/token_response_body.json"), Charset.defaultCharset()))));
}
private void mockDefaultEnvironment() {
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.ID, "email");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.SUB, "sub");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.FIRSTNAME, "given_name");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.LASTNAME, "family_name");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.EMAIL, "email");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.PICTURE, "picture");
}
private void mockWrongEnvironment() {
mockDefaultEnvironment();
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.EMAIL, "theEmail");
identityProvider.getUserProfileMapping().put(SocialIdentityProviderEntity.UserProfile.ID, "theEmail");
}
private InputStream read(String resource) throws IOException {
return this.getClass().getResourceAsStream(resource);
}
@Test
public void shouldNotConnectNewUserWhenWrongELGroupsMapping() throws Exception {
// -- MOCK
//mock environment
mockDefaultEnvironment();
//mock oauth2 exchange authorisation code for access token
mockExchangeAuthorizationCodeForAccessToken();
//mock oauth2 user info call
mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
//mock DB find user by name
when(userService.createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString())).thenThrow(new SpelEvaluationException(SpelMessage.TYPE_CONVERSION_ERROR, "cannot convert from java.lang.String to boolean"));
// -- CALL
final MultivaluedMap<String, String> payload =
createPayload("the_client_id","http://localhost/callback","CoDe");
Response response = target().request().post(form(payload));
// -- VERIFY
verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString());
verify(userService, times(0)).connect(anyString());
assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR_500, response.getStatus());
// verify jwt token
verifyJwtTokenIsNotPresent(response);
}
}
|
al2698/sp | 02-c/02-good/_more/sharp1.c | <gh_stars>0
/* Compile with:
make sizesof CFLAGS="-g -Wall -std=gnu11 -O3"
*/
#include <stdio.h>
#include <math.h>
#define peval(cmd) printf(#cmd ": %g\n", cmd)
// #define pchar(ch) printf("%c\n", #@ch)
#define Setup_list(name, ...) \
double *name ## _list = (double []){__VA_ARGS__, NAN}; \
int name ## _len = 0; \
for (name ## _len =0; \
!isnan(name ## _list[name ## _len]); \
) name ## _len ++;
int main(){
double *plist = (double[]){1, 2, 3};
double list[] = {1, 2, 3};
// #exp : stringizing operator => "exp 運算式的字串"
peval(sizeof(plist)/(sizeof(double)+0.0));
peval(sizeof(list)/(sizeof(double)+0.0));
// #@var : charizing operator => 'var 對應的字元'
// char a, b;
// pchar(a);
// pchar(b);
// ## : token parsing operator => 多個參數合成一個參數
Setup_list(items, 1, 2, 4, 8);
double sum=0;
for (double *ptr= items_list; !isnan(*ptr); ptr++)
sum += *ptr;
printf("total for items list: %g\n", sum);
#define Length(in) in ## _len
sum=0;
Setup_list(next_set, -1, 2.2, 4.8, 0.1);
for (int i=0; i < Length(next_set); i++)
sum += next_set_list[i];
printf("total for next set list: %g\n", sum);
}
|
ShaneLee/gowaves | pkg/miner/utxpool/transaction_bulk_validator_test.go | package utxpool
import (
"errors"
"sync"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/wavesplatform/gowaves/pkg/proto"
"github.com/wavesplatform/gowaves/pkg/settings"
"github.com/wavesplatform/gowaves/pkg/util/byte_helpers"
"github.com/wavesplatform/gowaves/pkg/util/lock"
)
func TestBulkValidator_Validate(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
emptyBlock := &proto.Block{}
mu := lock.NewRwMutex(&sync.RWMutex{})
now := time.Now()
m := NewMockstateWrapper(ctrl)
m.EXPECT().Mutex().Return(mu)
m.EXPECT().TopBlock().Return(emptyBlock)
m.EXPECT().Height().Return(uint64(0), nil)
m.EXPECT().BlockVRF(gomock.Any(), gomock.Any()).Return(nil, nil)
m.EXPECT(). // first transaction returns err
ValidateNextTx(byte_helpers.TransferWithSig.Transaction, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Return(errors.New("some err"))
m.EXPECT(). // second returns ok
ValidateNextTx(byte_helpers.BurnWithSig.Transaction, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Return(nil)
m.EXPECT().ResetValidationList()
utx := New(10000, NoOpValidator{}, settings.MainNetSettings)
require.NoError(t, utx.AddWithBytes(byte_helpers.TransferWithSig.Transaction, byte_helpers.TransferWithSig.TransactionBytes))
require.NoError(t, utx.AddWithBytes(byte_helpers.BurnWithSig.Transaction, byte_helpers.BurnWithSig.TransactionBytes))
require.Equal(t, 2, utx.Len())
validator := newBulkValidator(m, utx, tm(now))
validator.Validate()
require.Equal(t, 1, utx.Len())
}
|
ugrupp/kienzler | src/icons/InstagramBold.js | import { Icon } from "@chakra-ui/icons"
import React from "react"
const InstagramBoldIcon = props => {
return (
<Icon viewBox="0 0 15.73 15.73" {...props}>
<g>
<path
fill="none"
stroke="currentColor"
strokeMiterlimit="10"
d="M.5.5h14.73v14.73H.5z"
/>
<circle cx="9.84" cy="5.87" r=".46" fill="currentColor" />
<circle
cx="7.87"
cy="7.86"
r="1.64"
fill="none"
stroke="currentColor"
strokeMiterlimit="10"
/>
<rect
x="4.58"
y="4.49"
width="6.57"
height="6.76"
rx="1.6"
fill="none"
stroke="currentColor"
strokeMiterlimit="10"
/>
</g>
</Icon>
)
}
export default InstagramBoldIcon
|
gorootde/owncloud | environment/owncloud_releases/OC50/apps/files_antivirus/js/settings.js | function av_mode_show_options(str){
if ( str == 'daemon'){
$('p.av_host').show('slow');
$('p.av_port').show('slow');
$('p.av_chunk_size').show('slow');
$('p.av_path').hide('slow');
} else if (str == 'executable'){
$('p.av_host').hide('slow');
$('p.av_port').hide('slow');
$('p.av_chunk_size').hide('slow');
$('p.av_path').show('slow');
}
}
$(document).ready(function() {
$("#av_mode").change(function () {
var str = $("#av_mode").val();
av_mode_show_options(str);
});
$("#av_mode").change();
});
|
levigo/sfntly | src/main/java/org/jadice/font/sfntly/table/opentype/component/SubstLookupRecord.java | <filename>src/main/java/org/jadice/font/sfntly/table/opentype/component/SubstLookupRecord.java
package org.jadice.font.sfntly.table.opentype.component;
import org.jadice.font.sfntly.data.ReadableFontData;
import org.jadice.font.sfntly.data.WritableFontData;
final class SubstLookupRecord implements Record {
static final int RECORD_SIZE = 4;
private static final int SEQUENCE_INDEX_OFFSET = 0;
private static final int LOOKUP_LIST_INDEX_OFFSET = 2;
final int sequenceIndex;
final int lookupListIndex;
SubstLookupRecord(ReadableFontData data, int base) {
this.sequenceIndex = data.readUShort(base + SEQUENCE_INDEX_OFFSET);
this.lookupListIndex = data.readUShort(base + LOOKUP_LIST_INDEX_OFFSET);
}
@Override
public int writeTo(WritableFontData newData, int base) {
newData.writeUShort(base + SEQUENCE_INDEX_OFFSET, sequenceIndex);
newData.writeUShort(base + LOOKUP_LIST_INDEX_OFFSET, lookupListIndex);
return RECORD_SIZE;
}
}
|
renato-yuzup/axis-fem | Axis.Physalis/application/factories/collectors/GeneralNodeCollectorParser.hpp | <filename>Axis.Physalis/application/factories/collectors/GeneralNodeCollectorParser.hpp
#pragma once
#include "services/language/parsing/ParseResult.hpp"
#include "services/language/primitives/GeneralExpressionParser.hpp"
#include "services/language/primitives/OrExpressionParser.hpp"
#include "services/language/primitives/EnumerationParser.hpp"
#include "application/output/collectors/summarizers/SummaryType.hpp"
#include "CollectorParseResult.hpp"
namespace axis { namespace application { namespace factories { namespace collectors {
class GeneralNodeCollectorParser
{
public:
GeneralNodeCollectorParser(void);
~GeneralNodeCollectorParser(void);
CollectorParseResult Parse(const axis::services::language::iterators::InputIterator& begin,
const axis::services::language::iterators::InputIterator& end);
private:
void InitGrammar(void);
CollectorParseResult InterpretParseTree(
const axis::services::language::parsing::ParseResult& result) const;
// our grammar rules
axis::services::language::primitives::GeneralExpressionParser collectorStatement_;
axis::services::language::primitives::OrExpressionParser groupingType_;
axis::services::language::primitives::OrExpressionParser collectorType3D_;
axis::services::language::primitives::OrExpressionParser collectorType6D_;
axis::services::language::primitives::GeneralExpressionParser collectorType6DExpression_;
axis::services::language::primitives::GeneralExpressionParser collectorType3DExpression_;
axis::services::language::primitives::OrExpressionParser optionalDirection3DExpression_;
axis::services::language::primitives::OrExpressionParser optionalDirection6DExpression_;
axis::services::language::primitives::OrExpressionParser collectorTypeExpression_;
axis::services::language::primitives::EnumerationParser *direction3DEnum_;
axis::services::language::primitives::EnumerationParser *direction6DEnum_;
axis::services::language::primitives::OrExpressionParser direction3D_;
axis::services::language::primitives::OrExpressionParser direction6D_;
axis::services::language::primitives::OrExpressionParser optionalSetExpression_;
axis::services::language::primitives::GeneralExpressionParser setExpression_;
axis::services::language::primitives::OrExpressionParser optionalScaleExpression_;
axis::services::language::primitives::GeneralExpressionParser scaleExpression_;
axis::services::language::primitives::OrExpressionParser anyIdentifierExpression_;
};
} } } } // namespace axis::application::factories::collectors
|
SamGG/mev | source/org/tigr/microarray/mev/gaggle/GooseImpl.java | <reponame>SamGG/mev<filename>source/org/tigr/microarray/mev/gaggle/GooseImpl.java
package org.tigr.microarray.mev.gaggle;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.systemsbiology.gaggle.core.*;
import org.systemsbiology.gaggle.core.datatypes.*;
import org.systemsbiology.gaggle.geese.common.*;
import org.tigr.microarray.mev.AffySlideDataElement;
import org.tigr.microarray.mev.FloatSlideData;
import org.tigr.microarray.mev.ISlideData;
import org.tigr.microarray.mev.ISlideDataElement;
import org.tigr.microarray.mev.SlideData;
import org.tigr.microarray.mev.SlideDataElement;
import org.tigr.microarray.mev.TMEV;
import org.tigr.microarray.mev.annotation.IChipAnnotation;
import org.tigr.microarray.mev.annotation.MevChipAnnotation;
import org.tigr.microarray.mev.cluster.clusterUtil.Cluster;
import org.tigr.microarray.mev.cluster.gui.IData;
import org.tigr.microarray.mev.cluster.gui.helpers.GenomeBrowserWebstart;
public class GooseImpl implements Goose, GaggleConnectionListener {
String myGaggleName = GaggleConstants.ORIGINAL_GAGGLE_NAME;
String genomeBrowserGoose;
String[] gooseNames;
private boolean isConnected = false;
String targetGoose = "Boss";
RmiGaggleConnector gaggleConnector;
Boss gaggleBoss;
GaggleListener listener;
public GooseImpl() {
}
public void setListener(GaggleListener listener) {
this.listener = listener;
}
public String getTargetGoose() {
return targetGoose;
}
public void setTargetGoose(String targetGoose) {
this.targetGoose = targetGoose;
}
public String getMyGaggleName() {
return myGaggleName;
}
public void setMyGaggleName(String myGaggleName) {
this.myGaggleName = myGaggleName;
}
public String[] getGooseNames() {
return gooseNames;
}
public void setGooseNames(String[] gooseNames) {
this.gooseNames = gooseNames;
updateGenomeBrowserGoose();
}
private void updateGenomeBrowserGoose() {
if(genomeBrowserGoose != null) {
for(String gooseName : gooseNames)
if(genomeBrowserGoose.equals(gooseName))
return;
genomeBrowserGoose = null;
}
for(int i=0; i<gooseNames.length; i++) {
if(gooseNames[i].startsWith("Genome Browser"))
genomeBrowserGoose = gooseNames[i];
}
}
public String getGenomeBrowserGoose(String species) {
while(genomeBrowserGoose == null) {
GenomeBrowserWebstart.onWebstartGenomeBrowser(species);
if(JOptionPane.showConfirmDialog(new JFrame(),
"Could not find a connected Genome Browser.\n" +
"MeV will launch an instance of the Genome Browser.\n" +
"Please load the genome of the organism of interest.\n" +
"Click Ok when the genome is loaded to begin the broadcast.\n" +
"See http://mev.tm4.org/documentation/gaggle for help",
"Waiting for Genome Browser",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
!= JOptionPane.OK_OPTION) {
return null;
}
updateGenomeBrowserGoose();
}
return genomeBrowserGoose;
}
public boolean isConnected() {
return isConnected;
}
/**
* @author eleanora
* @param matrix
*/
public void doBroadcastMatrix(DataMatrix matrix, String target) {
if(!isConnected()) {
gaggleConnectWarning();
return;
}
if(target == null)
target = this.targetGoose;
try { //here is where an exception is thrown if gaggle is not connected.
gaggleBoss.broadcastMatrix(myGaggleName, target, matrix);
} catch (RemoteException rex) {
JOptionPane.showMessageDialog(new JFrame(), "Gaggle unavailable. Please use Utilities -> Connect to Gaggle.");
disconnectFromGaggle();
}
}
/**
* @author eleanora
*/
public void disconnectFromGaggle() {
if(isConnected())
gaggleConnector.disconnectFromGaggle(true);
}
public void gaggleInit(){
if(gaggleConnector == null) {
gaggleConnector = new RmiGaggleConnector(this);
gaggleConnector.setAutoStartBoss(true);
new GooseShutdownHook(gaggleConnector);
gaggleConnector.addListener(this);
}
}
/**
* @author eleanora
* @return
*/
public boolean connectToGaggle() {
TMEV.GAGGLE_CONNECT_ON_STARTUP = true;
if(gaggleConnector == null) {
gaggleInit();
}
try {
gaggleConnector.connectToGaggle();
} catch (Exception ex0) {
//System.err.println("MAV.connectToGaggle(): Failed to connect to gaggle: " + ex0.getMessage());
}
gaggleBoss = gaggleConnector.getBoss();
if(gaggleBoss != null) {
return true;
} else {
//System.out.println("MAV.connectToGaggle(): Couldn't connect to Gaggle");
//JOptionPane.showMessageDialog(mainframe, "Gaggle unavailable.");
return false;
}
}
/**
* @author eleanora
* @param nt
*/
public void doBroadcastNetwork(Network nt) {
if(!isConnected()) {
gaggleConnectWarning();
return;
}
try {
gaggleBoss.broadcastNetwork(myGaggleName, targetGoose, nt);
} catch (RemoteException rex) {
System.err.println("doBroadcastNetwork: rmi error calling boss.broadcast");
disconnectFromGaggle();
}
}
/**
* @author eleanora
* @param nl
*/
public void doBroadcastNamelist(Namelist nl){
if(!isConnected()) {
gaggleConnectWarning();
return;
}
try {
gaggleBoss.broadcastNamelist(myGaggleName, targetGoose, nl);
} catch (RemoteException rex) {
System.err.println("doBroadcastNamelist: rmi error calling boss.broadcast");
disconnectFromGaggle();
}
}
public void show(String key) throws RemoteException {
gaggleBoss.show(key);
}
protected void gaggleConnectWarning() {
String title = "Not connected to Gaggle";
String msg = "Please connect to Gaggle using the Utilities -> Gaggle menu.";
JOptionPane.showMessageDialog(new JFrame(), msg, title, JOptionPane.OK_OPTION);
disconnectFromGaggle();
}
/**
* Taken from <NAME>'s MeV 3.1 Goose implementation
* His notes are below:
* this, the GaggledMev implementation of Goose.handleMatrix () is inspired by the
* org/tigr/microarray/mev/file/StanfordFileLoader class.
* it reads a file of (typically) log10 ratio values, and returns a vector version
* of an array it constructs out of SlideData objects, one for each column found
* in the incoming data.
*
* ---- ISlideData [] slideDataArray = new ISlideData [experimentCount]
* slideDataArray [0] = new SlideData (rRows == spotCount == # of genes, rColumn=1);
* for (int i=1; i < slideDataArray.length; i++) {
* slideDataArray[i] = new FloatSlideData (slideDataArray[0].getSlideMetaData(), spotCount);
*
* the above suggests that the 0th slideDataArray element is metadata
* and that 1-n+1 elements are the actual data
*
* int experimentCount = ss.countTokens () + 1 - preExperimentColumns; // numerical columns + 1
* slideDataArray = new ISlideData [experimentCount];
*
* upon reading first row of file -- the title line -- these things occur,
* creating & initializing a structure to hold a column's worth (a condition) of data
*
* slideDataArray = new ISlideData [experimentCount];
* slideDataArray [0] = new SlideData (rRows == spotCount == # of genes, rColumn=1);
* slideDataArray [0].setSlideFileName (f.getPath());
* for (int i=1; i < slideDataArray.length; i++) {
* slideDataArray[i] = new FloatSlideData (slideDataArray[0].getSlideMetaData(), spotCount);
* slideDataArray[i].setSlideFileName (f.getPath());
* }
*
* then, looping through all rows in the input matrix (or file) these things occur:
* a SlideDataElement 'sde' is created, and added to SlideDataArray [0]
* i am not sure what this accomplishes
*
* then looping through the columns,
* slideDataArray [columnNumber].setIntensities (rowNumber, cy3=0, cy5=ration)
*
* SlideDataElement sde: constructed with these arguments:
* String UID
* int [] rows
* int [] columns
* float [] intensities
* String [] values)
*
* Vector slideDataList: a vector form of the slideDataArray
*/
public void handleMatrix(String sourceGoose, DataMatrix matrix)
throws RemoteException {
IChipAnnotation chipAnno = new MevChipAnnotation();
chipAnno.setSpeciesName(matrix.getSpecies());
Tuple metaData = matrix.getMetadata();
@SuppressWarnings("unused")
String identifier;
@SuppressWarnings("unused")
String logStatus;
int dataType = IData.DATA_TYPE_AFFY_ABS;
if (metaData != null) {
List<Single> singles = metaData.getSingleList();
for (Single thisSingle : singles) {
if (thisSingle.getName().equals(GaggleConstants.MEV_METADATA)) {
try {
Tuple mevMetaData = (Tuple) thisSingle.getValue();
List<Single> items = mevMetaData.getSingleList();
for (Single item : items) {
String itemname = item.getName();
if (itemname.equals(GaggleConstants.DATA_TYPE)) {
String untranslatedDataType = item.getValue().toString();
dataType = GaggleTranslater.translateDataType(untranslatedDataType);
chipAnno.setDataType(new Integer(dataType)
.toString());
}
if (itemname.equals(GaggleConstants.ARRAY_NAME)) {
chipAnno
.setChipName(item.getValue().toString());
chipAnno
.setChipType(item.getValue().toString());
}
if (itemname.equals(GaggleConstants.LOG_STATUS))
logStatus = item.getValue().toString();
}
} catch (ClassCastException cce) {
// Someone put the wrong thing into this location
}
}
if (thisSingle.getName()
.equals(GaggleConstants.IDENTIFIER_TYPE)) {
identifier = thisSingle.getValue().toString();
}
}
}
float cy3, cy5;
String[] moreFields = new String[1];
final int rColumns = 1;
int row, column;
row = column = 1;
// ----------------------------------
// make header assignments
// ----------------------------------
int experimentCount = matrix.getColumnCount(); // no kidding!
// each element slideDataArray seems to be storage for one column of
// data
ISlideData[] slideDataArray = new ISlideData[experimentCount];
slideDataArray[0] = new SlideData(matrix.getRowCount(), 1);
slideDataArray[0].setSlideFileName("Broadcast via Gaggle from "
+ sourceGoose + " " + matrix.getShortName());
for (int i = 1; i < experimentCount; i++) {
slideDataArray[i] = new FloatSlideData(slideDataArray[0]
.getSlideMetaData(), matrix.getRowCount());
slideDataArray[i].setSlideFileName("Broadcast via Gaggle from "
+ sourceGoose + " " + matrix.getShortName());
} // for i
// get Field Names
String[] fieldNames = new String[1];
fieldNames[0] = matrix.getRowTitlesTitle();
if (fieldNames == null || fieldNames[0] == null)
fieldNames = new String[] { "untitled annotation" };
slideDataArray[0].getSlideMetaData().setFieldNames(fieldNames);
for (int i = 0; i < experimentCount; i++) {
slideDataArray[i].setSlideDataName(matrix.getColumnTitles()[i]);
}
// ----------------------------------
// assign the data
// ----------------------------------
double matrixData[][] = matrix.get();
String[] rowTitles = matrix.getRowTitles();
double maxval = Double.NEGATIVE_INFINITY, minval = Double.POSITIVE_INFINITY;
for (int r = 0; r < matrix.getRowCount(); r++) {
int[] rows = new int[] { 0, 1, 0 };
int[] columns = new int[] { 0, 1, 0 };
rows[0] = rows[2] = row;
columns[0] = columns[2] = column;
if (column == rColumns) {
column = 1;
row++;
} else {
column++;
}
moreFields[0] = rowTitles[r];
ISlideDataElement sde;
sde = new SlideDataElement(
String.valueOf(row + 1), rows, columns, new float[2],
moreFields);
if(dataType == IData.DATA_TYPE_AFFY_ABS)
sde = new AffySlideDataElement(sde);
slideDataArray[0].addSlideDataElement(sde);
for (int i = 0; i < slideDataArray.length; i++) {
cy3 = 1f; // set cy3 to a default value of 1.
cy5 = (new Double(matrixData[r][i])).floatValue();
slideDataArray[i].setIntensities(r, cy3, cy5);
if (cy5 < minval)
minval = cy5;
if (cy5 > maxval)
maxval = cy5;
} // for i
} // for r
listener.expressionDataReceived(slideDataArray, chipAnno, dataType);
}
public void doExit() throws RemoteException {
disconnectFromGaggle();
listener.onExit();
}
public void doHide() throws RemoteException {
listener.onHide();
}
public void doShow() throws RemoteException {
listener.onShow();
}
public String getName() throws RemoteException {
return myGaggleName;
}
public void handleNameList(String arg0, Namelist nl) throws RemoteException {
String broadcastName = nl.getName();
nl.getMetadata();
Tuple metaData = nl.getMetadata();
String identifier = null;
boolean interactive = true;
if(metaData != null) {
List<Single> singles = metaData.getSingleList();
for(Single thisSingle: singles) {
if(thisSingle.getName().equals(GaggleConstants.MEV_METADATA)) {
//Parse MEV metadata that's useful
}
if(thisSingle.getName().equals(GaggleConstants.IDENTIFIER_TYPE)) {
identifier = thisSingle.getValue().toString();
}
try {
if(thisSingle.getName().equals(GaggleConstants.INTERACTIVE)) {
interactive = new Boolean(thisSingle.getValue().toString()).booleanValue();
}
} catch (Exception e) {
//Any kind of parsing error should result in going interactive.
interactive = true;
}
}
}
listener.nameListReceived(nl.getNames(), identifier, interactive, broadcastName);
}
public void setName(String newGaggleName) throws RemoteException {
this.myGaggleName = newGaggleName;
listener.onNameChange(newGaggleName);
}
public void update(String[] gooseNames) throws RemoteException {
setGooseNames(gooseNames);
Vector<String> menuNames = new Vector<String>();
menuNames.add("Boss");
for(int i=0; i<gooseNames.length; i++) {
if(!gooseNames[i].equals(myGaggleName))
menuNames.add(gooseNames[i]);
}
String[] temp = new String[menuNames.size()];
for(int i=0; i<temp.length; i++) {
temp[i] = (String)menuNames.get(i);
}
listener.onUpdate(temp);
}
/**
* This method is for the GaggleConnectionListener implementation.
* @author eleanora
* @param connected
* @param boss
*/
public void setConnected(boolean connected, Boss boss) {
this.isConnected = connected;
gaggleBoss = boss;
if(isConnected) {
try {
} catch (NullPointerException npe) {
//Suppress exception if menubar doesn't exist.
}
} else {
myGaggleName = GaggleConstants.ORIGINAL_GAGGLE_NAME;
}
listener.onUpdateConnected(connected);
}
/**
* Implemented to satisfy the Goose interface
*/
public void handleCluster(String arg0,
org.systemsbiology.gaggle.core.datatypes.Cluster arg1)
throws RemoteException {
//MeV ignores incoming Cluster broadcasts
}
/**
* Implemented to satisfy the Goose interface
*/
public void handleNetwork(String arg0, Network arg1) throws RemoteException {
//MeV does not handle Networks. Incoming network broadcasts are ignored.
}
/**
* Implemented to satisfy the Goose interface
*/
public void handleTuple(String arg0, GaggleTuple arg1)
throws RemoteException {
//MeV ignores incoming Tuple broadcasts
}
/**
* Implemented to satisfy the Goose interface
*/
public void handleCluster(String arg0, Cluster arg1) throws RemoteException {
//MeV ignores incoming Cluster broadcasts.
}
/**
* Implemented to satisfy the Goose interface
*/
public void doBroadcastList() throws RemoteException {}
}
|
coderZsq/coderZsq.maven.java | study-notes/j2ee-collection/java-web/03-JDBC/src/com/coderZsq/_13_smis/dao/impl/StudentDAOImpl.java | <gh_stars>1-10
package com.coderZsq._13_smis.dao.impl;
import com.coderZsq._13_smis.dao.IStudentDAO;
import com.coderZsq._13_smis.domain.Student;
import com.coderZsq._13_smis.handler.BeanHandler;
import com.coderZsq._13_smis.handler.BeanListHandler;
import com.coderZsq._13_smis.util.JdbcTemplate;
import java.util.List;
public class StudentDAOImpl implements IStudentDAO {
@Override
public void save(Student stu) {
JdbcTemplate.update("INSERT INTO t_student (name,age) VALUES(?,?)",
stu.getName(), stu.getAge());
}
@Override
public void delete(Long id) {
JdbcTemplate.update("DELETE FROM t_student WHERE id = ?", id);
}
@Override
public void update(Long id, Student stu) {
JdbcTemplate.update("UPDATE t_student SET name = ?, age = ? WHERE id = ?",
stu.getName(), stu.getAge(), id);
}
@Override
public Student get(Long id) {
String sql = "SELECT * FROM t_student WHERE id = ?";
return JdbcTemplate.query(sql, new BeanHandler<>(Student.class), id);
}
@Override
public List<Student> listAll() {
// 创建一个结果集处理: 每一行数据封装成Student对象
// return JdbcTemplate.query("SELECT * FROM t_student", new StudentResultSetHandler());
return JdbcTemplate.query("SELECT * FROM t_student", new BeanListHandler<>(Student.class));
}
}
// 把结果集中每一行数据封装成Student对象
// class StudentResultSetHandler implements IResultSetHandler<List<Student>> {
// @Override
// public List<Student> handle(ResultSet rs) throws Exception {
// List<Student> list = new ArrayList<>();
// while (rs.next()) {
// Student stu = new Student();
// stu.setId(rs.getLong("id"));
// stu.setName(rs.getString("name"));
// stu.setAge(rs.getInt("age"));
// list.add(stu);
// }
// return list;
// }
// }
|
sPHENIX-Test/sPHENIX-Test | doxygen/d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.js | <filename>doxygen/d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.js
var classTpcPrototypeUnpacker_1_1ChannelHeader =
[
[ "ChannelHeader", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a221a6207029b18226664b2cbd570d459", null ],
[ "bx_counter", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#ae4829d3538338f17b165e0f0f225b5cc", null ],
[ "fee_channel", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a075800e717477f090479d90f8eeee70d", null ],
[ "fee_id", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#ac872776618030fecbddcc58188563513", null ],
[ "max", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a58ed2a100071d14fd7f2be8ab3a70799", null ],
[ "packet_type", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#ac2e1a3340cab6d05ed479b2246272a93", null ],
[ "pad_x", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a629bc59e3f9840652b246620aec8573e", null ],
[ "pad_y", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a4425dda68b030b9f9d1ca4eff95836b2", null ],
[ "pedestal", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a95856522f33e307ecb631702a0d01b1d", null ],
[ "sampa_address", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#aeea5bd866cbcab6990069b154f5e0149", null ],
[ "sampa_channel", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#a88fbb75d8a10c2aa724355dd689c0feb", null ],
[ "size", "d8/d72/classTpcPrototypeUnpacker_1_1ChannelHeader.html#aab3e6b07313cf953a3e1ae6b8c00ba61", null ]
]; |
sytanta/gatsbystitch | src/components/product/recommendation.js | import React from "react"
import styled from "styled-components"
import { breakpoints } from "../../theme"
const Container = styled.section`
clear: both;
margin: 4em auto;
padding-left: 45px;
padding-right: 45px;
width: 100%;
.container {
padding-left: 0;
padding-right: 0;
}
h3 {
font-size: 1.2rem;
letter-spacing: 0.14em;
text-align: left;
text-transform: uppercase;
}
ul {
padding: 1em 0 0;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
text-align: left;
li {
flex-basis: 24%;
margin-bottom: 3rem;
}
figure {
background: transparent;
margin: 0;
overflow: hidden;
padding-top: 2em;
position: relative;
width: 100%;
a {
display: block;
position: relative;
text-decoration: none;
::after {
content: "";
display: block;
height: 0;
padding-bottom: 100%;
width: 100%;
}
img:not(:first-of-type) {
opacity: 0;
}
:hover {
img:not(:first-of-type) {
opacity: 1;
}
}
}
img {
height: 100%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
margin: 0 auto;
color: #fff;
transition: opacity 0.3s ease-in-out;
backface-visibility: hidden;
width: 100%;
}
}
figcaption {
margin: 1em auto 0;
position: relative;
b {
display: block;
font-size: 12px;
font-weight: 500;
line-height: 18px;
padding: 1em 0;
}
.title,
.subtitle {
display: block;
width: 100%;
}
.title {
font-family: "ANW", "AN", Avenir, "HelveticaNeue-Light",
"Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial,
"Lucida Grande", sans-serif;
font-size: inherit;
font-style: normal;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.subtitle {
font-style: normal;
font-weight: 300;
letter-spacing: 0;
}
}
}
@media (max-width: ${breakpoints.phablet}px) {
ul {
figcaption b {
font-size: calc(1.07143vw + 5.57143px);
line-height: calc(1.78571vw + 7.28571px);
}
}
}
@media (max-width: ${breakpoints.headerMobile}px) {
margin: 2em 0;
padding: 0;
.container {
padding: 0 12px;
}
ul {
justify-content: space-evenly;
li {
flex-basis: 46%;
}
}
}
`
const Recommendation = () => (
<Container id="featured" className="images">
<div className="recommendations-group group-basket container">
<h3 className="anw normal-700">Recommendations for you</h3>
<ul className="product matrix">
<li>
<figure>
<a href="/products/the-cash-shirt-in-indigo-sashiko">
<img
className="lazyload feature"
alt="The Cash Shirt in Indigo Sashiko - featured image"
src="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_large.jpg?v=1574707310"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_large.jpg?v=1574707310 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_compact.jpg?v=1574707310 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_medium.jpg?v=1574707310 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_grande.jpg?v=1574707310 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_1024x1024.jpg?v=1574707310} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_large.jpg?v=1574707310 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_compact.jpg?v=1574707310 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_medium.jpg?v=1574707310 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_grande.jpg?v=1574707310 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q419_product_cash_shirt_indigo_sashiko_001_1024x1024.jpg?v=1574707310} 1024w"
data-sizes="auto"
/>
<img
className="lazyunload lazypreload swap ls-is-cached lazyautosizes lazyloaded"
alt="The Cash Shirt in Indigo Sashiko - alternate view"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_large.jpg?v=1581530114 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_compact.jpg?v=1581530114 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_medium.jpg?v=1581530114 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_grande.jpg?v=1581530114 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_1024x1024.jpg?v=1581530114} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_large.jpg?v=1581530114 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_compact.jpg?v=1581530114 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_medium.jpg?v=1581530114 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_grande.jpg?v=1581530114 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_product_cash_shirt_indigo_sashiko_006_1024x1024.jpg?v=1581530114} 1024w"
data-sizes="auto"
sizes="324px"
/>
</a>
<figcaption>
<b>
<span className="title">The Cash Shirt</span>
<span className="subtitle">in Indigo Sashiko</span>
<span>$125</span>
</b>
</figcaption>
</figure>
</li>
<li>
<figure>
<a href="/products/the-california-in-indigo-dobby">
<img
className="lazyload feature"
alt="The California in Indigo Dobby - featured image"
src="https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_large.jpg?v=1571341344"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_large.jpg?v=1571341344 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_compact.jpg?v=1571341344 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_medium.jpg?v=1571341344 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_grande.jpg?v=1571341344 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_1024x1024.jpg?v=1571341344} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_large.jpg?v=1571341344 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_compact.jpg?v=1571341344 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_medium.jpg?v=1571341344 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_grande.jpg?v=1571341344 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/INDIGO_DOBI_CALY_2_1024x1024.jpg?v=1571341344} 1024w"
data-sizes="auto"
/>
<img
className="lazyunload lazypreload swap ls-is-cached lazyautosizes lazyloaded"
alt="The California in Indigo Dobby - alternate view"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_large.jpg?v=1571341362 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_compact.jpg?v=1571341362 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_medium.jpg?v=1571341362 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_grande.jpg?v=1571341362 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_1024x1024.jpg?v=1571341362} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_large.jpg?v=1571341362 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_compact.jpg?v=1571341362 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_medium.jpg?v=1571341362 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_grande.jpg?v=1571341362 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/mens_workshop_Q319_california_indigo_dobby_04_1024x1024.jpg?v=1571341362} 1024w"
data-sizes="auto"
sizes="324px"
/>
</a>
<figcaption>
<b>
<span className="title">The California</span>
<span className="subtitle">in Indigo Dobby</span>
<span>$125</span>
</b>
</figcaption>
</figure>
</li>
<li>
<figure>
<a href="/products/the-crater-shirt-in-navy-plaid-2">
<img
className="lazyload feature"
alt="The Crater Shirt in Navy Plaid - featured image"
src="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_large.jpg?v=1571340411"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_large.jpg?v=1571340411 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_compact.jpg?v=1571340411 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_medium.jpg?v=1571340411 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_grande.jpg?v=1571340411 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_1024x1024.jpg?v=1571340411} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_large.jpg?v=1571340411 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_compact.jpg?v=1571340411 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_medium.jpg?v=1571340411 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_grande.jpg?v=1571340411 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_001_1024x1024.jpg?v=1571340411} 1024w"
data-sizes="auto"
/>
<img
className="lazyunload lazypreload swap ls-is-cached lazyautosizes lazyloaded"
alt="The Crater Shirt in Navy Plaid - alternate view"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_large.jpg?v=1571340435 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_compact.jpg?v=1571340435 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_medium.jpg?v=1571340435 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_grande.jpg?v=1571340435 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_1024x1024.jpg?v=1571340435} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_large.jpg?v=1571340435 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_compact.jpg?v=1571340435 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_medium.jpg?v=1571340435 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_grande.jpg?v=1571340435 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/workshop_mens_Q319_product_crater_navy_plaid_002_1024x1024.jpg?v=1571340435} 1024w"
data-sizes="auto"
sizes="324px"
/>
</a>
<figcaption>
<b>
<span className="title">The Crater Shirt</span>
<span className="subtitle">in Navy Plaid</span>
<span className="sale-price">$99</span>
<del>$128</del>
</b>
</figcaption>
</figure>
</li>
<li>
<figure>
<a href="/products/the-western-in-washed-denim">
<img
className="lazyload feature"
alt="The Western Shirt in Washed Denim - featured image"
src="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_large.jpg?v=1579560997"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_large.jpg?v=1579560997 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_compact.jpg?v=1579560997 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_medium.jpg?v=1579560997 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_grande.jpg?v=1579560997 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_1024x1024.jpg?v=1579560997} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_large.jpg?v=1579560997 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_compact.jpg?v=1579560997 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_medium.jpg?v=1579560997 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_grande.jpg?v=1579560997 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_001_1024x1024.jpg?v=1579560997} 1024w"
data-sizes="auto"
/>
<img
className="lazyunload lazypreload swap ls-is-cached lazyautosizes lazyloaded"
alt="The Western Shirt in Washed Denim - alternate view"
srcSet="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_large.jpg?v=1579561395 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_compact.jpg?v=1579561395 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_medium.jpg?v=1579561395 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_grande.jpg?v=1579561395 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_1024x1024.jpg?v=1579561395} 1024w"
data-srcset="https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_large.jpg?v=1579561395 480w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_compact.jpg?v=1579561395 160w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_medium.jpg?v=1579561395 240w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_grande.jpg?v=1579561395 600w, https://cdn.shopify.com/s/files/1/0070/1922/products/instock_mens_Q120_western_washed_denim_002_1024x1024.jpg?v=1579561395} 1024w"
data-sizes="auto"
sizes="324px"
/>
</a>
<figcaption>
<b>
<span className="title">The Western Shirt</span>
<span className="subtitle">in Washed Denim</span>{" "}
<span>$125</span>
</b>
</figcaption>
</figure>
</li>
</ul>
</div>
</Container>
)
export default Recommendation
|
frankbezema/argos-parent | argos-service/src/main/java/com/rabobank/argos/service/security/LogContextHelper.java | <filename>argos-service/src/main/java/com/rabobank/argos/service/security/LogContextHelper.java<gh_stars>0
/*
* Copyright (C) 2019 - 2020 <NAME>
*
* 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.rabobank.argos.service.security;
import com.rabobank.argos.service.domain.security.AccountUserDetailsAdapter;
import org.slf4j.MDC;
import java.util.UUID;
public class LogContextHelper {
void addAccountInfoToLogContext(AccountUserDetailsAdapter userDetails) {
MDC.put("accountId", userDetails.getAccount().getAccountId());
MDC.put("accountName", userDetails.getAccount().getName());
}
void addTraceIdToLogContext() {
MDC.put("traceId", UUID.randomUUID().toString());
}
}
|
uk-gov-mirror/ministryofjustice.cla_public | cla_public/apps/checker/fields.py | <filename>cla_public/apps/checker/fields.py
# coding: utf-8
"Custom form fields"
from collections import defaultdict, namedtuple
import itertools
import re
from flask import session
from flask.ext.babel import lazy_gettext as _
from wtforms import Form as NoCsrfForm, Label
from wtforms import FormField, IntegerField, RadioField, SelectField, SelectMultipleField, widgets, FieldList
from wtforms.validators import Optional, InputRequired
from cla_public.apps.base.forms import BabelTranslationsFormMixin
from cla_public.apps.checker.constants import MONEY_INTERVALS, NO, YES
from cla_public.apps.checker.validators import ValidMoneyInterval
from cla_public.libs.money_interval import MoneyInterval
def coerce_unicode_if_value(value):
return unicode(value) if value is not None else None
class PartnerMixin(object):
def __init__(self, *args, **kwargs):
partner_label = kwargs.pop("partner_label", kwargs.get("label"))
partner_description = kwargs.pop("partner_description", kwargs.get("description"))
if session.checker.has_partner:
kwargs["label"] = partner_label
kwargs["description"] = partner_description
super(PartnerMixin, self).__init__(*args, **kwargs)
class SelfEmployedMixin(object):
"""
Mix-in to allow fields to show different labels and descriptions
based on employed/self-employed choices made by the applicant or
about their partner
"""
EmploymentChoices = namedtuple("EmploymentChoices", "employed self_employed")
def __init__(self, *args, **kwargs):
label = kwargs.get("label")
description = kwargs.get("description")
label_dict = defaultdict(lambda: label)
label_dict.update(kwargs.pop("self_employed_labels", {}))
description_dict = defaultdict(lambda: description)
description_dict.update(kwargs.pop("self_employed_descriptions", {}))
self._label_dict = label_dict
self._description_dict = description_dict
super(SelfEmployedMixin, self).__init__(*args, **kwargs)
def set_self_employed_details(self, is_partner=False):
person_fields = ["is_employed", "is_self_employed"]
if is_partner:
person_fields = map(lambda f: "partner_%s" % f, person_fields)
person_fields = self.EmploymentChoices(*map(lambda f: getattr(session.checker, f), person_fields))
if person_fields.employed and person_fields.self_employed:
self.label = Label(self.id, self._label_dict["both"])
self.description = self._description_dict["both"]
elif person_fields.employed:
self.label = Label(self.id, self._label_dict["employed"])
self.description = self._description_dict["employed"]
elif person_fields.self_employed:
self.label = Label(self.id, self._label_dict["self_employed"])
self.description = self._description_dict["self_employed"]
else:
self.label = Label(self.id, self._label_dict["neither"])
self.description = self._description_dict["neither"]
class DescriptionRadioField(RadioField):
"""RadioField with a description for each radio button, not just for the
group.
The choices kwargs field takes a list of triples.
Format:
choices=[(name, label, description), ...]
"""
def __init__(self, *args, **kwargs):
self.options_attributes = []
self.field_names = []
self.descriptions = []
choices = []
for name, label, description in kwargs.get("choices", []):
self.field_names.append(name)
self.descriptions.append(description)
choices.append((name, label))
if choices:
kwargs["choices"] = choices
super(DescriptionRadioField, self).__init__(*args, **kwargs)
def __iter__(self):
options = super(DescriptionRadioField, self).__iter__()
for index, option in enumerate(options):
option.description = self.descriptions[index]
option.field_name = self.field_names[index]
try:
option_attributes = self.options_attributes[index]
option.__dict__.update(option_attributes)
except IndexError:
pass
yield option
def add_options_attributes(self, options_attributes):
self.options_attributes = options_attributes
class YesNoField(RadioField):
"""Yes/No radio button field"""
_yes_no_field = True
def __init__(self, label=None, validators=None, yes_text=_("Yes"), no_text=_("No"), **kwargs):
choices = [(YES, yes_text), (NO, no_text)]
if validators is None:
validators = [InputRequired(message=_(u"Please choose Yes or No"))]
super(YesNoField, self).__init__(
label=label, validators=validators, coerce=coerce_unicode_if_value, choices=choices, **kwargs
)
def set_zero_values(form):
"""Set values on a form to zero"""
def set_zero(field):
if hasattr(field, "set_zero"):
field.set_zero()
map(set_zero, form._fields.itervalues())
return form
class SetZeroIntegerField(IntegerField):
def set_zero(self):
self.data = 0
class SetZeroFormField(FormField):
def set_zero(self):
set_zero_values(self.form)
class MoneyTextInput(widgets.TextInput):
def __call__(self, field, **kwargs):
return super(MoneyTextInput, self).__call__(field, **kwargs)
class MoneyField(SetZeroIntegerField):
widget = MoneyTextInput()
def __init__(self, label=None, validators=None, min_val=0, max_val=9999999999, **kwargs):
super(MoneyField, self).__init__(label, validators, **kwargs)
self.min_val = min_val
self.max_val = max_val
def extract_pounds_and_pence(self, valuelist):
pounds, _, pence = valuelist[0].strip().partition(".")
try:
pounds = pounds.decode("utf-8")
except UnicodeEncodeError:
# Input is already in UTF-8 format
pass
# xa3 is the ASCII character reference for the pound sign
pounds = re.sub(r"^\xa3|[\s,]+", "", pounds)
return pounds, pence
def process_formdata(self, valuelist):
if valuelist:
pounds, pence = self.extract_pounds_and_pence(valuelist)
if pence:
if len(pence) > 2:
self.data = None
raise ValueError(self.gettext(u"Enter a number"))
if len(pence) == 1:
pence = "{0}0".format(pence)
try:
self.data = int(pounds) * 100
if pence:
self.data += int(pence)
except ValueError:
self.data = None
raise ValueError(self.gettext(u"Enter a number"))
if self.min_val is not None and self.data < self.min_val:
self.data = None
raise ValueError(self.gettext(u"Enter a value of more than £{:,.0f}").format(self.min_val / 100.0))
if self.max_val is not None and self.data > self.max_val:
self.data = None
raise ValueError(self.gettext(u"Enter a value of less than £{:,.0f}").format(self.max_val / 100.0))
def process_data(self, value):
self.data = value
if value:
pence = value % 100
pounds = value / 100
self.data = "{0:,}.{1:02}".format(pounds, pence)
class MoneyIntervalForm(BabelTranslationsFormMixin, NoCsrfForm):
"""Money amount and interval subform"""
per_interval_value = MoneyField(validators=[Optional()])
interval_period = SelectField("", choices=MONEY_INTERVALS, coerce=coerce_unicode_if_value)
def __init__(self, *args, **kwargs):
# Enable choices to be passed through
choices = kwargs.pop("choices", None)
super(MoneyIntervalForm, self).__init__(*args, **kwargs)
self.per_interval_value.label.text = kwargs.get("label")
if choices:
self.interval_period.choices = choices
@property
def data(self):
data = super(MoneyIntervalForm, self).data
if data["per_interval_value"] == 0 and not data["interval_period"]:
data["interval_period"] = MONEY_INTERVALS[1][0]
return data
def money_interval_to_monthly(data):
return MoneyInterval(data).per_month()
class PassKwargsToFormField(SetZeroFormField):
def __init__(self, *args, **kwargs):
form_kwargs = kwargs.pop("form_kwargs", {})
super(PassKwargsToFormField, self).__init__(*args, **kwargs)
self._form_class = self.form_class
def form_class_proxy(*f_args, **f_kwargs):
f_kwargs.update(form_kwargs)
return self._form_class(*f_args, **f_kwargs)
self.form_class = form_class_proxy
class MoneyIntervalField(PassKwargsToFormField):
"""Convenience class for FormField(MoneyIntervalForm)"""
def __init__(self, *args, **kwargs):
self._errors = []
self.validators = []
if "validators" in kwargs:
self.validators.extend(kwargs["validators"])
del kwargs["validators"]
self.validators.append(ValidMoneyInterval())
# Enable kwarg choices to be passed through to interval field
choices = kwargs.pop("choices", None)
super(MoneyIntervalField, self).__init__(
MoneyIntervalForm, form_kwargs={"choices": choices, "label": kwargs.get("label")}, *args, **kwargs
)
def as_monthly(self):
return money_interval_to_monthly(self.data)
def validate(self, form, extra_validators=None):
form_valid = self.form.validate()
self._run_validation_chain(form, self.validators)
return form_valid and len(self.errors) == 0
@property
def errors(self):
return self._errors
@errors.setter
def errors(self, _errors):
self._errors = _errors
def set_zero(self):
self.form.per_interval_value.data = 0
self.form.interval_period.data = "per_month"
class MultiCheckboxField(SelectMultipleField):
"""
A multiple-select, except displays a list of checkboxes.
Iterating the field will produce subfields, allowing custom rendering of
the enclosed checkbox fields.
"""
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class PropertyList(FieldList):
def remove(self, index):
del self.entries[index]
self.last_index -= 1
def validate(self, form, extra_validators=tuple()):
self.errors = []
for index, subfield in enumerate(self.entries):
if not subfield.validate(form):
self.errors.append({"_index": index, "_errors": subfield.errors})
chain = itertools.chain(self.validators, extra_validators)
self._run_validation_chain(form, chain)
main_properties = filter(lambda x: x.is_main_home.data == YES, self.entries)
if len(main_properties) > 1:
message = self.gettext("You can only have 1 main Property")
map(lambda x: x.is_main_home.errors.append(message), main_properties)
self.errors.append(message)
return len(self.errors) == 0
def set_zero(self):
self.entries = []
class PartnerMoneyIntervalField(PartnerMixin, MoneyIntervalField):
pass
class PartnerIntegerField(PartnerMixin, SetZeroIntegerField):
pass
class PartnerYesNoField(PartnerMixin, YesNoField):
pass
class PartnerMultiCheckboxField(PartnerMixin, MultiCheckboxField):
pass
class PartnerMoneyField(PartnerMixin, MoneyField):
pass
class SelfEmployedMoneyIntervalField(SelfEmployedMixin, MoneyIntervalField):
pass
|
ucdavis/uccsc-mobile | Components/Styles/ScheduleSectionHeaderStyle.js | import { StyleSheet } from 'react-native';
import { Colors, Fonts, Metrics } from '../../Themes/';
export default StyleSheet.create({
sectionHeaderContainer: {
flex: 1,
paddingTop: Metrics.baseMargin,
paddingBottom: Metrics.baseMargin,
backgroundColor: Colors.blue,
borderColor: 'rgba(253,229,255,0.5)',
borderBottomWidth: 1,
borderTopWidth: 1,
// shadowRadius: 20,
// shadowColor: 'black',
// shadowOpacity: 0.8,
// elevation: 20,
},
headerTime: {
textAlign: 'center',
color: Colors.snow,
},
});
|
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | XFree86-3.3/xc/programs/xkbcomp/xkbcomp.c | <filename>XFree86-3.3/xc/programs/xkbcomp/xkbcomp.c
/* $XConsortium: xkbcomp.c /main/12 1996/12/27 21:17:23 kaleb $ */
/* $XFree86: xc/programs/xkbcomp/xkbcomp.c,v 3.8 1997/01/27 07:00:20 dawes Exp $ */
/************************************************************
Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
Permission to use, copy, modify, and distribute this
software and its documentation for any purpose and without
fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting
documentation, and that the name of Silicon Graphics not be
used in advertising or publicity pertaining to distribution
of the software without specific prior written permission.
Silicon Graphics makes no representation about the suitability
of this software for any purpose. It is provided "as is"
without any express or implied warranty.
SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.
********************************************************/
#include <stdio.h>
#include <ctype.h>
#include <X11/keysym.h>
#if defined(sgi)
#include <malloc.h>
#endif
#define DEBUG_VAR_NOT_LOCAL
#define DEBUG_VAR debugFlags
#include "xkbcomp.h"
#ifndef X_NOT_STDC_ENV
#include <stdlib.h>
#endif
#include "xkbpath.h"
#include "parseutils.h"
#include "misc.h"
#include "tokens.h"
#include <X11/extensions/XKBgeom.h>
#ifdef __EMX__
#define chdir _chdir2
#endif
#define lowbit(x) ((x) & (-(x)))
/***====================================================================***/
#define WANT_DEFAULT 0
#define WANT_XKM_FILE 1
#define WANT_C_HDR 2
#define WANT_XKB_FILE 3
#define WANT_X_SERVER 4
#define WANT_LISTING 5
#define INPUT_UNKNOWN 0
#define INPUT_XKB 1
#define INPUT_XKM 2
static char *fileTypeExt[] = {
"XXX",
"xkm",
"h",
"xkb",
"dir"
};
static unsigned inputFormat,outputFormat;
char * rootDir;
static char * inputFile;
static char * inputMap;
static char * outputFile;
static char * inDpyName;
static char * outDpyName;
static Display * inDpy;
static Display * outDpy;
static Bool showImplicit= False;
static Bool synch= False;
static Bool merge= False;
static Bool computeDflts= False;
static Bool xkblist= False;
unsigned warningLevel= 5;
unsigned verboseLevel= 0;
unsigned dirsToStrip= 0;
unsigned optionalParts= 0;
static char * preErrorMsg= NULL;
static char * postErrorMsg= NULL;
static char * errorPrefix= NULL;
/***====================================================================***/
#define M(m) fprintf(stderr,(m))
#define M1(m,a) fprintf(stderr,(m),(a))
static void
#if NeedFunctionPrototypes
Usage(int argc,char *argv[])
#else
Usage(argc,argv)
int argc;
char * argv[];
#endif
{
if (!xkblist)
M1("Usage: %s [options] input-file [ output-file ]\n",argv[0]);
else M1("Usage: %s [options] file[(map)] ...\n",argv[0]);
M("Legal options:\n");
M("-?,-help Print this message\n");
if (!xkblist) {
M("-a Show all actions\n");
M("-C Create a C header file\n");
}
#ifdef DEBUG
M("-d [flags] Report debugging information\n");
#endif
M("-em1 <msg> Print <msg> before printing first error message\n");
M("-emp <msg> Print <msg> at the start of each message line\n");
M("-eml <msg> If there were any errors, print <msg> before exiting\n");
if (!xkblist) {
M("-dflts Compute defaults for missing parts\n");
M("-I[<dir>] Specifies a top level directory for include\n");
M(" directives. Multiple directories are legal.\n");
M("-l [flags] List matching maps in the specified files\n");
M(" f: list fully specified names\n");
M(" h: also list hidden maps\n");
M(" l: long listing (show flags)\n");
M(" p: also list partial maps\n");
M(" R: recursively list subdirectories\n");
M(" default is all options off\n");
}
M("-m[ap] <map> Specifies map to compile\n");
if (!xkblist)
M("-merge Merge file with map on server\n");
M("-o <file> Specifies output file name\n");
if (!xkblist) {
M("-opt[ional] <parts> Specifies optional components of keymap\n");
M(" Errors in optional parts are not fatal\n");
M(" <parts> can be any combination of:\n");
M(" c: compat map g: geometry\n");
M(" k: keycodes s: symbols\n");
M(" t: types\n");
}
if (xkblist) {
M("-p <count> Specifies the number of slashes to be stripped\n");
M(" from the front of the map name on output\n");
}
M("-R[<DIR>] Specifies the root directory for\n");
M(" relative path names\n");
M("-synch Force synchronization\n");
if (xkblist) {
M("-v [<flags>] Set level of detail for listing.\n");
M(" flags are as for the -l option\n");
}
M("-w [<lvl>] Set warning level (0=none, 10=all)\n");
if (!xkblist) {
M("-xkb Create an XKB source (.xkb) file\n");
M("-xkm Create a compiled key map (.xkm) file\n");
}
return;
}
/***====================================================================***/
static void
#if NeedFunctionPrototypes
setVerboseFlags(char *str)
#else
setVerboseFlags(str)
char * str;
#endif
{
for (;*str;str++) {
switch (*str) {
case 'f': verboseLevel|= WantFullNames; break;
case 'h': verboseLevel|= WantHiddenMaps; break;
case 'l': verboseLevel|= WantLongListing; break;
case 'p': verboseLevel|= WantPartialMaps; break;
case 'R': verboseLevel|= ListRecursive; break;
default:
if (warningLevel>4) {
WARN1("Unknown verbose option \"%c\"\n",(unsigned int)*str);
ACTION("Ignored\n");
}
break;
}
}
return;
}
static Bool
#if NeedFunctionPrototypes
parseArgs(int argc,char *argv[])
#else
parseArgs(argc,argv)
int argc;
char * argv[];
#endif
{
register int i,tmp;
i= strlen(argv[0]);
tmp= strlen("xkblist");
if ((i>=tmp)&&(strcmp(&argv[0][i-tmp],"xkblist")==0)) {
xkblist= True;
}
for (i=1;i<argc;i++) {
if ((argv[i][0]!='-')||(uStringEqual(argv[i],"-"))) {
if (!xkblist) {
if (inputFile==NULL)
inputFile= argv[i];
else if (outputFile==NULL)
outputFile= argv[i];
else if (warningLevel>0) {
WARN("Too many file names on command line\n");
ACTION3("Compiling %s, writing to %s, ignoring %s\n",
inputFile,outputFile,argv[i]);
}
}
else if (!AddMatchingFiles(argv[i]))
return False;
}
else if ((strcmp(argv[i],"-?")==0)||(strcmp(argv[i],"-help")==0)) {
Usage(argc,argv);
exit(0);
}
else if ((strcmp(argv[i],"-a")==0)&&(!xkblist)) {
showImplicit= True;
}
else if ((strcmp(argv[i],"-C")==0)&&(!xkblist)) {
if ((outputFormat!=WANT_DEFAULT)&&(outputFormat!=WANT_C_HDR)) {
if (warningLevel>0) {
WARN("Multiple output file formats specified\n");
ACTION1("\"%s\" flag ignored\n",argv[i]);
}
}
else outputFormat= WANT_C_HDR;
}
#ifdef DEBUG
else if (strcmp(argv[i],"-d")==0) {
if ((i>=(argc-1))||(!isdigit(argv[i+1][0]))) {
debugFlags= 1;
}
else {
sscanf(argv[++i],"%i",&debugFlags);
}
INFO1("Setting debug flags to %d\n",debugFlags);
}
#endif
else if ((strcmp(argv[i],"-dflts")==0)&&(!xkblist)) {
computeDflts= True;
}
else if (strcmp(argv[i],"-em1")==0) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No pre-error message specified\n");
ACTION("Trailing \"-em1\" option ignored\n");
}
}
else if (preErrorMsg!=NULL) {
if (warningLevel>0) {
WARN("Multiple pre-error messsages specified\n");
ACTION2("Compiling %s, ignoring %s\n",preErrorMsg,argv[i]);
}
}
else preErrorMsg= argv[i];
}
else if (strcmp(argv[i],"-emp")==0) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No error prefix specified\n");
ACTION("Trailing \"-emp\" option ignored\n");
}
}
else if (errorPrefix!=NULL) {
if (warningLevel>0) {
WARN("Multiple error prefixes specified\n");
ACTION2("Compiling %s, ignoring %s\n",errorPrefix,argv[i]);
}
}
else errorPrefix= argv[i];
}
else if (strcmp(argv[i],"-eml")==0) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No post-error message specified\n");
ACTION("Trailing \"-eml\" option ignored\n");
}
}
else if (postErrorMsg!=NULL) {
if (warningLevel>0) {
WARN("Multiple post-error messages specified\n");
ACTION2("Compiling %s, ignoring %s\n",postErrorMsg,argv[i]);
}
}
else postErrorMsg= argv[i];
}
else if ((strncmp(argv[i],"-I",2)==0)&&(!xkblist)) {
if (!XkbAddDirectoryToPath(&argv[i][2])) {
ACTION("Exiting\n");
}
exit(1);
}
else if ((strncmp(argv[i],"-l",2)==0)&&(!xkblist)) {
if (outputFormat!=WANT_DEFAULT) {
if (warningLevel>0) {
WARN("Multiple output file formats specified\n");
ACTION1("\"%s\" flag ignored\n",argv[i]);
}
}
else {
if (argv[i][2]!='\0')
setVerboseFlags(&argv[i][2]);
xkblist= True;
if ((inputFile)&&(!AddMatchingFiles(inputFile)))
return False;
else inputFile= NULL;
if ((outputFile)&&(!AddMatchingFiles(outputFile)))
return False;
else outputFile= NULL;
}
}
else if ((strcmp(argv[i],"-m")==0)||(strcmp(argv[i],"-map")==0)) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No map name specified\n");
ACTION1("Trailing \"%s\" option ignored\n",argv[i-1]);
}
}
else if (xkblist) {
if (!AddMapOnly(argv[i]))
return False;
}
else if (inputMap!=NULL) {
if (warningLevel>0) {
WARN("Multiple map names specified\n");
ACTION2("Compiling %s, ignoring %s\n",inputMap,argv[i]);
}
}
else inputMap= argv[i];
}
else if ((strcmp(argv[i],"-merge")==0)&&(!xkblist)) {
merge= True;
}
else if (strcmp(argv[i],"-o")==0) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No output file specified\n");
ACTION("Trailing \"-o\" option ignored\n");
}
}
else if (outputFile!=NULL) {
if (warningLevel>0) {
WARN("Multiple output files specified\n");
ACTION2("Compiling %s, ignoring %s\n",outputFile,argv[i]);
}
}
else outputFile= argv[i];
}
else if (((strcmp(argv[i],"-opt")==0)||(strcmp(argv[i],"optional")==0))
&&(!xkblist)) {
if (++i>=argc) {
if (warningLevel>0) {
WARN("No optional components specified\n");
ACTION1("Trailing \"%s\" option ignored\n",argv[i-1]);
}
}
else {
char *tmp2;
for (tmp2=argv[i];(*tmp2!='\0');tmp2++) {
switch (*tmp2) {
case 'c': case 'C':
optionalParts|= XkmCompatMapMask;
break;
case 'g': case 'G':
optionalParts|= XkmGeometryMask;
break;
case 'k': case 'K':
optionalParts|= XkmKeyNamesMask;
break;
case 's': case 'S':
optionalParts|= XkmSymbolsMask;
break;
case 't': case 'T':
optionalParts|= XkmTypesMask;
break;
default:
if (warningLevel>0) {
WARN1("Illegal component for %s option\n",
argv[i-1]);
ACTION1("Ignoring unknown specifier \"%c\"\n",
(unsigned int)*tmp2);
}
break;
}
}
}
}
else if (strncmp(argv[i],"-p",2)==0) {
if (isdigit(argv[i][2])) {
sscanf(&argv[i][2],"%i",&dirsToStrip);
}
else if ((i<(argc-1))&&(isdigit(argv[i+1][0]))) {
sscanf(argv[++i],"%i",&dirsToStrip);
}
else {
dirsToStrip= 0;
}
if (warningLevel>5)
INFO1("Setting path count to %d\n",dirsToStrip);
}
else if (strncmp(argv[i],"-R",2)==0) {
if (argv[i][2]=='\0') {
if (warningLevel>0) {
WARN("No root directory specified\n");
ACTION("Ignoring -R option\n");
}
}
else if (rootDir!=NULL) {
if (warningLevel>0) {
WARN("Multiple root directories specified\n");
ACTION2("Using %s, ignoring %s\n",rootDir,argv[i]);
}
}
else {
rootDir= &argv[i][2];
if (warningLevel>8) {
WARN1("Changing root directory to \"%s\"\n",rootDir);
}
if ((chdir(rootDir)<0) && (warningLevel>0)) {
WARN1("Couldn't change directory to \"%s\"\n",rootDir);
ACTION("Root directory (-R) option ignored\n");
rootDir= NULL;
}
}
}
else if ((strcmp(argv[i],"-synch")==0)||(strcmp(argv[i],"-s")==0)) {
synch= True;
}
else if (strncmp(argv[i],"-v",2)==0) {
char *str;
if (argv[i][2]!='\0')
str= &argv[i][2];
else if ((i<(argc-1))&&(argv[i+1][0]!='-'))
str= argv[++i];
else str= NULL;
if (str)
setVerboseFlags(str);
}
else if (strncmp(argv[i],"-w",2)==0) {
if ((i>=(argc-1))||(!isdigit(argv[i+1][0]))) {
if (isdigit(argv[i][1]))
sscanf(&argv[i][1],"%i",&warningLevel);
else warningLevel= 0;
}
else {
sscanf(argv[++i],"%i",&warningLevel);
}
}
else if ((strcmp(argv[i],"-xkb")==0)&&(!xkblist)) {
if ((outputFormat!=WANT_DEFAULT)&&(outputFormat!=WANT_XKB_FILE)) {
if (warningLevel>0) {
WARN("Multiple output file formats specified\n");
ACTION1("\"%s\" flag ignored\n",argv[i]);
}
}
else outputFormat= WANT_XKB_FILE;
}
else if ((strcmp(argv[i],"-xkm")==0)&&(!xkblist)) {
if ((outputFormat!=WANT_DEFAULT)&&(outputFormat!=WANT_XKM_FILE)) {
if (warningLevel>0) {
WARN("Multiple output file formats specified\n");
ACTION1("\"%s\" flag ignored\n",argv[i]);
}
}
else outputFormat= WANT_XKM_FILE;
}
else {
ERROR1("Unknown flag \"%s\" on command line\n",argv[i]);
Usage(argc,argv);
return False;
}
}
if (xkblist)
inputFormat= INPUT_XKB;
else if (inputFile==NULL) {
ERROR("No input file specified\n");
return False;
}
else if (uStringEqual(inputFile,"-")) {
inputFormat= INPUT_XKB;
}
else if (strchr(inputFile,':')==0) {
int len;
len= strlen(inputFile);
if (inputFile[len-1]==')') {
char *tmp;
if ((tmp=strchr(inputFile,'('))!=0) {
*tmp= '\0'; inputFile[len-1]= '\0';
tmp++;
if (*tmp=='\0') {
WARN("Empty map in filename\n");
ACTION("Ignored\n");
}
else if (inputMap==NULL) {
inputMap= uStringDup(tmp);
}
else {
WARN("Map specified in filename and with -m flag\n");
ACTION1("map from name (\"%s\") ignored\n",tmp);
}
}
else {
ERROR1("Illegal name \"%s\" for input file\n",inputFile);
return False;
}
}
if ((len>4)&&(strcmp(&inputFile[len-4],".xkm")==0)) {
inputFormat= INPUT_XKM;
}
else {
FILE *file;
file= fopen(inputFile,"r");
if (file) {
if (XkmProbe(file)) inputFormat= INPUT_XKM;
else inputFormat= INPUT_XKB;
fclose(file);
}
else {
fprintf(stderr,"Cannot open \"%s\" for reading\n",inputFile);
return False;
}
}
}
else {
inDpyName= inputFile;
inputFile= NULL;
inputFormat= INPUT_XKM;
}
if (outputFormat==WANT_DEFAULT) {
if (xkblist) outputFormat= WANT_LISTING;
else if (inputFormat==INPUT_XKB) outputFormat= WANT_XKM_FILE;
else outputFormat= WANT_XKB_FILE;
}
if ((outputFormat==WANT_LISTING)&&(inputFormat!=INPUT_XKB)) {
if (inputFile)
ERROR("Cannot generate a listing from a .xkm file (yet)\n");
else ERROR("Cannot generate a listing from an X connection (yet)\n");
return False;
}
if (xkblist) {
if (outputFile==NULL) outputFile= uStringDup("-");
else if (strchr(outputFile,':')!=NULL) {
ERROR("Cannot write a listing to an X connection\n");
return False;
}
}
else if ((!outputFile) && (inputFile) && uStringEqual(inputFile,"-")) {
int len= strlen("stdin")+strlen(fileTypeExt[outputFormat])+2;
outputFile= uTypedCalloc(len,char);
if (outputFile==NULL) {
WSGO("Cannot allocate space for output file name\n");
ACTION("Exiting\n");
exit(1);
}
sprintf(outputFile,"stdin.%s",fileTypeExt[outputFormat]);
}
else if ((outputFile==NULL)&&(inputFile!=NULL)) {
int len;
char *base,*ext;
if (inputMap==NULL) {
base= strrchr(inputFile,'/');
if (base==NULL) base= inputFile;
else base++;
}
else base= inputMap;
len= strlen(base)+strlen(fileTypeExt[outputFormat])+2;
outputFile= uTypedCalloc(len,char);
if (outputFile==NULL) {
WSGO("Cannot allocate space for output file name\n");
ACTION("Exiting\n");
exit(1);
}
ext= strrchr(base,'.');
if (ext==NULL)
sprintf(outputFile,"%s.%s",base,fileTypeExt[outputFormat]);
else {
strcpy(outputFile,base);
strcpy(&outputFile[ext-base+1],fileTypeExt[outputFormat]);
}
}
else if (outputFile==NULL) {
int len;
char *ch,*name,buf[128];
if (inDpyName[0]==':')
sprintf(name=buf,"server%s",inDpyName);
else name= inDpyName;
len= strlen(name)+strlen(fileTypeExt[outputFormat])+2;
outputFile= uTypedCalloc(len,char);
if (outputFile==NULL) {
WSGO("Cannot allocate space for output file name\n");
ACTION("Exiting\n");
exit(1);
}
strcpy(outputFile,name);
for (ch=outputFile;(*ch)!='\0';ch++) {
if (*ch==':') *ch= '-';
else if (*ch=='.') *ch= '_';
}
*ch++= '.';
strcpy(ch,fileTypeExt[outputFormat]);
}
else if (strchr(outputFile,':')!=NULL) {
outDpyName= outputFile;
outputFile= NULL;
outputFormat= WANT_X_SERVER;
}
return True;
}
static Display *
#if NeedFunctionPrototypes
GetDisplay(char *program,char *dpyName)
#else
GetDisplay(program,dpyName)
char * program;
char * dpyName;
#endif
{
int mjr,mnr,error;
Display *dpy;
mjr= XkbMajorVersion;
mnr= XkbMinorVersion;
dpy= XkbOpenDisplay(dpyName,NULL,NULL,&mjr,&mnr,&error);
if (dpy==NULL) {
switch (error) {
case XkbOD_BadLibraryVersion:
INFO3("%s was compiled with XKB version %d.%02d\n",
program,XkbMajorVersion,XkbMinorVersion);
ERROR2("X library supports incompatible version %d.%02d\n",
mjr,mnr);
break;
case XkbOD_ConnectionRefused:
ERROR1("Cannot open display \"%s\"\n",dpyName);
break;
case XkbOD_NonXkbServer:
ERROR1("XKB extension not present on %s\n",dpyName);
break;
case XkbOD_BadServerVersion:
INFO3("%s was compiled with XKB version %d.%02d\n",
program,XkbMajorVersion,XkbMinorVersion);
ERROR3("Server %s uses incompatible version %d.%02d\n",
dpyName,mjr,mnr);
break;
default:
WSGO1("Unknown error %d from XkbOpenDisplay\n",error);
}
}
else if (synch)
XSynchronize(dpy,True);
return dpy;
}
/***====================================================================***/
extern int yydebug;
int
#if NeedFunctionPrototypes
main(int argc,char *argv[])
#else
main(argc,argv)
int argc;
char * argv[];
#endif
{
FILE * file;
XkbFile * rtrn;
XkbFile * mapToUse;
int ok;
XkbFileInfo result;
Status status;
#ifdef Lynx
{
extern FILE *yyin;
yyin = stdin;
uSetEntryFile(NullString);
uSetDebugFile(NullString);
uSetErrorFile(NullString);
}
#endif
if (!parseArgs(argc,argv))
exit(1);
#ifdef DEBUG
if (debugFlags&0x2)
yydebug= 1;
#endif
if (preErrorMsg)
uSetPreErrorMessage(preErrorMsg);
if (errorPrefix)
uSetErrorPrefix(errorPrefix);
if (postErrorMsg)
uSetPostErrorMessage(postErrorMsg);
file= NULL;
XkbInitAtoms(NULL);
XkbInitIncludePath();
if (xkblist) {
Bool gotSome;
gotSome= GenerateListing(outputFile);
if ((warningLevel>7)&&(!gotSome))
return -1;
return 0;
}
if (inputFile!=NULL) {
if (uStringEqual(inputFile,"-")) {
static char *in= "stdin";
file= stdin;
inputFile= in;
}
else {
file= fopen(inputFile,"r");
}
}
else if (inDpyName!=NULL) {
inDpy= GetDisplay(argv[0],inDpyName);
if (!inDpy) {
ACTION("Exiting\n");
exit(1);
}
}
if (outDpyName!=NULL) {
outDpy= GetDisplay(argv[0],outDpyName);
if (!outDpy) {
ACTION("Exiting\n");
exit(1);
}
}
if ((inDpy==NULL) && (outDpy==NULL)) {
int mjr,mnr;
mjr= XkbMajorVersion;
mnr= XkbMinorVersion;
if (!XkbLibraryVersion(&mjr,&mnr)) {
INFO3("%s was compiled with XKB version %d.%02d\n",
argv[0],XkbMajorVersion,XkbMinorVersion);
ERROR2("X library supports incompatible version %d.%02d\n",
mjr,mnr);
ACTION("Exiting\n");
exit(1);
}
}
if (file) {
ok= True;
setScanState(inputFile,1);
if ((inputFormat==INPUT_XKB)&&(XKBParseFile(file,&rtrn)&&(rtrn!=NULL))){
fclose(file);
mapToUse= rtrn;
if (inputMap!=NULL) {
while ((mapToUse)&&(!uStringEqual(mapToUse->name,inputMap))) {
mapToUse= (XkbFile *)mapToUse->common.next;
}
if (!mapToUse) {
FATAL2("No map named \"%s\" in \"%s\"\n",inputMap,
inputFile);
/* NOTREACHED */
}
}
else if (rtrn->common.next!=NULL) {
mapToUse= rtrn;
for (;mapToUse;mapToUse= (XkbFile*)mapToUse->common.next) {
if (mapToUse->flags&XkbLC_Default)
break;
}
if (!mapToUse) {
mapToUse= rtrn;
if (warningLevel>4) {
WARN1("No map specified, but \"%s\" has several\n",
inputFile);
ACTION1("Using the first defined map, \"%s\"\n",
mapToUse->name);
}
}
}
bzero((char *)&result,sizeof(result));
result.type= mapToUse->type;
if ((result.xkb= XkbAllocKeyboard())==NULL) {
WSGO("Cannot allocate keyboard description\n");
/* NOTREACHED */
}
switch (mapToUse->type) {
case XkmSemanticsFile:
case XkmLayoutFile:
case XkmKeymapFile:
ok= CompileKeymap(mapToUse,&result,MergeReplace);
break;
case XkmKeyNamesIndex:
ok= CompileKeycodes(mapToUse,&result,MergeReplace);
break;
case XkmTypesIndex:
ok= CompileKeyTypes(mapToUse,&result,MergeReplace);
break;
case XkmSymbolsIndex:
/* if it's just symbols, invent key names */
result.xkb->flags|= AutoKeyNames;
ok= False;
break;
case XkmCompatMapIndex:
ok= CompileCompatMap(mapToUse,&result,MergeReplace,NULL);
break;
case XkmGeometryFile:
case XkmGeometryIndex:
/* if it's just a geometry, invent key names */
result.xkb->flags|= AutoKeyNames;
ok= CompileGeometry(mapToUse,&result,MergeReplace);
break;
default:
WSGO1("Unknown file type %d\n",mapToUse->type);
ok= False;
break;
}
}
else if (inputFormat==INPUT_XKM) {
unsigned tmp;
bzero((char *)&result,sizeof(result));
if ((result.xkb= XkbAllocKeyboard())==NULL) {
WSGO("Cannot allocate keyboard description\n");
/* NOTREACHED */
}
tmp= XkmReadFile(file,0,XkmKeymapLegal,&result);
if (tmp==XkmKeymapLegal) {
ERROR1("Cannot read XKM file \"%s\"\n",inputFile);
ok= False;
}
}
else {
INFO1("Errors encountered in %s; not compiled.\n",inputFile);
ok= False;
}
}
else if (inDpy!=NULL) {
bzero((char *)&result,sizeof(result));
result.type= XkmKeymapFile;
result.xkb= XkbGetMap(inDpy,XkbAllMapComponentsMask,XkbUseCoreKbd);
if (result.xkb==NULL)
WSGO("Cannot load keyboard description\n");
if (XkbGetIndicatorMap(inDpy,~0,result.xkb)!=Success)
WSGO("Could not load indicator map\n");
if (XkbGetControls(inDpy,XkbAllControlsMask,result.xkb)!=Success)
WSGO("Could not load keyboard controls\n");
if (XkbGetCompatMap(inDpy,XkbAllCompatMask,result.xkb)!=Success)
WSGO("Could not load compatibility map\n");
if (XkbGetNames(inDpy,XkbAllNamesMask,result.xkb)!=Success)
WSGO("Could not load names\n");
if ((status=XkbGetGeometry(inDpy,result.xkb))!=Success) {
if (warningLevel>3) {
char buf[100];
buf[0]= '\0';
XGetErrorText(inDpy,status,buf,100);
WARN1("Could not load keyboard geometry for %s\n",inDpyName);
ACTION1("%s\n",buf);
ACTION("Resulting keymap file will not describe geometry\n");
}
}
if (computeDflts)
ok= (ComputeKbdDefaults(result.xkb)==Success);
else ok= True;
}
else {
fprintf(stderr,"Cannot open \"%s\" to compile\n",inputFile);
ok= 0;
}
if (ok) {
FILE *out = stdout;
if ((inDpy!=outDpy)&&
(XkbChangeKbdDisplay(outDpy,&result)!=Success)) {
WSGO2("Error converting keyboard display from %s to %s\n",
inDpyName,outDpyName);
exit(1);
}
if (outputFile!=NULL) {
if (uStringEqual(outputFile,"-")) {
static char *of= "stdout";
outputFile= of;
}
else {
out= fopen(outputFile,"w");
if (out==NULL) {
ERROR1("Cannot open \"%s\" to write keyboard description\n",
outputFile);
ACTION("Exiting\n");
exit(1);
}
}
}
switch (outputFormat) {
case WANT_XKM_FILE:
ok= XkbWriteXKMFile(out,&result);
break;
case WANT_XKB_FILE:
ok= XkbWriteXKBFile(out,&result,showImplicit,NULL,NULL);
break;
case WANT_C_HDR:
ok= XkbWriteCFile(out,outputFile,&result);
break;
case WANT_X_SERVER:
if (!(ok= XkbWriteToServer(&result))) {
ERROR2("%s in %s\n",_XkbErrMessages[_XkbErrCode],
_XkbErrLocation?_XkbErrLocation:"unknown");
ACTION1("Couldn't write keyboard description to %s\n",
outDpyName);
}
break;
default:
WSGO1("Unknown output format %d\n",outputFormat);
ACTION("No output file created\n");
ok= False;
break;
}
if (outputFormat!=WANT_X_SERVER) {
fclose(out);
if (!ok) {
ERROR2("%s in %s\n",_XkbErrMessages[_XkbErrCode],
_XkbErrLocation?_XkbErrLocation:"unknown");
ACTION1("Output file \"%s\" removed\n",outputFile);
unlink(outputFile);
}
}
}
if (inDpy)
XCloseDisplay(inDpy);
inDpy= NULL;
if (outDpy)
XCloseDisplay(outDpy);
uFinishUp();
return (ok==0);
}
|
sobomax/microsippy | platforms/freertos/esp8266/usipy_port/byteorder.h | <gh_stars>10-100
#include <lwip/def.h>
#ifndef BYTE_ORDER
#error BYTE_ORER is unknown
#endif
#if BYTE_ORDER == LITTLE_ENDIAN
#define USIPY_BIGENDIAN 0
#else
#define USIPY_BIGENDIAN 1
#endif
|
ajs6f/trellis | core/http/src/test/java/org/trellisldp/http/AbstractTrellisHttpResourceTest.java | /*
* 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.trellisldp.http;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.time.Instant.MAX;
import static java.time.Instant.ofEpochSecond;
import static java.time.ZoneOffset.UTC;
import static java.time.ZonedDateTime.parse;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Date.from;
import static java.util.Objects.nonNull;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static java.util.function.Predicate.isEqual;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import static javax.servlet.http.HttpServletResponse.SC_GONE;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
import static javax.servlet.http.HttpServletResponse.SC_NOT_ACCEPTABLE;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED;
import static javax.servlet.http.HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE;
import static javax.ws.rs.HttpMethod.DELETE;
import static javax.ws.rs.HttpMethod.GET;
import static javax.ws.rs.HttpMethod.HEAD;
import static javax.ws.rs.HttpMethod.OPTIONS;
import static javax.ws.rs.HttpMethod.POST;
import static javax.ws.rs.HttpMethod.PUT;
import static javax.ws.rs.client.Entity.entity;
import static javax.ws.rs.core.HttpHeaders.CACHE_CONTROL;
import static javax.ws.rs.core.HttpHeaders.CONTENT_LOCATION;
import static javax.ws.rs.core.HttpHeaders.LINK;
import static javax.ws.rs.core.HttpHeaders.VARY;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.trellisldp.api.Resource.SpecialResources.DELETED_RESOURCE;
import static org.trellisldp.api.Resource.SpecialResources.MISSING_RESOURCE;
import static org.trellisldp.api.TrellisUtils.TRELLIS_DATA_PREFIX;
import static org.trellisldp.http.core.HttpConstants.ACCEPT_DATETIME;
import static org.trellisldp.http.core.HttpConstants.ACCEPT_PATCH;
import static org.trellisldp.http.core.HttpConstants.ACCEPT_POST;
import static org.trellisldp.http.core.HttpConstants.ACCEPT_RANGES;
import static org.trellisldp.http.core.HttpConstants.APPLICATION_LINK_FORMAT;
import static org.trellisldp.http.core.HttpConstants.DIGEST;
import static org.trellisldp.http.core.HttpConstants.LINK_TEMPLATE;
import static org.trellisldp.http.core.HttpConstants.MEMENTO_DATETIME;
import static org.trellisldp.http.core.HttpConstants.PATCH;
import static org.trellisldp.http.core.HttpConstants.PREFER;
import static org.trellisldp.http.core.HttpConstants.RANGE;
import static org.trellisldp.http.core.HttpConstants.SLUG;
import static org.trellisldp.http.core.HttpConstants.WANT_DIGEST;
import static org.trellisldp.http.core.RdfMediaType.APPLICATION_LD_JSON;
import static org.trellisldp.http.core.RdfMediaType.APPLICATION_LD_JSON_TYPE;
import static org.trellisldp.http.core.RdfMediaType.APPLICATION_N_TRIPLES;
import static org.trellisldp.http.core.RdfMediaType.APPLICATION_SPARQL_UPDATE;
import static org.trellisldp.http.core.RdfMediaType.TEXT_TURTLE_TYPE;
import static org.trellisldp.vocabulary.RDF.type;
import static org.trellisldp.vocabulary.Trellis.InvalidCardinality;
import static org.trellisldp.vocabulary.Trellis.InvalidRange;
import static org.trellisldp.vocabulary.Trellis.PreferAccessControl;
import static org.trellisldp.vocabulary.Trellis.PreferServerManaged;
import static org.trellisldp.vocabulary.Trellis.PreferUserManaged;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.Quad;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.function.Executable;
import org.trellisldp.api.EventService;
import org.trellisldp.api.Resource;
import org.trellisldp.api.RuntimeTrellisException;
import org.trellisldp.vocabulary.ACL;
import org.trellisldp.vocabulary.DC;
import org.trellisldp.vocabulary.LDP;
import org.trellisldp.vocabulary.Memento;
import org.trellisldp.vocabulary.XSD;
/**
* @author acoburn
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
abstract class AbstractTrellisHttpResourceTest extends BaseTrellisHttpResourceTest {
/* ****************************** *
* HEAD Tests
* ****************************** */
@Test
public void testHeadDefaultType() {
final Response res = target(RESOURCE_PATH).request().head();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incorrect content-type: " + res.getMediaType());
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
}
/* ******************************* *
* GET Tests
* ******************************* */
@Test
public void testGetJson() throws IOException {
final Response res = target("/" + RESOURCE_PATH).request().accept("application/ld+json").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(ACCEPT_POST), "Unexpected Accept-Post header!");
assertAll("Check JSON-LD Response", checkJsonLdResponse(res));
assertAll("Check LD-Template headers", checkLdTemplateHeaders(res));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check Vary headers", checkVary(res, asList(ACCEPT_DATETIME, PREFER)));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@context", "title"), asList("mode", "created")));
}
@Test
public void testGetDefaultType() {
final Response res = target(RESOURCE_PATH).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incorrect content-type: " + res.getMediaType());
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
}
@Test
public void testGetDefaultType2() {
final Response res = target("resource").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incorrect content-type: " + res.getMediaType());
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
}
@Test
public void testScrewyAcceptDatetimeHeader() {
final Response res = target(RESOURCE_PATH).request().header("Accept-Datetime",
"it's pathetic how we both").get();
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testScrewyRange() {
final Response res = target(BINARY_PATH).request().header("Range", "say it to my face, then").get();
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetRootSlash() {
final Response res = target("/").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incorrect content-type: " + res.getMediaType());
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
}
@Test
public void testGetRoot() {
final Response res = target("").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incorrect content-type: " + res.getMediaType());
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
}
@Test
public void testGetDatetime() {
assumeTrue(getBaseUrl().startsWith("http://localhost"));
final Response res = target(RESOURCE_PATH).request()
.header(ACCEPT_DATETIME, RFC_1123_DATE_TIME.withZone(UTC).format(time)).get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(time, parse(res.getHeaderString(MEMENTO_DATETIME), RFC_1123_DATE_TIME).toInstant(),
"Incorrect Memento-Datetime value!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(HUB), "hub")), "Missing rel=hub header!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(getBaseUrl() + RESOURCE_PATH
+ "?version=1496262729"), "self")), "Missing rel=self header!");
assertFalse(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(getBaseUrl() + RESOURCE_PATH), "self")),
"Unexpected versionless rel=self header");
assertNotNull(res.getHeaderString(MEMENTO_DATETIME), "Missing Memento-Datetime header!");
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testGetTrailingSlash() {
final Response res = target(RESOURCE_PATH + "/").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(from(time), res.getLastModified(), "Incorrect modified date!");
assertTrue(hasTimeGateLink(res, RESOURCE_PATH), "Missing rel=timegate link!");
assertTrue(hasOriginalLink(res, RESOURCE_PATH), "Missing rel=original link!");
}
@Test
public void testGetNotModified() {
final Response res = target("").request().header("If-Modified-Since", "Wed, 12 Dec 2018 07:28:00 GMT").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetNotModifiedInvalidDate() {
final Response res = target("").request().header("If-Modified-Since", "Wed, 12 Dec 2017 07:28:00 GMT").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetNotModifiedInvalidSyntax() {
final Response res = target("").request().header("If-Modified-Since", "Yesterday").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatchStar() {
final Response res = target("").request().header("If-None-Match", "*").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfMatchWeak() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-Match", "W/\"" + etag + "\"").get();
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfMatch() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-Match", "\"" + etag + "\"").get();
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatchFoo() {
final Response res = target("").request().header("If-None-Match", "\"blah\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatch() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-None-Match", "\"" + etag + "\"").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatchWeak() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-None-Match", "W/\"" + etag + "\"").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfMatchBinaryWeak() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-Match", "W/\"" + etag + "\"").get();
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfMatchBinary() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-Match", "\"" + etag + "\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatchBinary() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-None-Match", "\"" + etag + "\"").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetIfNoneMatchWeakBinary() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-None-Match", "W/\"" + etag + "\"").get();
assertEquals(SC_NOT_MODIFIED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetBinaryDescription() {
final Response res = target(BINARY_PATH).request().accept("text/turtle").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(HUB), "hub")), "Missing rel=hub header!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(getBaseUrl() + BINARY_PATH), "self")),
"Missing rel=self header!");
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incorrect content-type: " + res.getMediaType());
assertNull(res.getHeaderString(ACCEPT_RANGES), "Unexpected Accept-Ranges header!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
assertAll("Check Vary headers", checkVary(res, asList(ACCEPT_DATETIME, PREFER)));
assertAll("Check allowed methods",
checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS, POST)));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testGetBinary() throws IOException {
final Response res = target(BINARY_PATH).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(HUB), "hub")), "Missing rel=hub header!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(getBaseUrl() + BINARY_PATH), "self")),
"Missing rel=hub header!");
assertAll("Check Binary response", checkBinaryResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("Some input stream", entity, "Incorrect entity value!");
}
@Test
public void testGetBinaryDigestInvalid() throws IOException {
final Response res = target(BINARY_PATH).request().header(WANT_DIGEST, "FOO").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(DIGEST), "Unexpected Digest header!");
assertAll("Check Binary response", checkBinaryResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("Some input stream", entity, "Incorrect entity value!");
}
@Test
public void testGetBinaryDigestMd5() throws IOException {
final Response res = target(BINARY_PATH).request().header(WANT_DIGEST, "MD5").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals("md5=Q29tcHV0ZWREaWdlc3Q=", res.getHeaderString(DIGEST), "Incorrect Digest header value!");
assertAll("Check Binary response", checkBinaryResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("Some input stream", entity, "Incorrect entity value!");
}
@Test
public void testGetBinaryDigestSha1() throws IOException {
final Response res = target(BINARY_PATH).request().header(WANT_DIGEST, "SHA").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals("sha=Q29tcHV0ZWREaWdlc3Q=", res.getHeaderString(DIGEST), "Incorrect Digest header value!");
assertAll("Check Binary response", checkBinaryResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("Some input stream", entity, "Incorrect entity value!");
}
@Test
public void testGetBinaryRange() throws IOException {
final Response res = target(BINARY_PATH).request().header(RANGE, "bytes=3-10").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check Binary response", checkBinaryResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("e input", entity, "Incorrect entity value!");
}
@Test
public void testGetBinaryErrorSkip() throws IOException {
when(mockBinaryService.get(eq(binaryInternalIdentifier))).thenAnswer(inv -> completedFuture(mockBinary));
when(mockBinary.getContent()).thenReturn(mockInputStream);
when(mockInputStream.skip(anyLong())).thenThrow(new IOException());
final Response res = target(BINARY_PATH).request().header(RANGE, "bytes=300-400").get();
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetBinaryDigestError() throws Exception {
when(mockBinaryService.calculateDigest(eq(binaryInternalIdentifier), any(MessageDigest.class)))
.thenAnswer(inv ->
supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(BINARY_PATH).request().header(WANT_DIGEST, "MD5").get();
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetVersionError() {
final Response res = target(BINARY_PATH).queryParam("version", "looking at my history").request().get();
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetVersionNotFound() {
final Response res = target(NON_EXISTENT_PATH).queryParam("version", "1496260729").request().get();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetTimemapNotFound() {
final Response res = target(NON_EXISTENT_PATH).queryParam("ext", "timemap").request().get();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetTimegateNotFound() {
final Response res = target(NON_EXISTENT_PATH).request()
.header(ACCEPT_DATETIME, "Wed, 16 May 2018 13:18:57 GMT").get();
assertEquals(SC_NOT_ACCEPTABLE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetBinaryVersion() throws IOException {
final Response res = target(BINARY_PATH).queryParam("version", timestamp).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check Memento headers", checkMementoHeaders(res, BINARY_PATH));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
assertTrue(res.getMediaType().isCompatible(TEXT_PLAIN_TYPE), "Incorrect content-type: " + res.getMediaType());
assertEquals("bytes", res.getHeaderString(ACCEPT_RANGES), "Incorrect Accept-Ranges header!");
assertNotNull(res.getHeaderString(MEMENTO_DATETIME), "Missing Memento-Datetime header!");
assertEquals(time, parse(res.getHeaderString(MEMENTO_DATETIME), RFC_1123_DATE_TIME).toInstant(),
"Incorrect Memento-Datetime header value!");
assertAll("Check Vary headers", checkVary(res, asList(RANGE, WANT_DIGEST)));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertEquals("Some input stream", entity, "Incorrect entity value!");
}
@Test
public void testPrefer() throws IOException {
final Response res = target(RESOURCE_PATH).request()
.header("Prefer", "return=representation; include=\"" + PreferServerManaged.getIRIString() + "\"")
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@context", "title"), asList("mode", "created")));
assertEquals("A title", (String) obj.get("title"), "Incorrect title value!");
}
@Test
public void testPrefer2() throws IOException {
when(mockResource.getInteractionModel()).thenReturn(LDP.BasicContainer);
when(mockResource.stream()).thenAnswer(inv -> getPreferQuads());
final Response res = target(RESOURCE_PATH).request()
.header("Prefer", "return=representation; include=\"" + LDP.PreferMinimalContainer.getIRIString() + "\"")
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertAll("Check JSON-LD structure", checkJsonStructure(obj, asList("@context", "title"),
asList("mode", "created", "contains", "member")));
assertEquals("A title", (String) obj.get("title"), "Incorrect title value!");
}
@Test
public void testPrefer3() throws IOException {
when(mockResource.getInteractionModel()).thenReturn(LDP.BasicContainer);
when(mockResource.stream()).thenAnswer(inv -> getPreferQuads());
final Response res = target(RESOURCE_PATH).request()
.header("Prefer", "return=representation; omit=\"" + LDP.PreferMinimalContainer.getIRIString() + "\"")
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertAll("Check JSON-LD structure", checkJsonStructure(obj, asList("@context", "contains", "member"),
asList("title", "mode", "created")));
}
@Test
public void testGetJsonCompact() throws IOException {
final Response res = target(RESOURCE_PATH).request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check LDF response", checkLdfResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertEquals("A title", (String) obj.get("title"), "Incorrect title property in JSON!");
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@context", "title"), asList("mode", "created")));
}
@Test
public void testGetJsonCompactLDF1() throws IOException {
when(mockResource.stream()).thenAnswer(inv -> getLdfQuads());
final Response res = target(RESOURCE_PATH).queryParam("subject", getBaseUrl() + RESOURCE_PATH)
.queryParam("predicate", "http://purl.org/dc/terms/title").request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check LDF response", checkLdfResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertTrue(obj.get("title") instanceof List, "title property isn't a List!");
@SuppressWarnings("unchecked")
final List<Object> titles = (List<Object>) obj.get("title");
assertTrue(titles.contains("A title"), "Incorrect title value!");
assertEquals(2L, titles.size(), "Incorrect title property size!");
assertEquals(getBaseUrl() + RESOURCE_PATH, obj.get("@id"), "Incorrect @id value!");
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@context", "title"), asList("creator", "mode", "created")));
}
@Test
public void testGetJsonCompactLDF2() throws IOException {
when(mockResource.stream()).thenAnswer(inv -> getLdfQuads());
final Response res = target(RESOURCE_PATH).queryParam("subject", getBaseUrl() + RESOURCE_PATH)
.queryParam("object", "ex:Type").queryParam("predicate", "").request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check LDF response", checkLdfResponse(res));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertEquals("ex:Type", obj.get("@type"), "Incorrect @type value!");
assertEquals(getBaseUrl() + RESOURCE_PATH, obj.get("@id"), "Incorrect @id value!");
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@type"), asList("@context", "creator", "title", "mode", "created")));
}
@Test
public void testGetJsonCompactLDF3() throws IOException {
when(mockResource.stream()).thenAnswer(inv -> getLdfQuads());
final Response res = target(RESOURCE_PATH).queryParam("subject", getBaseUrl() + RESOURCE_PATH)
.queryParam("object", "A title").queryParam("predicate", DC.title.getIRIString()).request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(from(time), res.getLastModified(), "Incorrect modified date!");
assertTrue(hasTimeGateLink(res, RESOURCE_PATH), "Missing rel=timegate link!");
assertTrue(hasOriginalLink(res, RESOURCE_PATH), "Missing rel=original link!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check Vary headers", checkVary(res, asList(ACCEPT_DATETIME, PREFER)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_RANGES)));
assertAll("Check JSON-LD Response", checkJsonLdResponse(res));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertEquals("A title", obj.get("title"), "Incorrect title property!");
assertEquals(getBaseUrl() + RESOURCE_PATH, obj.get("@id"), "Incorrect @id value!");
assertAll("Check JSON-LD structure",
checkJsonStructure(obj, asList("@context", "title"), asList("@type", "creator", "mode", "created")));
}
@Test
public void testGetTimeMapLinkDefaultFormat() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(MediaType.valueOf(APPLICATION_LINK_FORMAT), res.getMediaType(), "Incorrect content-type!");
}
@Test
public void testGetTimeMapLinkDefaultFormat2() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target("resource").queryParam("ext", "timemap").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(MediaType.valueOf(APPLICATION_LINK_FORMAT), res.getMediaType(), "Incorrect content-type!");
}
@Test
public void testGetTimeMapLinkInvalidFormat() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.accept("some/made-up-format").get();
assertEquals(SC_NOT_ACCEPTABLE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetTimeMapLink() throws IOException {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.mementos(eq(identifier))).thenReturn(completedFuture(new TreeSet<>(asList(
ofEpochSecond(timestamp - 2000), ofEpochSecond(timestamp - 1000), time))));
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.accept(APPLICATION_LINK_FORMAT).get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(MediaType.valueOf(APPLICATION_LINK_FORMAT), res.getMediaType(), "Incorrect content-type!");
assertNull(res.getLastModified(), "Unexpected last-modified header!");
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers",
checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, ACCEPT_RANGES, MEMENTO_DATETIME)));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final List<Link> entityLinks = stream(entity.split(",\n")).map(Link::valueOf).collect(toList());
assertEquals(4L, entityLinks.size(), "Incorrect number of Link headers!");
final List<Link> links = getLinks(res);
assertAll("Check link headers", entityLinks.stream().map(l ->
() -> assertTrue(links.contains(l), "Link not in response: " + l)));
}
@Test
public void testGetTimeMapJsonCompact() throws IOException {
when(mockMementoService.mementos(eq(identifier))).thenReturn(completedFuture(new TreeSet<>(asList(
ofEpochSecond(timestamp - 2000), ofEpochSecond(timestamp - 1000), time))));
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertNull(res.getLastModified(), "Incorrect last modified date!");
assertAll("Check Simple JSON-LD", checkSimpleJsonLdResponse(res, LDP.RDFSource));
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers",
checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, ACCEPT_RANGES, MEMENTO_DATETIME)));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity,
new TypeReference<Map<String, Object>>(){});
@SuppressWarnings("unchecked")
final List<Map<String, Object>> graph = (List<Map<String, Object>>) obj.get("@graph");
assertEquals(5L, graph.size(), "Incorrect @graph size!");
assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH) &&
x.containsKey("timegate") && x.containsKey("timemap") && x.containsKey("memento")),
"Missing memento-related properties in graph for given @id");
assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?ext=timemap") &&
x.containsKey("hasBeginning") &&
x.containsKey("hasEnd")),
"Missing hasBeginning/hasEnd properties in timemap graph!");
assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496260729") &&
x.containsKey("hasTime")), "Missing hasTime property in timemap graph for version 1!");
assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496261729") &&
x.containsKey("hasTime")), "Missing hasTime property in timemap graph for version 2!");
assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496262729") &&
x.containsKey("hasTime")), "Missign hasTime property in timemap graph for version 3!");
}
@Test
public void testGetTimeMapJson() throws IOException {
when(mockMementoService.mementos(eq(identifier))).thenReturn(completedFuture(new TreeSet<>(asList(
ofEpochSecond(timestamp - 2000), ofEpochSecond(timestamp - 1000), time))));
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#expanded\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertNull(res.getLastModified(), "Incorrect last-modified header!");
assertAll("Check Simple JSON-LD", checkSimpleJsonLdResponse(res, LDP.RDFSource));
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers",
checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, ACCEPT_RANGES, MEMENTO_DATETIME)));
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final List<Map<String, Object>> obj = MAPPER.readValue(entity,
new TypeReference<List<Map<String, Object>>>(){});
assertEquals(5L, obj.size(), "Incorrect number of properties in timemap JSON-LD!");
assertTrue(obj.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH) &&
x.containsKey("http://mementoweb.org/ns#timegate") &&
x.containsKey("http://mementoweb.org/ns#timemap") &&
x.containsKey("http://mementoweb.org/ns#memento")),
"Missing expected memento properties in expanded JSON-LD!");
assertTrue(obj.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?ext=timemap") &&
x.containsKey("http://www.w3.org/2006/time#hasBeginning") &&
x.containsKey("http://www.w3.org/2006/time#hasEnd")),
"Missing hasBeginning/hasEnd properties in expanded JSON-LD!");
assertTrue(obj.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496260729") &&
x.containsKey("http://www.w3.org/2006/time#hasTime")),
"Missing hasTime property in first memento!");
assertTrue(obj.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496261729") &&
x.containsKey("http://www.w3.org/2006/time#hasTime")),
"Missing hasTime property in second memento!");
assertTrue(obj.stream().anyMatch(x -> x.containsKey("@id") &&
x.get("@id").equals(getBaseUrl() + RESOURCE_PATH + "?version=1496262729") &&
x.containsKey("http://www.w3.org/2006/time#hasTime")),
"Missing hasTime property in third memento!");
}
@Test
public void testGetVersionJson() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(from(time), res.getLastModified(), "Incorrect last-modified header!");
assertEquals(time, parse(res.getHeaderString(MEMENTO_DATETIME), RFC_1123_DATE_TIME).toInstant(),
"Incorrect Memento-Datetime header!");
assertAll("Check Simple JSON-LD", checkSimpleJsonLdResponse(res, LDP.RDFSource));
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, ACCEPT_RANGES)));
}
@Test
public void testGetVersionContainerJson() {
when(mockVersionedResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(from(time), res.getLastModified(), "Incorrect last-modified header!");
assertEquals(time, parse(res.getHeaderString(MEMENTO_DATETIME), RFC_1123_DATE_TIME).toInstant(),
"Incorrect Memento-Datetime header!");
assertAll("Check Simple JSON-LD", checkSimpleJsonLdResponse(res, LDP.Container));
assertAll("Check Memento headers", checkMementoHeaders(res, RESOURCE_PATH));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, ACCEPT_RANGES)));
}
@Test
public void testGetNoAcl() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request().get();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetBinaryAcl() {
when(mockBinaryResource.hasAcl()).thenReturn(true);
final Response res = target(BINARY_PATH).queryParam("ext", "acl").request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describes")), "Unexpected rel=describes");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describedby")),
"Unexpected rel=describedby");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("canonical")), "Unexpected rel=canonical");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("alternate")), "Unexpected rel=alternate");
}
@Test
public void testGetBinaryLinks() {
final Response res = target(BINARY_PATH).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describes")), "Unexpected rel=describes");
assertTrue(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describedby")), "Missing rel=describedby");
assertTrue(getLinks(res).stream().anyMatch(l -> l.getRel().equals("canonical")), "Missing rel=canonical");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("alternate")), "Unexpected rel=alternate");
}
@Test
public void testGetBinaryDescriptionLinks() {
final Response res = target(BINARY_PATH).request().accept("text/turtle").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describes")), "Missing rel=describes");
assertFalse(getLinks(res).stream().anyMatch(l -> l.getRel().equals("describedby")),
"Unexpected rel=describedby");
assertTrue(getLinks(res).stream().anyMatch(l -> l.getRel().equals("canonical")), "Missing rel=canonical");
assertTrue(getLinks(res).stream().anyMatch(l -> l.getRel().equals("alternate")), "Missing rel=alternate");
}
@Test
public void testGetAclJsonCompact() throws IOException {
when(mockResource.hasAcl()).thenReturn(true);
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header");
assertEquals(from(time), res.getLastModified(), "Incorrect last-modified header!");
assertFalse(hasTimeGateLink(res, RESOURCE_PATH), "Unexpected rel=timegate link");
assertFalse(hasOriginalLink(res, RESOURCE_PATH), "Unexpected rel=original link");
assertTrue(res.hasEntity(), "Missing entity!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});
assertEquals(ACL.Control.getIRIString(), (String) obj.get("mode"), "Incorrect ACL mode property!");
assertAll("Check Simple JSON-LD", checkSimpleJsonLdResponse(res, LDP.RDFSource));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, GET, HEAD, OPTIONS)));
assertAll("Check Vary headers", checkVary(res, asList(ACCEPT_DATETIME)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_RANGES)));
assertAll("Check JSON-LD structure", checkJsonStructure(obj, asList("@context", "mode"), asList("title")));
}
@Test
public void testGetResource() {
final Response res = target(RESOURCE_PATH).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetNotFound() {
final Response res = target(NON_EXISTENT_PATH).request().get();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetGone() {
final Response res = target(DELETED_PATH).request().get();
assertEquals(SC_GONE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testGetCORSInvalid() {
final Response res = target(RESOURCE_PATH).request().header("Origin", "http://foo.com")
.header("Access-Control-Request-Method", "PUT")
.header("Access-Control-Request-Headers", "Content-Type, Link").get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check null headers", checkNullHeaders(res, asList("Access-Control-Allow-Origin",
"Access-Control-Allow-Credentials", "Access-Control-Max-Age",
"Access-Control-Allow-Headers", "Access-Control-Allow-Methods")));
}
@Test
public void testGetException() {
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().get();
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/* ******************************* *
* OPTIONS Tests
* ******************************* */
@Test
public void testOptionsLDPRS() {
final Response res = target(RESOURCE_PATH).request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(MEMENTO_DATETIME)));
}
@Test
public void testOptionsLDPNR() {
final Response res = target(BINARY_PATH).request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, MEMENTO_DATETIME)));
}
@Test
public void testOptionsLDPC() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header!");
assertNotNull(res.getHeaderString(ACCEPT_POST), "Missing Accept-Post header!");
assertAll("Check allowed methods",
checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS, POST)));
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.Container));
assertAll("Check null headers", checkNullHeaders(res, asList(MEMENTO_DATETIME)));
final List<String> acceptPost = asList(res.getHeaderString(ACCEPT_POST).split(","));
assertEquals(3L, acceptPost.size(), "Accept-Post header has wrong number of elements!");
assertTrue(acceptPost.contains("text/turtle"), "Turtle missing from Accept-Post");
assertTrue(acceptPost.contains(APPLICATION_LD_JSON), "JSON-LD missing from Accept-Post");
assertTrue(acceptPost.contains(APPLICATION_N_TRIPLES), "N-Triples missing from Accept-Post");
}
@Test
public void testOptionsACL() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, MEMENTO_DATETIME)));
}
@Test
public void testOptionsNonexistent() {
final Response res = target(NON_EXISTENT_PATH).request().options();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testOptionsVersionNotFound() {
final Response res = target(NON_EXISTENT_PATH).queryParam("version", "1496260729").request().options();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testOptionsGone() {
final Response res = target(DELETED_PATH).request().options();
assertEquals(SC_GONE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testOptionsSlash() {
final Response res = target(RESOURCE_PATH + "/").request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), "Incorrect Accept-Patch header!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, MEMENTO_DATETIME)));
}
@Test
public void testOptionsTimemap() {
when(mockMementoService.mementos(eq(identifier))).thenReturn(completedFuture(new TreeSet<>(asList(
ofEpochSecond(timestamp - 2000), ofEpochSecond(timestamp - 1000), time))));
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_PATCH, MEMENTO_DATETIME)));
}
@Test
public void testOptionsVersion() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check allowed methods", checkAllowedMethods(res, asList(GET, HEAD, OPTIONS)));
assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_PATCH, ACCEPT_POST)));
}
@Test
public void testOptionsException() {
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().options();
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/* ******************************* *
* POST Tests
* ******************************* */
@Test
public void testPost() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE)),
eq(MAX))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertEquals(getBaseUrl() + RESOURCE_PATH + "/" + RANDOM_VALUE, res.getLocation().toString(),
"Incorrect Location header!");
assertFalse(getLinks(res).stream().map(Link::getRel).anyMatch(isEqual("describedby")),
"Unexpected describedby link!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPostRoot() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE)), eq(MAX)))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target("").request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertEquals(getBaseUrl() + RANDOM_VALUE, res.getLocation().toString(), "Incorrect Location header!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostInvalidLink() {
final Response res = target(RESOURCE_PATH).request().header("Link", "I never really liked his friends")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostToTimemap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostTypeMismatch() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.header("Link", "<http://www.w3.org/ns/ldp#NonRDFSource>; rel=\"type\"")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostConflict() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(mockResource));
final Response res = target(RESOURCE_PATH).request()
.header("Link", "<http://www.w3.org/ns/ldp#NonRDFSource>; rel=\"type\"")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostUnknownLinkType() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.header("Link", "<http://example.com/types/Foo>; rel=\"type\"")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertEquals(getBaseUrl() + RESOURCE_PATH + "/" + RANDOM_VALUE, res.getLocation().toString(),
"Incorrect Location header!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPostBadContent() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("<> <http://purl.org/dc/terms/title> A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostToLdpRs() {
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostSlug() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).request().header(SLUG, "child")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertEquals(getBaseUrl() + CHILD_PATH, res.getLocation().toString(), "Incorrect Location header!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostBadSlug() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
final Response res = target(RESOURCE_PATH).request().header(SLUG, "child/grandchild")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostVersion() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request().header(SLUG, "test")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostAcl() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request().header(SLUG, "test")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostIndirectContainer() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"An indirect container\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostIndirectContainerSelf() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(root));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A self-contained LDP-IC\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostIndirectContainerResource() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(identifier));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"An LDP-IC\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(3)).emit(any());
}
@Test
public void testPostDirectContainer() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"An LDP-DC\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostDirectContainerSelf() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(root));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A self-contained LDP-DC\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPostDirectContainerResource() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(identifier));
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target().request()
.post(entity("<> <http://purl.org/dc/terms/title> \"An LDP-DC resource\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(3)).emit(any());
}
@Test
public void testPostBadJsonLdSemantics() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("{\"@id\": \"\", \"@type\": \"some type\"}", APPLICATION_LD_JSON_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostBadJsonLdSyntax() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().post(entity("{\"@id:", APPLICATION_LD_JSON_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostConstraint() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("<> <http://www.w3.org/ns/ldp#inbox> \"Some literal\" .",
TEXT_TURTLE_TYPE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream()
.anyMatch(hasLink(InvalidRange, LDP.constrainedBy.getIRIString())), "Missing constrainedBy link");
}
@Test
public void testPostIgnoreContains() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.post(entity("<> <http://www.w3.org/ns/ldp#contains> <./other> . ",
TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostNonexistent() {
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + NON_EXISTENT_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(NON_EXISTENT_PATH).request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostGone() {
when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + DELETED_PATH + "/" + RANDOM_VALUE))))
.thenAnswer(inv -> completedFuture(DELETED_RESOURCE));
final Response res = target(DELETED_PATH).request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_GONE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostBinary() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().header(SLUG, "newresource")
.post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().map(Link::getRel).anyMatch(isEqual("describedby")), "No describedby link!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPostBinaryWithInvalidDigest() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().header(SLUG, "newresource")
.header(DIGEST, "md5=blahblah").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostUnparseableDigest() {
final Response res = target(RESOURCE_PATH).request()
.header(DIGEST, "digest this, man!").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostBinaryWithInvalidDigestType() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().header(SLUG, "newresource")
.header(DIGEST, "uh=huh").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostBinaryWithMd5Digest() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().header(DIGEST, "md5=BJozgIQwPzzVzSxvjQsWkA==")
.header(SLUG, "newresource").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPostBinaryWithSha1Digest() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request().header(DIGEST, "sha=3VWEuvPnAM6riDQJUu4TG7A4Ots=")
.header(SLUG, "newresource").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPostBinaryWithSha256Digest() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockMementoService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/newresource")),
any(Instant.class))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH).request()
.header(DIGEST, "sha-256=voCCIRTNXosNlEgQ/7IuX5dFNvFQx5MfG/jy1AKiLMU=")
.header(SLUG, "newresource").post(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPostTimeMap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostSlash() {
final Response res = target(RESOURCE_PATH + "/").request().header(SLUG, "test")
.post(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPostException() {
when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().post(entity("", TEXT_TURTLE_TYPE));
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/* ******************************* *
* PUT Tests
* ******************************* */
@Test
public void testPutExisting() {
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertFalse(getLinks(res).stream().map(Link::getRel).anyMatch(isEqual("describedby")),
"Unexpected describedby link!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutUncontainedIndirectContainer() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier));
when(mockResource.getContainer()).thenReturn(empty());
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutUncontainedIndirectContainerSelf() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(root));
when(mockResource.getContainer()).thenReturn(empty());
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutUncontainedIndirectContainerResource() {
final EventService myEventService = mock(EventService.class);
final Resource mockChildResource = mock(Resource.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockResourceService.get(childIdentifier)).thenAnswer(inv -> completedFuture(mockChildResource));
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(childIdentifier));
when(mockResource.getContainer()).thenReturn(empty());
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutIndirectContainer() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutIndirectContainerSelf() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(root));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPutIndirectContainerResource() {
final EventService myEventService = mock(EventService.class);
final Resource mockChildResource = mock(Resource.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockResourceService.get(childIdentifier)).thenAnswer(inv -> completedFuture(mockChildResource));
when(mockChildResource.getIdentifier()).thenReturn(childIdentifier);
when(mockChildResource.getInteractionModel()).thenReturn(LDP.RDFSource);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(childIdentifier));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(2)).emit(any());
}
@Test
public void testPutDirectContainer() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(newresourceIdentifier));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutDirectContainerSelf() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(root));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutDirectContainerResource() {
final EventService myEventService = mock(EventService.class);
when(mockBundler.getEventService()).thenReturn(myEventService);
when(mockRootResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
when(mockRootResource.getMembershipResource()).thenReturn(of(identifier));
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
verify(myEventService, times(1)).emit(any());
}
@Test
public void testPutExistingBinaryDescription() {
final Response res = target(BINARY_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutExistingUnknownLink() {
final Response res = target(RESOURCE_PATH).request()
.header("Link", "<http://example.com/types/Foo>; rel=\"type\"")
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutExistingIgnoreProperties() {
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" ;"
+ " <http://example.com/foo> <http://www.w3.org/ns/ldp#IndirectContainer> ;"
+ " a <http://example.com/Type1>, <http://www.w3.org/ns/ldp#BasicContainer> .",
TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutExistingSubclassLink() {
final Response res = target(RESOURCE_PATH).request()
.header("Link", LDP.Container + "; rel=\"type\"")
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.Container));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutExistingMalformed() {
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutConstraint() {
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> \"Some literal\" .",
TEXT_TURTLE_TYPE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream()
.anyMatch(hasLink(InvalidRange, LDP.constrainedBy.getIRIString())), "Missing constrainedBy header!");
}
@Test
public void testPutIgnoreContains() {
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://www.w3.org/ns/ldp#contains> <./other> . ",
TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutNew() {
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/test");
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
when(mockMementoService.get(eq(identifier), eq(MAX))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH + "/test").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertEquals(getBaseUrl() + RESOURCE_PATH + "/test", res.getHeaderString(CONTENT_LOCATION),
"Incorrect Location header!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutDeleted() {
final Response res = target(DELETED_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CREATED, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertEquals(getBaseUrl() + DELETED_PATH, res.getHeaderString(CONTENT_LOCATION), "Incorrect Location header!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutVersion() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutAcl() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPutAclOnDc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPutAclOnIc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPutOnDc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(InvalidCardinality, LDP.constrainedBy.getIRIString())),
"Missing constrainedBy header!");
}
@Test
public void testPutOnIc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
final Response res = target(RESOURCE_PATH).request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(InvalidCardinality, LDP.constrainedBy.getIRIString())),
"Missing constrainedBy header!");
}
@Test
public void testPutBinary() {
final Response res = target(BINARY_PATH).request().put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().map(Link::getRel).anyMatch(isEqual("describedby")), "No describedby link!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPutBinaryWithInvalidDigest() {
final Response res = target(BINARY_PATH).request().header(DIGEST, "md5=blahblah")
.put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutBinaryWithMd5Digest() {
final Response res = target(BINARY_PATH).request().header(DIGEST, "md5=BJozgIQwPzzVzSxvjQsWkA==")
.put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPutBinaryWithSha1Digest() {
final Response res = target(BINARY_PATH).request().header(DIGEST, "sha=3VWEuvPnAM6riDQJUu4TG7A4Ots=")
.put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPutBinaryToACL() {
final Response res = target(BINARY_PATH).queryParam("ext", "acl").request()
.put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NOT_ACCEPTABLE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfMatch() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-Match", "\"" + etag + "\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfMatchWeak() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-Match", "W/\"" + etag + "\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatchEtag() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-None-Match", "\"" + etag + "\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatchRdfEtag() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-None-Match", "\"" + etag + "\"")
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatchRdfWeakEtag() {
final String etag = target("").request().get().getEntityTag().getValue();
final Response res = target("").request().header("If-None-Match", "W/\"" + etag + "\"")
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatchWeakEtag() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-None-Match", "W/\"" + etag + "\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatch() {
final Response res = target(BINARY_PATH).request().header("If-None-Match", "\"foo\", \"bar\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfMatchStar() {
final Response res = target(BINARY_PATH).request().header("If-Match", "*")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfMatchMultiple() {
final String etag = target(BINARY_PATH).request().get().getEntityTag().getValue();
final Response res = target(BINARY_PATH).request().header("If-Match", "\"blah\", \"" + etag + "\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfNoneMatchStar() {
final Response res = target(BINARY_PATH).request().header("If-None-Match", "*")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutBadIfMatch() {
final Response res = target(BINARY_PATH).request().header("If-Match", "4db2c60044c906361ac212ae8684e8ad")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_BAD_REQUEST, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutIfUnmodified() {
final Response res = target(BINARY_PATH).request()
.header("If-Unmodified-Since", "Tue, 29 Aug 2017 07:14:52 GMT")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutPreconditionFailed() {
final Response res = target(BINARY_PATH).request().header("If-Match", "\"blahblahblah\"")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutPreconditionFailed2() {
final Response res = target(BINARY_PATH).request()
.header("If-Unmodified-Since", "Wed, 19 Oct 2016 10:15:00 GMT")
.put(entity("some different data.", TEXT_PLAIN_TYPE));
assertEquals(SC_PRECONDITION_FAILED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutBinaryWithSha256Digest() {
final Response res = target(BINARY_PATH).request()
.header(DIGEST, "sha-256=voCCIRTNXosNlEgQ/7IuX5dFNvFQx5MfG/jy1AKiLMU=")
.put(entity("some data.", TEXT_PLAIN_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource));
}
@Test
public void testPutSlash() {
final Response res = target(RESOURCE_PATH + "/").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPutTimeMap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.put(entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPutException() {
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().put(entity("", TEXT_TURTLE_TYPE));
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/* ******************************* *
* DELETE Tests
* ******************************* */
@Test
public void testDeleteExisting() {
final Response res = target(RESOURCE_PATH).request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testDeleteNonexistent() {
final Response res = target(NON_EXISTENT_PATH).request().delete();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteDeleted() {
final Response res = target(DELETED_PATH).request().delete();
assertEquals(SC_GONE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteVersion() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request().delete();
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testDeleteNonExistant() {
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/test");
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
when(mockMementoService.get(eq(identifier), eq(MAX))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH + "/test").request().delete();
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testDeleteWithChildren() {
when(mockVersionedResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockVersionedResource.stream(eq(LDP.PreferContainment))).thenAnswer(inv -> Stream.of(
rdf.createTriple(identifier, LDP.contains, rdf.createIRI(identifier.getIRIString() + "/child"))));
final Response res = target(RESOURCE_PATH).request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteNoChildren1() {
when(mockVersionedResource.getInteractionModel()).thenReturn(LDP.BasicContainer);
when(mockVersionedResource.stream(eq(LDP.PreferContainment))).thenAnswer(inv -> Stream.empty());
final Response res = target(RESOURCE_PATH).request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteNoChildren2() {
when(mockVersionedResource.getInteractionModel()).thenReturn(LDP.Container);
when(mockVersionedResource.stream(eq(LDP.PreferContainment))).thenAnswer(inv -> Stream.empty());
final Response res = target(RESOURCE_PATH).request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteAcl() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testDeleteTimeMap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request().delete();
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testDeleteSlash() {
final Response res = target(RESOURCE_PATH + "/").request().delete();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertFalse(getLinks(res).stream().anyMatch(hasType(LDP.Resource)), "Unexpected ldp:Resource link!");
assertFalse(getLinks(res).stream().anyMatch(hasType(LDP.RDFSource)), "Unexpected ldp:RDFSource link!");
assertFalse(getLinks(res).stream().anyMatch(hasType(LDP.Container)), "Unexpected ldp:Container link!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testDeleteException() {
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().delete();
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/* ********************* *
* PATCH tests
* ********************* */
@Test
public void testPatchVersion() {
final Response res = target(RESOURCE_PATH).queryParam("version", timestamp).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchTimeMap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchExisting() {
final Response res = target(RESOURCE_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchRoot() {
final Response res = target().request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.BasicContainer));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchMissing() {
final Response res = target(NON_EXISTENT_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchGone() {
final Response res = target(DELETED_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_GONE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchExistingIgnoreLdpType() throws IOException {
final Response res = target(RESOURCE_PATH).request()
.header("Prefer", "return=representation; include=\"" + LDP.PreferMinimalContainer.getIRIString() + "\"")
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" ;"
+ " <http://example.com/foo> <http://www.w3.org/ns/ldp#IndirectContainer> ;"
+ " a <http://example.com/Type1>, <http://www.w3.org/ns/ldp#BasicContainer> } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertFalse(entity.contains("BasicContainer"), "Unexpected BasicContainer type!");
assertTrue(entity.contains("Type1"), "Missing Type1 type!");
}
@Test
public void testPatchExistingBinary() {
final Response res = target(BINARY_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchExistingResponse() throws IOException {
final Response res = target(RESOURCE_PATH).request()
.header("Prefer", "return=representation; include=\"" + LDP.PreferMinimalContainer.getIRIString() + "\"")
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
assertTrue(entity.contains("A title"), "Incorrect title value!");
}
@Test
public void testPatchConstraint() {
final Response res = target(RESOURCE_PATH).request()
.method("PATCH", entity("INSERT { <> a \"Some literal\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(InvalidRange, LDP.constrainedBy.getIRIString())),
"Missing constrainedBy link header!");
}
@Test
public void testPatchToTimemap() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
.method("PATCH", entity("<> <http://purl.org/dc/terms/title> \"A title\" .", TEXT_TURTLE_TYPE));
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchNew() {
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + RESOURCE_PATH + "/test");
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
when(mockMementoService.get(eq(identifier), eq(MAX))).thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
final Response res = target(RESOURCE_PATH + "/test").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NOT_FOUND, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchAcl() {
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchOnDc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
final Response res = target(RESOURCE_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(InvalidCardinality, LDP.constrainedBy.getIRIString())),
"Missing constrainedBy link header!");
}
@Test
public void testPatchOnIc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
final Response res = target(RESOURCE_PATH).request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_CONFLICT, res.getStatus(), "Unexpected response code!");
assertTrue(getLinks(res).stream().anyMatch(hasLink(InvalidCardinality, LDP.constrainedBy.getIRIString())),
"Missing constrainedBy link header!");
}
@Test
public void testPatchAclOnDc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.DirectContainer);
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPatchAclOnIc() {
when(mockResource.getInteractionModel()).thenReturn(LDP.IndirectContainer);
final Response res = target(RESOURCE_PATH).queryParam("ext", "acl").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource));
}
@Test
public void testPatchInvalidContent() {
final Response res = target(RESOURCE_PATH).request().method("PATCH", entity("blah blah blah", "invalid/type"));
assertEquals(SC_UNSUPPORTED_MEDIA_TYPE, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchSlash() {
final Response res = target(RESOURCE_PATH + "/").request()
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!");
}
@Test
public void testPatchNotAcceptable() {
final Response res = target(RESOURCE_PATH).request().accept("text/foo")
.method("PATCH", entity("INSERT { <> <http://purl.org/dc/terms/title> \"A title\" } WHERE {}",
APPLICATION_SPARQL_UPDATE));
assertEquals(SC_NOT_ACCEPTABLE, res.getStatus(), "Unexpected response code!");
}
@Test
public void testPatchException() {
when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> supplyAsync(() -> {
throw new RuntimeTrellisException("Expected exception");
}));
final Response res = target(RESOURCE_PATH).request().method("PATCH", entity("", APPLICATION_SPARQL_UPDATE));
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
/**
* Some other method
*/
@Test
public void testOtherMethod() {
final Response res = target(RESOURCE_PATH).request().method("FOO");
assertEquals(SC_METHOD_NOT_ALLOWED, res.getStatus(), "Unexpected response code!");
}
/* ************************************ *
* Test cache control headers
* ************************************ */
@Test
public void testCacheControl() {
final Response res = target(RESOURCE_PATH).request().get();
assertEquals(SC_OK, res.getStatus(), "Unexpected response code!");
assertNotNull(res.getHeaderString(CACHE_CONTROL), "Missing Cache-Control header!");
assertTrue(res.getHeaderString(CACHE_CONTROL).contains("max-age="), "Incorrect Cache-Control: max-age value!");
}
@Test
public void testCacheControlOptions() {
final Response res = target(RESOURCE_PATH).request().options();
assertEquals(SC_NO_CONTENT, res.getStatus(), "Unexpected response code!");
assertNull(res.getHeaderString(CACHE_CONTROL), "Unexpected Cache-Control header!");
}
protected static List<Link> getLinks(final Response res) {
// Jersey's client doesn't parse complex link headers correctly
return ofNullable(res.getStringHeaders().get(LINK)).orElseGet(Collections::emptyList)
.stream().map(Link::valueOf).collect(toList());
}
private boolean hasTimeGateLink(final Response res, final String path) {
return getLinks(res).stream().anyMatch(l ->
l.getRel().contains("timegate") && l.getUri().toString().equals(getBaseUrl() + path));
}
private boolean hasOriginalLink(final Response res, final String path) {
return getLinks(res).stream().anyMatch(l ->
l.getRel().contains("original") && l.getUri().toString().equals(getBaseUrl() + path));
}
protected static Predicate<Link> hasLink(final IRI iri, final String rel) {
return link -> rel.equals(link.getRel()) && iri.getIRIString().equals(link.getUri().toString());
}
protected static Predicate<Link> hasType(final IRI iri) {
return hasLink(iri, "type");
}
private Stream<Quad> getLdfQuads() {
return Stream.of(
rdf.createQuad(PreferUserManaged, identifier, DC.creator, rdf.createLiteral("User")),
rdf.createQuad(PreferUserManaged, rdf.createIRI("ex:foo"), DC.title, rdf.createIRI("ex:title")),
rdf.createQuad(PreferUserManaged, identifier, DC.title, rdf.createLiteral("A title")),
rdf.createQuad(PreferUserManaged, identifier, DC.title, rdf.createLiteral("Other title")),
rdf.createQuad(PreferUserManaged, identifier, type, rdf.createIRI("ex:Type")),
rdf.createQuad(PreferUserManaged, rdf.createIRI("ex:foo"), type, rdf.createIRI("ex:Type")),
rdf.createQuad(PreferUserManaged, rdf.createIRI("ex:foo"), type, rdf.createIRI("ex:Other")),
rdf.createQuad(PreferServerManaged, identifier, DC.created,
rdf.createLiteral("2017-04-01T10:15:00Z", XSD.dateTime)),
rdf.createQuad(PreferAccessControl, identifier, type, ACL.Authorization),
rdf.createQuad(PreferAccessControl, identifier, ACL.mode, ACL.Control));
}
private Stream<Quad> getPreferQuads() {
return Stream.of(
rdf.createQuad(PreferUserManaged, identifier, DC.title, rdf.createLiteral("A title")),
rdf.createQuad(PreferServerManaged, identifier, DC.created,
rdf.createLiteral("2017-04-01T10:15:00Z", XSD.dateTime)),
rdf.createQuad(LDP.PreferContainment, identifier, LDP.contains,
rdf.createIRI("trellis:data/resource/child1")),
rdf.createQuad(LDP.PreferContainment, identifier, LDP.contains,
rdf.createIRI("trellis:data/resource/child2")),
rdf.createQuad(LDP.PreferContainment, identifier, LDP.contains,
rdf.createIRI("trellis:data/resource/child3")),
rdf.createQuad(LDP.PreferMembership, identifier, LDP.member,
rdf.createIRI("trellis:data/resource/other")),
rdf.createQuad(PreferAccessControl, identifier, type, ACL.Authorization),
rdf.createQuad(PreferAccessControl, identifier, type, ACL.Authorization),
rdf.createQuad(PreferAccessControl, identifier, ACL.mode, ACL.Control));
}
private Stream<Executable> checkVary(final Response res, final List<String> vary) {
final List<String> vheaders = res.getStringHeaders().get(VARY);
return Stream.of(RANGE, WANT_DIGEST, ACCEPT_DATETIME, PREFER).map(header -> vary.contains(header)
? () -> assertTrue(vheaders.contains(header), "Missing Vary header: " + header)
: () -> assertFalse(vheaders.contains(header), "Unexpected Vary header: " + header));
}
private Stream<Executable> checkLdTemplateHeaders(final Response res) {
final List<String> templates = res.getStringHeaders().get(LINK_TEMPLATE);
return Stream.of(
() -> assertEquals(2L, templates.size(), "Incorrect Link-Template header count!"),
() -> assertTrue(templates.contains("<" + getBaseUrl() + RESOURCE_PATH
+ "{?subject,predicate,object}>; rel=\"" + LDP.RDFSource.getIRIString() + "\""),
"Template for Linked Data Fragments not found!"),
() -> assertTrue(templates.contains("<" + getBaseUrl() + RESOURCE_PATH
+ "{?version}>; rel=\"" + Memento.Memento.getIRIString() + "\""),
"Template for Memento queries not found!"));
}
private static Stream<IRI> ldpResourceSupertypes(final IRI ldpType) {
return Stream.of(ldpType).filter(t -> nonNull(LDP.getSuperclassOf(t)) || LDP.Resource.equals(t))
.flatMap(t -> Stream.concat(ldpResourceSupertypes(LDP.getSuperclassOf(t)), Stream.of(t)));
}
private Stream<Executable> checkLdpTypeHeaders(final Response res, final IRI ldpType) {
final Set<String> subTypes = ldpResourceSupertypes(ldpType).map(IRI::getIRIString).collect(toSet());
final Set<String> responseTypes = getLinks(res).stream().filter(link -> "type".equals(link.getRel()))
.map(link -> link.getUri().toString()).collect(toSet());
return Stream.concat(
subTypes.stream().map(t -> () -> assertTrue(responseTypes.contains(t),
"Response type doesn't contain LDP subtype: " + t)),
responseTypes.stream().map(t -> () -> assertTrue(subTypes.contains(t),
"Subtype " + t + " not present in response type for: " + t)));
}
private Stream<Executable> checkMementoHeaders(final Response res, final String path) {
final List<Link> links = getLinks(res);
return Stream.of(
() -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
.equals(l.getParams().get("datetime")) &&
l.getUri().toString().equals(getBaseUrl() + path + "?version=1496260729")),
"Missing expected first rel=memento Link!"),
() -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 1000))
.equals(l.getParams().get("datetime")) &&
l.getUri().toString().equals(getBaseUrl() + path + "?version=1496261729")),
"Missing expected second rel=memento Link!"),
() -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
RFC_1123_DATE_TIME.withZone(UTC).format(time).equals(l.getParams().get("datetime")) &&
l.getUri().toString().equals(getBaseUrl() + path + "?version=1496262729")),
"Missing expected third rel=memento Link!"),
() -> assertTrue(links.stream().anyMatch(l -> l.getRels().contains("timemap") &&
RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
.equals(l.getParams().get("from")) &&
RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp))
.equals(l.getParams().get("until")) &&
APPLICATION_LINK_FORMAT.equals(l.getType()) &&
l.getUri().toString().equals(getBaseUrl() + path + "?ext=timemap")), "Missing valid timemap link!"),
() -> assertTrue(hasTimeGateLink(res, path), "No rel=timegate Link!"),
() -> assertTrue(hasOriginalLink(res, path), "No rel=original Link!"));
}
private Stream<Executable> checkBinaryResponse(final Response res) {
return Stream.of(
() -> assertTrue(res.getMediaType().isCompatible(TEXT_PLAIN_TYPE), "Incompatible content-type!"),
() -> assertNotNull(res.getHeaderString(ACCEPT_RANGES), "Missing Accept-Ranges header!"),
() -> assertNull(res.getHeaderString(MEMENTO_DATETIME), "Unexpected Memento-Datetime header!"),
() -> assertAll("Check Vary header", checkVary(res, asList(RANGE, WANT_DIGEST, ACCEPT_DATETIME))),
() -> assertAll("Check allowed methods",
checkAllowedMethods(res, asList(PUT, DELETE, GET, HEAD, OPTIONS))),
() -> assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.NonRDFSource)));
}
private Stream<Executable> checkJsonLdResponse(final Response res) {
return Stream.of(
() -> assertTrue(APPLICATION_LD_JSON_TYPE.isCompatible(res.getMediaType()),
"Incorrect JSON-LD content-type!"),
() -> assertTrue(res.getMediaType().isCompatible(APPLICATION_LD_JSON_TYPE),
"Incompatible JSON-LD content-type!"),
() -> assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(HUB), "hub")),
"Missing rel=hub Link header!"),
() -> assertTrue(getLinks(res).stream().anyMatch(hasLink(rdf.createIRI(getBaseUrl() + RESOURCE_PATH),
"self")), "Missing rel=self Link header!"),
() -> assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH),
"Incorrect Accept-Patch header!"),
() -> assertTrue(res.hasEntity(), "Missing JSON-LD entity!"));
}
private Stream<Executable> checkNullHeaders(final Response res, final List<String> headers) {
return headers.stream().map(h -> () -> assertNull(res.getHeaderString(h), "Unexpected header: " + h));
}
private Stream<Executable> checkJsonStructure(final Map<String, Object> obj, final List<String> include,
final List<String> omit) {
return Stream.concat(
include.stream().map(key ->
() -> assertTrue(obj.containsKey(key), "JSON-LD didn't contain expected key: " + key)),
omit.stream().map(key ->
() -> assertFalse(obj.containsKey(key), "JSON-LD caontained extraneous key: " + key)));
}
private Stream<Executable> checkSimpleJsonLdResponse(final Response res, final IRI ldpType) {
return Stream.of(
() -> assertTrue(APPLICATION_LD_JSON_TYPE.isCompatible(res.getMediaType()),
"Incompatible JSON-LD content-type: " + res.getMediaType()),
() -> assertTrue(res.getMediaType().isCompatible(APPLICATION_LD_JSON_TYPE),
"Incorrect JSON-LD content-type: " + res.getMediaType()),
() -> assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, ldpType)));
}
private Stream<Executable> checkLdfResponse(final Response res) {
return Stream.of(
() -> assertEquals(from(time), res.getLastModified(), "Incorrect modification date!"),
() -> assertTrue(hasTimeGateLink(res, RESOURCE_PATH), "Missing rel=timegate link!"),
() -> assertTrue(hasOriginalLink(res, RESOURCE_PATH), "Missing rel=original link!"),
() -> assertAll("Check allowed methods",
checkAllowedMethods(res, asList(PATCH, PUT, DELETE, GET, HEAD, OPTIONS))),
() -> assertAll("Check Vary header", checkVary(res, asList(ACCEPT_DATETIME, PREFER))),
() -> assertAll("Check null headers", checkNullHeaders(res, asList(ACCEPT_POST, ACCEPT_RANGES))),
() -> assertAll("Check json-ld response", checkJsonLdResponse(res)),
() -> assertAll("Check LDP type Link headers", checkLdpTypeHeaders(res, LDP.RDFSource)));
}
private Stream<Executable> checkAllowedMethods(final Response res, final List<String> expected) {
final Set<String> actual = res.getAllowedMethods();
return Stream.concat(
actual.stream().map(method -> () -> assertTrue(expected.contains(method), "Method " + method
+ " was not present in the list of expected methods!")),
expected.stream().map(method -> () -> assertTrue(actual.contains(method), "Method " + method
+ " was not in the response header!")));
}
}
|
atum-martin/atum-jvcp | atum-jvcp/src/main/java/org/atum/jvcp/net/codec/cccam/io/CCcamPacketSender.java | package org.atum.jvcp.net.codec.cccam.io;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.apache.log4j.Logger;
import org.atum.jvcp.model.Card;
import org.atum.jvcp.model.EcmRequest;
import org.atum.jvcp.model.PacketSenderInterface;
import org.atum.jvcp.net.codec.NetUtils;
import org.atum.jvcp.net.codec.cccam.CCcamBuilds;
import org.atum.jvcp.net.codec.cccam.CCcamConstants;
import org.atum.jvcp.net.codec.cccam.CCcamPacket;
import org.atum.jvcp.net.codec.cccam.CCcamSession;
import org.atum.jvcp.net.codec.cccam.CCcamBuilds.CCcamBuild;
import org.atum.jvcp.net.codec.cccam.CCcamCipher;
/**
* @author <a href="https://github.com/atum-martin">atum-martin</a>
* @since 23 Nov 2016 00:05:46
*/
public class CCcamPacketSender implements PacketSenderInterface {
private CCcamSession session;
private Logger logger = Logger.getLogger(CCcamSession.class);
public CCcamPacketSender(CCcamSession session) {
this.session = session;
}
public void writeCard(Card card) {
int size = 22 + (7 * card.getProviders().length) + ( 8 * 1/*card.getNodeCount()*/);
ByteBuf out = Unpooled.buffer(size);
out.writeInt(card.getShare());
out.writeInt((int) card.getNodeId());
out.writeShort(card.getCardId());
out.writeByte(card.getHops());
out.writeByte(card.getReshare());
out.writeLong(card.getSerial());
out.writeByte(card.getProviders().length);
for (int prov : card.getProviders()) {
NetUtils.putTriByte(out, prov);
out.writeInt(0);
}
//node count
out.writeByte(1);
out.writeLong(card.getNodeId());
session.write(new CCcamPacket(CCcamConstants.MSG_NEW_CARD, out));
}
public void writeSrvData() {
ByteBuf out = Unpooled.buffer(72);
out.writeBytes(session.getServer().getNodeId());
CCcamBuild build = CCcamBuilds.getBuild("2.0.11");
NetUtils.writeCCcamStr(out, build.getVersion(), 32);
NetUtils.writeCCcamStr(out, "" + build.getBuildNum(), 32);
session.write(new CCcamPacket(CCcamConstants.MSG_SRV_DATA, out));
logger.info("MSG_SRV_DATA: " + build.getVersion() + " " + build.getBuildNum());
session.write(new CCcamPacket(CCcamConstants.MSG_CACHE_FILTER, Unpooled.buffer(482)));
}
public void writeCliData() {
// session.write(new CCcamPacket(CCcamConstants.MSG_CLI_DATA,null));
ByteBuf out = Unpooled.buffer(93);
NetUtils.writeCCcamStr(out, "user99", 20);
out.writeBytes(session.getServer().getNodeId());
out.writeByte(0);
CCcamBuild build = CCcamBuilds.getBuild("2.0.11");
NetUtils.writeCCcamStr(out, build.getVersion(), 32);
NetUtils.writeCCcamStr(out, "" + build.getBuildNum(), 32);
logger.info("sending MSG_CLI_DATA: " + build.getVersion() + " " + build.getBuildNum());
session.write(new CCcamPacket(CCcamConstants.MSG_CLI_DATA, out));
}
public void writeKeepAlive() {
session.write(new CCcamPacket(CCcamConstants.MSG_KEEPALIVE, null));
}
public void writeEcmRequest(EcmRequest req) {
ByteBuf out = Unpooled.buffer(req.getEcm().length + 13);
out.writeShort(req.getCardId());
out.writeInt(req.getProv());
out.writeInt(req.getShareId());
out.writeShort(req.getServiceId());
out.writeByte(req.getEcm().length);
out.writeBytes(req.getEcm());
session.write(new CCcamPacket(CCcamConstants.MSG_CW_ECM, out));
}
public void writeEcmAnswer(byte[] dcw) {
final byte[] sendDcw = new byte[dcw.length];
System.arraycopy(dcw, 0, sendDcw, 0, dcw.length);
ByteBuf out = Unpooled.buffer(16);
CCcamCipher.cc_crypt_cw(
session.getNodeId(),
//session.getServer().getNodeId(),
session.getLastRequest().getShareId(),
sendDcw);
out.writeBytes(sendDcw);
final byte[] sendDcw2 = new byte[dcw.length];
System.arraycopy(sendDcw, 0, sendDcw2, 0, dcw.length);
session.write(new CCcamPacket(CCcamConstants.MSG_CW_ECM, out)).addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
session.getEncrypter().encrypt(sendDcw2, 16);
}
});
}
public void writeEcmCachePush(EcmRequest ecm){
if(ecm.getCachePushBuffer() == null){
ByteBuf out = Unpooled.buffer(65+(ecm.getCacheNodeCount()*4));
out.writeShort(ecm.getCardId());
out.writeInt(ecm.getProv());
out.writeInt(0);
out.writeShort(ecm.getServiceId());
out.writeShort(ecm.getEcmLength());
out.writeByte(3);
out.writeByte(0);
out.writeByte(0);
out.writeByte(0);
//cycle time
out.writeByte(0);
out.writeByte(ecm.getEcm()[0]);
out.writeBytes(ecm.getEcmMD5());
out.writeInt(ecm.getCspHash());
out.writeBytes(ecm.getDcw());
out.writeByte(ecm.getCacheNodeCount()+1);
out.writeBytes(session.getServer().getNodeId());
for(int i = 0; i < ecm.getCacheNodeCount(); i++){
out.writeLong(0);
}
ecm.setCachePushBuffer(out);
}
session.write(new CCcamPacket(CCcamConstants.MSG_CACHE_PUSH, ecm.getCachePushBuffer()));
}
/* (non-Javadoc)
* @see org.atum.jvcp.model.PacketSenderInterface#writeFailedEcm()
*/
public void writeFailedEcm() {
// TODO Auto-generated method stub
}
}
|
sullis/mockserver | mockserver-core/src/main/java/org/mockserver/model/Not.java | package org.mockserver.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Objects;
/**
* @author jamesdbloom
*/
public class Not extends ObjectWithJsonToString {
private int hashCode;
Boolean not;
public static <T extends Not> T not(T t) {
t.not = true;
return t;
}
public static <T extends Not> T not(T t, Boolean not) {
if (not != null && not) {
t.not = true;
}
return t;
}
@JsonIgnore
public boolean isNot() {
return not != null && not;
}
public Boolean getNot() {
return not;
}
public void setNot(Boolean not) {
this.not = not;
this.hashCode = 0;
}
public Not withNot(Boolean not) {
this.not = not;
this.hashCode = 0;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (hashCode() != o.hashCode()) {
return false;
}
Not not1 = (Not) o;
return Objects.equals(not, not1.not);
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(not);
}
return hashCode;
}
}
|
stetre/moonfonts | src/fonts/stb_font_times_bold_14_latin1.inl | // Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_times_bold_14_latin1_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_times_bold_14_latin1'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_times_bold_14_latin1_BITMAP_WIDTH 256
#define STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT 70
#define STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT_POW2 128
#define STB_FONT_times_bold_14_latin1_FIRST_CHAR 32
#define STB_FONT_times_bold_14_latin1_NUM_CHARS 224
#define STB_FONT_times_bold_14_latin1_LINE_SPACING 9
static unsigned int stb__times_bold_14_latin1_pixels[]={
0x06200260,0x02200130,0x09800620,0x4a80a310,0x80401654,0x6d404aac,
0x2aaa603b,0x1bba8012,0x1a9804c0,0x20298551,0x8800aa98,0x0702a601,
0x35063751,0x03100188,0x204c40c4,0x7cc03029,0x5c04e800,0x00ff8806,
0x7d4007cc,0x01f3d706,0x809f10ba,0x07539019,0xf982ecb8,0x44144b7f,
0x00de99ed,0xd71720b9,0x215907c8,0x82ec02b8,0x9160f89c,0x6c7d515d,
0xf803e882,0x360bfa02,0x1fe45a84,0x048801c8,0xa9c80370,0xd803a803,
0x802102b8,0x2d409f01,0x98035530,0x7ffe81aa,0x07ec4b89,0x406407f3,
0x02235c5c,0xb014c032,0x960c9fc0,0x5f1cc1fc,0x07501220,0x8582c5dc,
0x0363267a,0x55303553,0x54c6aa15,0x303550aa,0xaa980555,0x70aaa981,
0x2cd3ae35,0xbf1669d7,0x882d85d9,0x40dd89ed,0x0dd89ed8,0x2225fffe,
0xdf11fe67,0x5c5c80c0,0x2191b626,0x4093cbc8,0x5613ee01,0x1f4107f8,
0x15555553,0x2aaaaaa6,0x77555530,0xb82aaa61,0x446aaa67,0x40dd89ed,
0x3f62c3fd,0x27b622c3,0x76c40dd8,0x7ec0dd89,0x22df12c3,0x2145be22,
0xf10fc8ef,0x7cc1fb03,0x7f307ec3,0x444bffec,0xfd0bf71f,0x17203a03,
0xd247c8d7,0xe80a5f37,0x41bf9700,0x5d00bf55,0x1e99bfc8,0x87a66ff2,
0x21e99bfc,0x323543fc,0xf983f63f,0x90e17e43,0x07ec385f,0x20fd87f3,
0x217e43f9,0x5c14fdc3,0xf74f829f,0xff307ea5,0x43fccdf0,0x25ffa26f,
0xf86f9a7c,0xc84fa80f,0x99f235c5,0x21f71f73,0xb309f502,0x1bea0fe6,
0x27f90750,0x44ff2198,0x4c4ff219,0x8ae0ff21,0xf0ff33fc,0x21c2fc8d,
0xff31c2fc,0x43fccdf0,0x0e17e46f,0xbf105bf1,0x4bea9f05,0x42fd41fa,
0xd0bf51fe,0xf095883f,0xdf307fc9,0x1721ff20,0x46a7c8d7,0xc814dd6e,
0x952f987f,0x3a80ff10,0xc838bfc8,0xbfc838bf,0xb83fc838,0x2fd4ff22,
0x85f90ff4,0xa8e17e43,0xf51fe85f,0x7e43fd0b,0x807ec1c2,0xf75f80fd,
0x1be60fc3,0x437cc3fe,0x889480ff,0xfb8bee1f,0x43fc9982,0x9f235c5c,
0x29f5bf29,0x3fc9980a,0x920bcfd8,0x5d0cc3fb,0xc83edfc8,0xdfc83edf,
0x543fc83e,0x6f99fe46,0x0bf20ff8,0x31c2fc87,0x261ff0df,0x320ff86f,
0x02cc1c2f,0x3b3be0b3,0x07f416c3,0xf81fd1be,0x0f312906,0x203b77b3,
0x45c8df33,0x64e3e46b,0x098adc8e,0xf706f99c,0x5ef5c58b,0x3f21fc2c,
0xabfc83ab,0x83abfc83,0x3235c3fc,0xdf03fa3f,0x2e1c2fb8,0x03fa1c2f,
0x7c0fe8df,0x40e17dc6,0x14f81402,0x45f70b50,0x517dc2fa,0x2e25205f,
0x440bf604,0x322feaac,0x51f235c5,0x3220c403,0x4542feaa,0x1dc161f9,
0x29fe42f8,0x4329fe43,0xfc8653fc,0x8ff23d43,0x50bea2fb,0x3ea1449f,
0x45f70a24,0x517dc2fa,0x224fa85f,0x6dc0b6e2,0x9809f102,0x2ebbeb81,
0x05d77d70,0x100a24a4,0x544857fb,0x2d91725f,0x42a86cd9,0x7d448298,
0x160e96c5,0x642d82d4,0x3fc9223f,0x223fc922,0x8b50ff24,0x5df5c3fc,
0x779f902e,0x40ef3f20,0x702ebbeb,0x3205d77d,0x0e4c3bcf,0xbd501c98,
0x02200803,0x39c00440,0x20988002,0x4ffea1fa,0x5c5532a9,0x3555100b,
0xffa87ea0,0x0906ee23,0xd11a8031,0x229fb7df,0x14fdbefe,0x29fb7dfd,
0x8510dfe8,0x0880dfe8,0x00200100,0x00880044,0x00000010,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0xdc808000,0x0260382a,0x200ec6c4,0x22062009,0x46cc1d8d,0x02cdd40d,
0xacc80371,0x2a00c982,0x4a05d504,0x2980c982,0x0dc81844,0x2ea01150,
0x70289981,0x4c28e017,0x2039100c,0xb105102c,0x20311309,0xa8050ab9,
0x406ed4c0,0x2201d505,0x27dc03b5,0x36b109b0,0x540dacc1,0x01ce058b,
0x3201bb73,0x5f407a03,0x82f8fa86,0x6c0fe83c,0x42674c0d,0xd5c86feb,
0x507add8b,0x41cda051,0x2609703d,0x3ccac80e,0x97d07732,0xbb11bb0d,
0x2aa63803,0x90586aa0,0x21555301,0x646c41aa,0x80c04880,0x5530aaa9,
0x73015555,0x03003005,0x0310980c,0x7d818021,0x28a16c54,0x6d7e0108,
0x81d40207,0x40605758,0x3ea02201,0x08514738,0x7d41fb02,0xfd8b9504,
0x555562c6,0x3fd8aa62,0x5302302c,0x403a0155,0x4dfe43fc,0x001d01e9,
0x8f2e201d,0x266d8ce9,0x3a66d8ce,0x6dd46d8c,0x32e22e44,0x2136ea1f,
0x8cf84dba,0x426dd42d,0x7f644dba,0x0ddcc6fe,0xb7506ee6,0x983ef989,
0x0ddcc1bb,0x7fd4cdf1,0x717de640,0xe961c9fd,0x5f906c3f,0x6403a038,
0x209f503f,0x89fe43fc,0x404fa819,0x3e5f04fa,0x3e3ed7e2,0xfb5f8fb5,
0x50fd4fc4,0x9fc57c47,0x221fa9f8,0x67c1fa9f,0x2a7e25c8,0x3ea7e21f,
0x9f858dc1,0x134cfc69,0xfc83f53f,0x234cfc2f,0x57ea699f,0xbf83fd38,
0x97fc5c0a,0x44df52c3,0x40e17e42,0x07f904fa,0x1fe41ff2,0xc80e2ff2,
0x43fe407f,0xafcbf1fa,0x47dafc7d,0xc8b8fb5f,0x1fa8a22f,0x17e45cbf,
0x9f0bf22e,0xfc8b87ea,0x117e45c2,0x7cc3d35b,0xb9f30fdc,0x17e45c1f,
0xcf997fd4,0xfb9f30fd,0xff1d7ea1,0x9c077c43,0x22c39ff9,0x5f9073fd,
0x20ff9038,0xfc9983fc,0x7e43fc83,0xf93303ed,0x0ff26607,0x5f97e3f5,
0x8fb5f8fb,0xaca8fb5f,0x7c7ee02f,0x50beb2a5,0x54f85f59,0x17d6545f,
0xfb8beb2a,0x0bea4ddc,0x56540bea,0x56ec822f,0x105f505f,0xe87f87df,
0xdf71c10f,0x57fcc587,0x41c2fc81,0xfc83fc99,0x90df3383,0x3abfc87f,
0x9c1be670,0xf97c46f9,0x3e3f57e3,0xfd5f8fd5,0x717dd7cc,0x33f97cc9,
0x7cc5f75f,0x4e7c2fba,0xf75f30fa,0x17dd7cc5,0xbf10aeb1,0x08afc422,
0x545f75f3,0x57e29970,0x822bf108,0x20bea2fb,0x321c5ffa,0x27e42c5f,
0x9c1c2fb8,0x43fc86f9,0x42feaac8,0x29fe43fc,0x7f556443,0x7f556442,
0x321de542,0x3f21fecf,0x33f21fec,0xf5bf31fe,0x2f2e3ec9,0x93eb7e65,
0x264fadf9,0x3e64cccf,0x37e64fad,0x06ce64fa,0x3aa17754,0x3eb7e62e,
0x8336fa64,0x77542eea,0x6dd75dc2,0x20e02501,0x27dc2c5e,0x10a24fa8,
0xc85fd559,0x17ea243f,0x23fc87f9,0x8bf51248,0x0082fd44,0x00400801,
0x00004000,0x20000000,0x00000108,0x00005300,0x02801104,0x2c4885d3,
0x9f9027dc,0x5fa89077,0x43f51fe4,0xbfd13ffa,0x36fbfa21,0x7d43f54f,
0x7d43f53f,0x0000003f,0x00000000,0x00000000,0x00000000,0x00000000,
0x22400004,0x0401dfd8,0x3fea1fa8,0x001bfd13,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x80000000,
0x8298002c,0x41c0cc0b,0x1980b819,0x05cc0288,0x03720b20,0x30115062,
0x42899815,0x03500aa8,0x2a6026e6,0xa98aaaa0,0x40157302,0x43102aaa,
0x7302aaaa,0x8054c015,0x4418acb9,0x2aaa60b9,0x75103550,0x06aa6063,
0x07540d50,0x44498f31,0x3621543d,0x65e424c3,0x75b006c4,0x26074c0d,
0x2e1c84ce,0x34de46fe,0x75d1eb76,0x17c7441d,0x3b63d476,0xb03fe26f,
0x5712c883,0x987fff50,0x3fffe21e,0x2b896445,0x6c43f2e8,0x968bd31e,
0x161fec3f,0x8faa2bb2,0x0dd89ed8,0x40ea8060,0x23c82c5b,0x05879058,
0x015cf77f,0x440d33f1,0x1160a280,0x7f15f102,0xf89fa820,0xf10e5ee4,
0x3f211243,0x9070ff20,0x855177d5,0x07cc199c,0x90b26aea,0x45575751,
0x7e49b3f9,0x33f12c41,0x0e17e47f,0x363983f9,0xd30fe60f,0xd800db19,
0xd8f20391,0x80e47900,0x80915cbe,0x7100bdf8,0x43cb8879,0x51e5c448,
0xcb893e5f,0x92fcbee3,0x07ff101f,0x53fc43c8,0xb91f1981,0xf82cf892,
0x3307401d,0x3e2494b5,0x0ff31eaf,0xf90fdc02,0x41fe2385,0x0df0ff30,
0x2141f6bf,0x104932bc,0x102751bd,0x204931bd,0x801b0bb9,0x43f52fea,
0xf97c5f2f,0x3e5f06e2,0xf97e5f72,0x7cfe65f2,0x707dff95,0xbf903dff,
0x7072fd81,0x2a3975fc,0x9f30ffff,0x38b303f9,0xffa8707b,0xb0017ea4,
0x51c2fc83,0x85fa80bf,0x7dafc1fe,0xb52c01c8,0x02765620,0x4ae02d4b,
0x22b60dbc,0x3ea2a8ff,0x7c7eabf1,0x3e3f5165,0x557e5f75,0x675cbf1f,
0x017f513f,0xb103ffa6,0x19ef985f,0x21f5f0b8,0xf73fc983,0x85709f15,
0x64384c8b,0x4df53ffc,0x0cc1ccb8,0xfa8e17e4,0x7c37cc06,0x47dafc0f,
0xc98e406d,0x82d41b05,0x440b931c,0x267d3f14,0xa89df53f,0x47eabf1f,
0x1fa8915f,0xa7cbeabf,0xf70bf1fa,0x20a81f81,0x82f882fb,0xf15304fe,
0x5d8129b3,0x3a1be5f5,0x4cf4d4c0,0x7cc7d491,0x5f98ff15,0x470bee00,
0x0fe807f8,0x7eafc37c,0x261753e2,0xa81d9b14,0x8a4c0643,0x21b00ecd,
0xdf34e9f9,0x44a7bf61,0x4be27f2f,0x2f88573f,0x97c57c7f,0xe887f2f8,
0x92f3f6a1,0x21987c4a,0x5c03f506,0x20c9889a,0x9fc4aa28,0x1b82cc4e,
0x0fa83213,0xf317dc7d,0x9f50790b,0x30fee144,0x5f517dc3,0x43fd9f90,
0x22583b5f,0x71620eca,0x6544b0bb,0x56c2b80e,0x2b7ff21e,0x2f2a1ffc,
0x0b1de543,0x9b50ef2a,0x223bca89,0x7eddc1ba,0x2eb3aa2f,0x80673ee3,
0xcbbcb805,0x215f7cc0,0x03b85aea,0x2032ef2e,0x7540dabc,0x5e82ecab,
0x20779f90,0xb82cbdeb,0x0202ebbe,0x0c41bb88,0x33026044,0x00881883,
0x04080605,0x00204010,0x00100401,0x20080208,0x00400000,0x00402004,
0x31000008,0x20010000,0x00088008,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0xa8000000,0x0aaa89aa,
0x006a6353,0xaa98aa60,0x501c6aa0,0x2e1c0555,0x206aaa65,0x401532aa,
0x1aaaaaaa,0x98500ba8,0x30aaaaaa,0x41555555,0xcea8b93e,0x2aaa62ec,
0x8aaa9809,0x5530aaa9,0xa986a615,0x350e4c02,0x7950154c,0x4c5510dd,
0xb5100aaa,0x985554c7,0x3e2b71aa,0x248bf70f,0x40d904f8,0x9637ec7d,
0x403fe00c,0x3f236c7b,0x8fea4fab,0x4f7ec405,0x37ff43c9,0x7f903faa,
0x67e43d33,0x6d3e2d99,0x7e477c46,0x3ba6ff60,0x7f91fe40,0x13e23fc8,
0x7c3c80bf,0xaf982fc4,0x3cfd41f9,0xaaf80bf2,0x87a1fe47,0xff8bf66d,
0x904f8510,0x3ae3ec0d,0x202a8e4f,0x00fd307f,0xf83fa5f7,0xf9b80336,
0xe8a98a16,0x3207ec1f,0x7dc3313f,0xdb4f8a23,0xc8bee9f0,0xfc8df12f,
0x7f90bf23,0x202fc4f8,0x82fc0981,0x6c2f89fa,0x855bf907,0x3fb811f9,
0x5f980191,0x6fc14ffa,0x66d402eb,0x97fc5c7d,0x10ff02c3,0x5f700f97,
0x39fc83fa,0x3b7c54c0,0x07e43dc0,0x2e0e2ff2,0x369f073f,0x45f54f86,
0xc87fa2fc,0xf90bf23f,0xbafc4f87,0xea8faa1d,0x11766fc3,0x7541d79b,
0xf9afc83f,0x7dc0bea5,0x3fa0049b,0xf076fa99,0x11443f2b,0x2671fa7f,
0x806c39ff,0xc8f9387f,0x17e67dc4,0x2700f3e6,0x6c05cff8,0x7e40fc84,
0xddfb83ed,0x0feafc45,0xb51fbafc,0x47f9159f,0x2feccdfc,0xf13e1fe4,
0xf13e02eb,0x47d8ef89,0x20fb009b,0x221fd2fc,0x6fdc116f,0xfb8b705f,
0xf037fd3c,0x51ccbea9,0x5c71f65f,0xf81543ef,0x0fecd547,0x05fdc1fd,
0x055ff554,0x477dd554,0x7e41a204,0x41d5fe40,0x7c459bfb,0x77c3fccf,
0xb17e43ec,0xf91fe47f,0x27c3fc85,0x27c0f37e,0x9f6bf13e,0x6c1bccf9,
0x3fa5f907,0xf70ffaa0,0x8db09fd7,0x0df72ff8,0x5b97d53e,0x0e3ecbea,
0x26488bf9,0xfffc8ff2,0x0bee1c6f,0x40cfeccc,0x095be228,0x0fc810c8,
0x5c329fe4,0x20c9853f,0xf9014f80,0x7f90ffc5,0x0ff217e4,0x0fdef89f,
0x3e27c4f8,0xfeed8f95,0xcfc83ec6,0xb82b82ec,0x002ff8bf,0xf81fc4f9,
0x89f61f75,0xe838fb3f,0x37db6585,0x987f6662,0x99817dc1,0x444819fe,
0x3372246f,0x3207ec3c,0x3fb9223f,0x4f880d50,0x2fccbf20,0x42fc8ff2,
0x3e2fc3fc,0x45f86f8d,0x27dafc5f,0x0fb1a24a,0x0b500ff2,0x07fe67f7,
0x20190e60,0x3fa2dade,0x4bfb3ae0,0x5c2442e9,0x403f7931,0x6fec407c,
0x907ff300,0x2ffee21b,0x3ffea5eb,0x42ffa62f,0x4fdbefe8,0x7301bfb1,
0x881dea80,0x443ecdfe,0xdfe98dfd,0x2a1bfd10,0x91df30ef,0xa877d49f,
0xd1df30ef,0x055ddc3f,0xfe983fd1,0x8813100c,0xffe88dfd,0x08008002,
0x001083a8,0x00008100,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x70000000,0x80aaa987,0xaaa81aa9,
0x81669d71,0xa993a201,0x99409aaa,0x2aaaaaa0,0xa98aaaa1,0x2a155532,
0x26aaa61a,0x2f220a00,0x4c11985b,0x32aaaaaa,0x00135555,0x4cccc1c0,
0x2a070199,0x543bcbda,0x2ca883db,0x9d70ddc4,0x00951db1,0x4003bb88,
0x207445bc,0x3ff203fc,0xf893fa20,0x80740516,0x2ff20ecc,0xb5f10ee9,
0x7fc45749,0x8361ff40,0x360ee5fd,0x5c0de9bf,0x47da7445,0x2ee0ffd9,
0x3669afe9,0x881fd9af,0x18683ccb,0x3e216010,0x223d4f99,0x4fc1fa9f,
0x134cf47a,0x8263f6bf,0x7c5bdcbc,0x407325f2,0x0440a8ea,0xfcb80bf2,
0xf70feea3,0x827d4053,0xf72fc8a2,0x3f628047,0x0a26fa83,0x20913ff1,
0x54df12fc,0x6cbea4ef,0xb1408847,0x32fc8a3f,0x0fe7f0bf,0x5804061a,
0xb59f7170,0x30fe45c7,0xcbf9821f,0x3ee3f20f,0x6447442b,0x32fc7e63,
0x1ff987d9,0x0bf21f54,0x2ee6f9b8,0x016fc43f,0x0faa0ff9,0xa87f65f9,
0x40df503e,0x3ee073fd,0xe8bf203e,0x5f717e1f,0xecce99f6,0xf903fb03,
0x5f317e65,0x3f32edf7,0xb82033cc,0x2a4ccecc,0x59504f9d,0x5417d43f,
0x3abf302f,0x4b115c2e,0x2a0bf1fa,0xf03fea4e,0x4e02fc89,0x3fb99afd,
0x93300fd8,0xf913e07f,0x09f03fdb,0x7cc05ff1,0x13f601af,0x8ff62fc8,
0x7d9fcc5f,0xd83ec77c,0xdabfc81f,0x746fd41e,0x133d3316,0xd3310406,
0x7cbe2333,0x75f3188e,0x08b7c43f,0x9d022bf1,0x447503ee,0x41fc7e24,
0xf3131dda,0x17e44f85,0x5cf7ea70,0x4e05983f,0xc89f06f9,0x4f85fb2f,
0xfc805fc8,0x80ffdc04,0xf8ff62fc,0x47eceb85,0x3f60fb5f,0x2febfc81,
0xd09f3f88,0x42c02030,0x5ffabff9,0x513eb7e2,0x2eea87dd,0xf30b11b8,
0xaca87d57,0x502fae23,0x44f81b5b,0x747142fc,0x0a07f72f,0x17f55644,
0x4cbf227c,0x3e627c6f,0x3ee0260f,0x1beaa604,0x43ff17e4,0xf1f6105f,
0x0fec1f6b,0x07fc57e4,0xcb96f726,0x2033ccfc,0x00400b00,0x10200000,
0x09177370,0x40200ae0,0x961fe45f,0x23fb9ae3,0xf51202db,0x2fc8bf0b,
0x745f89f5,0x4fb82c3f,0x427ec710,0xc89f32fc,0xbf1f600e,0x40ff41f6,
0x40df72fc,0x4ccccc40,0x33333330,0x00000020,0x00000000,0x7d400000,
0x75dfd30e,0x9c4ba6bd,0x3930dfd8,0xffa87ea0,0x74c3bea3,0x2a0bdbdf,
0x75ff70ef,0xbfb10fd9,0x3ee3ea83,0x337fa63f,0xed98003d,0x3fd1ff32,
0x260bff98,0x09fb0cfe,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x4db19d30,0x000934eb,0x9cd88a15,0x7d79d31e,0x07141bb3,
0x105d79d3,0x1edaca83,0x20591bd3,0x280b8905,0x198cc530,0x983506e6,
0x4c330542,0xca80661d,0x32a4cccc,0x1e44cccc,0x8898ec41,0x41983261,
0x82222220,0xddd13bba,0x00005ddd,0x44fb5f80,0x6440336f,0x3a1dd265,
0x23ba0cae,0x223f9afc,0xb1df0955,0x9945a88f,0x01d7e45f,0x0f236603,
0x5b550fe2,0xad9b75ba,0x221f551d,0xacaa7c79,0x0f629f53,0x26666273,
0x26666219,0x3f99a669,0x1eb365f3,0x2fb72a79,0xbbbbb13a,0x01376e3b,
0x3e000000,0x29fb8fb5,0x7cc3bb50,0xd07e86a8,0x0fe23eeb,0x2bf0fa99,
0x3aefe27c,0x3e207f43,0xcccccb87,0x9d81fcc3,0x6cb6e20e,0x1cc6e9b4,
0x9f45b8d1,0xc8e259bb,0xbbbab443,0x265803bb,0x02007620,0x017710c6,
0x00000000,0x47dafc00,0x5f542cf8,0x86c8fa80,0x3eebd05e,0xdb5c3f88,
0xb87cafc5,0xc81fd40b,0x4cccc42f,0x4c2e6409,0x96e64954,0x2326572a,
0x3b022e1c,0x12bc88e4,0x984c3c85,0x80199999,0x00000001,0x00000000,
0x36bd0000,0xdc887d87,0xd0b27703,0x47dd7a0b,0x2cc743f8,0x65c7cafc,
0x0c5be25a,0x82c0dd51,0x20d8b33c,0x0442200d,0x8ffdc393,0x2000c2ac,
0x000004d8,0x00000000,0x00000000,0x767e4000,0x2a024c1f,0x2385c1cd,
0x7fc40ef8,0x25fabfd8,0x1df3070a,0xfc8203fd,0xb1d31ecc,0x20c0a09f,
0x00000001,0x00000000,0x00000000,0x00000000,0x10000000,0x12600100,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
};
static signed short stb__times_bold_14_latin1_x[224]={ 0,1,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,-1,0,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
static signed short stb__times_bold_14_latin1_y[224]={ 11,2,2,2,2,2,2,2,2,2,2,3,9,7,
9,2,2,2,2,2,2,2,2,2,2,2,5,5,3,5,3,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,12,2,5,2,5,2,5,2,5,2,2,
2,2,2,5,5,5,5,5,5,5,3,5,5,5,5,5,5,2,2,2,6,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,11,4,2,2,3,2,
2,2,2,2,2,5,5,7,2,1,2,3,2,2,2,5,2,5,10,2,2,5,2,2,2,4,-1,-1,-1,0,
0,0,2,2,-1,-1,-1,0,-1,-1,-1,0,2,0,-1,-1,-1,0,0,4,2,-1,-1,-1,0,-1,2,2,2,2,
2,2,2,2,5,5,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,4,2,2,2,2,2,2,2,
};
static unsigned short stb__times_bold_14_latin1_w[224]={ 0,3,5,7,6,12,10,3,5,4,6,7,3,4,
3,4,6,6,6,6,6,6,6,7,6,6,3,4,7,8,7,6,12,9,8,9,9,8,8,10,10,5,7,10,
8,12,9,10,8,10,10,7,8,9,10,13,10,9,9,3,4,3,7,8,3,7,7,6,7,6,6,7,7,4,
5,8,4,11,7,6,7,7,6,5,5,7,7,10,7,7,6,4,2,4,7,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,0,3,6,7,7,7,
2,6,5,10,4,7,8,4,10,8,5,7,4,4,3,8,7,3,3,4,4,7,10,10,10,6,9,9,9,9,
9,9,14,9,8,8,8,8,5,5,5,5,9,9,10,10,10,10,10,7,10,9,9,9,9,9,8,7,7,7,
7,7,7,7,9,6,6,6,6,6,5,4,5,5,6,7,6,6,6,6,6,7,6,7,7,7,7,7,7,7,
};
static unsigned short stb__times_bold_14_latin1_h[224]={ 0,10,5,10,10,10,10,5,12,12,6,8,5,2,
3,10,10,9,9,10,9,10,10,10,10,10,7,9,7,4,7,10,12,9,9,10,9,9,9,10,9,9,10,9,
9,9,10,10,9,12,9,10,9,10,10,10,9,9,9,12,10,12,5,2,3,7,10,7,10,7,9,9,9,9,
12,9,9,6,6,7,9,9,6,7,9,7,7,7,6,9,6,12,12,12,3,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,0,10,12,10,7,9,
12,12,3,10,5,6,4,2,10,1,5,8,5,5,3,9,12,3,4,5,5,6,10,10,10,10,12,12,12,11,
11,11,9,12,12,12,12,11,12,12,12,11,9,12,13,13,13,12,12,6,10,13,13,13,12,12,9,10,10,10,
10,10,10,10,7,9,10,10,10,10,9,9,9,9,10,9,10,10,10,10,10,6,8,10,10,10,10,12,12,12,
};
static unsigned short stb__times_bold_14_latin1_s[224]={ 64,141,119,192,222,49,62,141,88,124,68,
175,150,220,189,87,99,109,102,136,58,165,172,179,198,113,252,65,17,163,241,
216,164,37,53,233,99,116,125,205,161,172,50,241,7,16,35,243,70,129,140,
128,131,223,143,1,88,78,68,150,45,154,106,211,199,193,15,201,27,208,218,
210,202,197,158,183,178,40,60,234,143,115,33,249,109,1,9,215,82,29,75,
207,18,245,203,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,
166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,64,23,1,
120,226,79,194,187,193,187,114,25,172,220,154,225,125,158,131,136,181,134,116,
185,159,154,145,52,38,27,16,9,140,177,41,92,57,82,87,197,212,221,230,
73,239,51,250,67,151,8,43,1,32,105,94,98,243,22,12,54,31,21,225,
168,133,214,152,160,176,184,183,234,200,207,229,236,1,192,47,62,145,123,102,
73,80,92,106,90,151,1,109,117,125,72,80,64, };
static unsigned short stb__times_bold_14_latin1_t[224]={ 14,15,60,15,15,28,28,60,1,1,60,
50,60,60,60,28,28,39,39,28,39,28,28,28,28,28,39,39,60,60,50,
28,1,50,50,28,50,39,39,28,39,39,39,39,50,50,39,28,39,1,50,
28,50,28,28,39,50,50,50,1,39,1,60,60,60,50,39,50,39,50,39,
39,39,39,1,39,39,60,60,50,39,50,60,50,50,60,60,50,60,50,60,
1,15,1,60,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,
50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,14,39,15,
28,50,39,1,1,60,28,60,60,60,60,28,60,60,50,60,60,60,39,1,
60,60,60,60,60,28,28,28,28,1,1,15,15,15,15,39,1,1,1,1,
15,1,15,1,15,39,15,1,1,1,1,1,60,15,1,1,1,15,15,39,
15,15,15,15,15,15,15,50,39,15,15,15,15,50,39,50,50,15,50,15,
28,28,28,28,60,50,28,15,15,15,1,1,1, };
static unsigned short stb__times_bold_14_latin1_a[224]={ 51,67,112,101,101,202,168,56,
67,67,101,115,51,67,51,56,101,101,101,101,101,101,101,101,
101,101,67,67,115,115,115,101,188,146,135,146,146,135,124,157,
157,79,101,157,135,191,146,157,124,157,146,112,135,146,146,202,
146,146,135,67,56,67,118,101,67,101,112,90,112,90,67,101,
112,56,67,112,56,168,112,101,112,112,90,79,67,112,101,146,
101,101,90,80,45,80,105,157,157,157,157,157,157,157,157,157,
157,157,157,157,157,157,157,157,157,157,157,157,157,157,157,157,
157,157,157,157,157,157,157,157,51,67,101,101,101,101,45,101,
67,151,61,101,115,67,151,101,81,111,61,61,67,117,109,51,
67,61,67,101,152,152,152,101,146,146,146,146,146,146,202,146,
135,135,135,135,79,79,79,79,146,146,157,157,157,157,157,115,
157,146,146,146,146,146,124,112,101,101,101,101,101,101,146,90,
90,90,90,90,56,56,56,56,101,112,101,101,101,101,101,111,
101,112,112,112,112,101,112,101, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT or STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_times_bold_14_latin1(stb_fontchar font[STB_FONT_times_bold_14_latin1_NUM_CHARS],
unsigned char data[STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT][STB_FONT_times_bold_14_latin1_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__times_bold_14_latin1_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_times_bold_14_latin1_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_times_bold_14_latin1_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_times_bold_14_latin1_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_times_bold_14_latin1_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__times_bold_14_latin1_s[i]) * recip_width;
font[i].t0 = (stb__times_bold_14_latin1_t[i]) * recip_height;
font[i].s1 = (stb__times_bold_14_latin1_s[i] + stb__times_bold_14_latin1_w[i]) * recip_width;
font[i].t1 = (stb__times_bold_14_latin1_t[i] + stb__times_bold_14_latin1_h[i]) * recip_height;
font[i].x0 = stb__times_bold_14_latin1_x[i];
font[i].y0 = stb__times_bold_14_latin1_y[i];
font[i].x1 = stb__times_bold_14_latin1_x[i] + stb__times_bold_14_latin1_w[i];
font[i].y1 = stb__times_bold_14_latin1_y[i] + stb__times_bold_14_latin1_h[i];
font[i].advance_int = (stb__times_bold_14_latin1_a[i]+8)>>4;
font[i].s0f = (stb__times_bold_14_latin1_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__times_bold_14_latin1_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__times_bold_14_latin1_s[i] + stb__times_bold_14_latin1_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__times_bold_14_latin1_t[i] + stb__times_bold_14_latin1_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__times_bold_14_latin1_x[i] - 0.5f;
font[i].y0f = stb__times_bold_14_latin1_y[i] - 0.5f;
font[i].x1f = stb__times_bold_14_latin1_x[i] + stb__times_bold_14_latin1_w[i] + 0.5f;
font[i].y1f = stb__times_bold_14_latin1_y[i] + stb__times_bold_14_latin1_h[i] + 0.5f;
font[i].advance = stb__times_bold_14_latin1_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_times_bold_14_latin1
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_times_bold_14_latin1_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_times_bold_14_latin1_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_times_bold_14_latin1_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_times_bold_14_latin1_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_times_bold_14_latin1_LINE_SPACING
#endif
|
libremoney/main | Lm/Modules/Peers/Peers.js | <reponame>libremoney/main
/**!
* LibreMoney Peers 0.2
* Copyright (c) LibreMoney Team <<EMAIL>>
* CC0 license
*/
if (typeof module !== "undefined") {
var Constants = require(__dirname + '/../../Constants');
var Convert = require(__dirname + '/../../Util/Convert');
var Core = require(__dirname + '/../Core');
var Listeners = require(__dirname + '/../../Util/Listeners');
var ThreadPool = require(__dirname + '/../ThreadPool');
}
var Peers = function() {
var Event = {
BLACKLIST:0,
UNBLACKLIST:1,
DEACTIVATE:2,
REMOVE:3,
DOWNLOADED_VOLUME:4,
UPLOADED_VOLUME:5,
WEIGHT:6,
ADDED_ACTIVE_PEER:7,
CHANGED_ACTIVE_PEER:8,
NEW_PEER:9
};
var State = {
NON_CONNECTED:0,
CONNECTED:1,
DISCONNECTED:2
}
var peerServer;
var LOGGING_MASK_EXCEPTIONS = 1;
var LOGGING_MASK_NON200_RESPONSES = 2;
var LOGGING_MASK_200_RESPONSES = 4;
var communicationLoggingMask;
var wellKnownPeers = [];
var knownBlacklistedPeers = [];
var connectTimeout;
var readTimeout;
var blacklistingPeriod;
var getMorePeers;
/*
static final int DEFAULT_PEER_PORT = 7874;
static final int TESTNET_PEER_PORT = 6874;
*/
var myPlatform;
var myAddress;
var myPeerServerPort;
var myHallmark;
var shareMyAddress;
var maxNumberOfConnectedPublicPeers;
var enableHallmarkProtection;
var pushThreshold;
var pullThreshold;
var sendToPeersLimit;
var usePeersDb;
var savePeers;
var myPeerInfoRequest;
var myPeerInfoResponse;
var listeners = new Listeners();
var peers = new Array(); // ConcurrentMap<String, PeerImpl>
var announcedAddresses = []; //new ConcurrentHashMap<>();
var allPeers = new Array(); //Collections.unmodifiableCollection(peers.values()); // Collection<PeerImpl>
//var sendToPeersService = Executors.newFixedThreadPool(10);
function AddListener(eventType, listener) {
return listeners.AddListener(eventType, listener);
}
function AddPeer1(announcedAddress) {
throw new Error('This is not implemented');
/*
if (announcedAddress == null) {
return null;
}
try {
URI uri = new URI("http://" + announcedAddress.trim());
String host = uri.getHost();
InetAddress inetAddress = InetAddress.getByName(host);
return addPeer(inetAddress.getHostAddress(), announcedAddress);
} catch (URISyntaxException | UnknownHostException e) {
//Logger.logDebugMessage("Invalid peer address: " + announcedAddress + ", " + e.toString());
return null;
}
*/
}
function AddPeer2(address, announcedAddress) {
throw new Error('This is not implemented');
/*
//re-add the [] to ipv6 addresses lost in getHostAddress() above
String clean_address = address;
if (clean_address.split(":").length > 2) {
clean_address = "[" + clean_address + "]";
}
PeerImpl peer;
if ((peer = peers.get(clean_address)) != null) {
return peer;
}
String peerAddress = normalizeHostAndPort(clean_address);
if (peerAddress == null) {
return null;
}
if ((peer = peers.get(peerAddress)) != null) {
return peer;
}
String announcedPeerAddress = address.equals(announcedAddress) ? peerAddress : normalizeHostAndPort(announcedAddress);
if (Peers.myAddress != null && Peers.myAddress.length() > 0 && Peers.myAddress.equalsIgnoreCase(announcedPeerAddress)) {
return null;
}
peer = new PeerImpl(peerAddress, announcedPeerAddress);
if (Constants.isTestnet && peer.getPort() > 0 && peer.getPort() != TESTNET_PEER_PORT) {
Logger.logDebugMessage("Peer " + peerAddress + " on testnet is not using port " + TESTNET_PEER_PORT + ", ignoring");
return null;
}
peers.put(peerAddress, peer);
if (announcedAddress != null) {
updateAddress(peer);
}
listeners.notify(peer, Event.NEW_PEER);
return peer;
*/
}
function GetActivePeers() {
throw new Error('This is not implemented');
/*
List<PeerImpl> activePeers = new ArrayList<>();
for (PeerImpl peer : peers.values()) {
if (peer.getState() != Peer.State.NON_CONNECTED) {
activePeers.add(peer);
}
}
return activePeers;
*/
}
function GetAllPeers() {
return allPeers;
}
function GetAnyPeer(state, applyPullThreshold) {
throw new Error('This is not implemented');
/*
List<Peer> selectedPeers = new ArrayList<>();
for (Peer peer : peers.values()) {
if (! peer.isBlacklisted() && peer.getState() == state && peer.shareAddress()
&& (!applyPullThreshold || ! Peers.enableHallmarkProtection || peer.getWeight() >= Peers.pullThreshold)) {
selectedPeers.add(peer);
}
}
if (selectedPeers.size() > 0) {
if (! Peers.enableHallmarkProtection) {
return selectedPeers.get(ThreadLocalRandom.current().nextInt(selectedPeers.size()));
}
long totalWeight = 0;
for (Peer peer : selectedPeers) {
long weight = peer.getWeight();
if (weight == 0) {
weight = 1;
}
totalWeight += weight;
}
long hit = ThreadLocalRandom.current().nextLong(totalWeight);
for (Peer peer : selectedPeers) {
long weight = peer.getWeight();
if (weight == 0) {
weight = 1;
}
if ((hit -= weight) < 0) {
return peer;
}
}
}
return null;
*/
}
function GetMorePeersThread() {
/*
private final JSONStreamAware getPeersRequest;
{
JSONObject request = new JSONObject();
request.put("requestType", "getPeers");
getPeersRequest = JSON.prepareRequest(request);
}
public void run() {
try {
try {
Peer peer = getAnyPeer(Peer.State.CONNECTED, true);
if (peer == null) {
return;
}
JSONObject response = peer.send(getPeersRequest);
if (response == null) {
return;
}
JSONArray peers = (JSONArray)response.get("peers");
Set<String> addedAddresses = new HashSet<>();
if (peers != null) {
for (Object announcedAddress : peers) {
if (addPeer((String) announcedAddress) != null) {
addedAddresses.add((String) announcedAddress);
}
}
if (savePeers && addedNewPeer) {
updateSavedPeers();
addedNewPeer = false;
}
}
JSONArray myPeers = new JSONArray();
for (Peer myPeer : Peers.getAllPeers()) {
if (! myPeer.isBlacklisted() && myPeer.getAnnouncedAddress() != null
&& myPeer.getState() == Peer.State.CONNECTED && myPeer.shareAddress()
&& ! addedAddresses.contains(myPeer.getAnnouncedAddress())
&& ! myPeer.getAnnouncedAddress().equals(peer.getAnnouncedAddress())) {
myPeers.add(myPeer.getAnnouncedAddress());
}
}
if (myPeers.size() > 0) {
JSONObject request = new JSONObject();
request.put("requestType", "addPeers");
request.put("peers", myPeers);
peer.send(JSON.prepareRequest(request));
}
} catch (Exception e) {
Logger.logDebugMessage("Error requesting peers from a peer", e);
}
} catch (Throwable t) {
Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString());
t.printStackTrace();
System.exit(1);
}
}
private void updateSavedPeers() {
Set<String> oldPeers = new HashSet<>(PeerDb.loadPeers());
Set<String> currentPeers = new HashSet<>();
for (Peer peer : Peers.peers.values()) {
if (peer.getAnnouncedAddress() != null && ! peer.isBlacklisted()) {
currentPeers.add(peer.getAnnouncedAddress());
}
}
Set<String> toDelete = new HashSet<>(oldPeers);
toDelete.removeAll(currentPeers);
PeerDb.deletePeers(toDelete);
currentPeers.removeAll(oldPeers);
PeerDb.addPeers(currentPeers);
}
*/
}
function GetNumberOfConnectedPublicPeers() {
throw new Error('This is not implemented');
/*
int numberOfConnectedPeers = 0;
for (Peer peer : peers.values()) {
if (! Peers.enableHallmarkProtection) {
return selectedPeers.get(ThreadLocalRandom.current().nextInt(selectedPeers.size()));
}
if (peer.getState() == Peer.State.CONNECTED && peer.getAnnouncedAddress() != null) {
numberOfConnectedPeers++;
}
}
return numberOfConnectedPeers;
*/
}
function GetPeer(peerAddress) {
return peers[peerAddress];
}
function Init() {
Core.AddListener(Core.Event.Shutdown, function() {
Shutdown();
});
Core.AddListener(Core.Event.GetState, OnGetState);
Core.AddListener(Core.Event.InitServer, OnInitServer);
Init1();
Init2();
Init3();
Init4();
if (!Constants.isOffline) {
ThreadPool.ScheduleThread(Peers.PeerConnectingThread, 5);
ThreadPool.ScheduleThread(Peers.PeerUnBlacklistingThread, 1);
if (Peers.getMorePeers) {
ThreadPool.ScheduleThread(Peers.GetMorePeersThread, 5);
}
}
Init8();
Init9();
}
function Init1() {
/*
myPlatform = Nxt.getStringProperty("nxt.myPlatform");
myAddress = Nxt.getStringProperty("nxt.myAddress");
if (myAddress != null && myAddress.endsWith(":" + TESTNET_PEER_PORT) && !Constants.isTestnet) {
throw new RuntimeException("Port " + TESTNET_PEER_PORT + " should only be used for testnet!!!");
}
myPeerServerPort = Nxt.getIntProperty("nxt.peerServerPort");
if (myPeerServerPort == TESTNET_PEER_PORT && !Constants.isTestnet) {
throw new RuntimeException("Port " + TESTNET_PEER_PORT + " should only be used for testnet!!!");
}
shareMyAddress = Nxt.getBooleanProperty("nxt.shareMyAddress") && ! Constants.isOffline;
myHallmark = Nxt.getStringProperty("nxt.myHallmark");
if (Peers.myHallmark != null && Peers.myHallmark.length() > 0) {
try {
Hallmark hallmark = Hallmark.parseHallmark(Peers.myHallmark);
if (!hallmark.isValid() || myAddress == null) {
throw new RuntimeException();
}
URI uri = new URI("http://" + myAddress.trim());
String host = uri.getHost();
if (!hallmark.getHost().equals(host)) {
throw new RuntimeException();
}
} catch (RuntimeException|URISyntaxException e) {
Logger.logMessage("Your hallmark is invalid: " + Peers.myHallmark + " for your address: " + myAddress);
throw new RuntimeException(e.toString(), e);
}
}
*/
}
function Init2() {
var json = {};
if (this.myAddress != null && this.myAddress.length > 0) {
try {
var uri = new URI("http://" + myAddress.trim());
var host = uri.hostname; //uri.getHost();
var port = uri.port(); //uri.getPort();
json.announcedAddress = host;
} catch (e) {
Logger.warn("Your announce address is invalid: " + myAddress);
throw new Error(e);
}
}
if (Peers.myHallmark != null && Peers.myHallmark.length > 0) {
json.hallmark = Peers.myHallmark;
}
json.application = Core.GetApplication();
json.version = Core.GetVersion();
json.platform = Peers.myPlatform;
json.shareAddress = Peers.shareMyAddress;
Logger.debug("My peer info:\n" + json);
this.myPeerInfoResponse = json;
json.requestType = "getInfo";
this.myPeerInfoRequest = json;
}
function Init3() {
/*
List<String> wellKnownPeersList = Constants.isTestnet ? Nxt.getStringListProperty("nxt.testnetPeers")
: Nxt.getStringListProperty("nxt.wellKnownPeers");
if (wellKnownPeersList.isEmpty()) {
wellKnownPeers = Collections.emptySet();
} else {
wellKnownPeers = Collections.unmodifiableSet(new HashSet<>(wellKnownPeersList));
}
List<String> knownBlacklistedPeersList = Nxt.getStringListProperty("nxt.knownBlacklistedPeers");
if (knownBlacklistedPeersList.isEmpty()) {
knownBlacklistedPeers = Collections.emptySet();
} else {
knownBlacklistedPeers = Collections.unmodifiableSet(new HashSet<>(knownBlacklistedPeersList));
}
maxNumberOfConnectedPublicPeers = Nxt.getIntProperty("nxt.maxNumberOfConnectedPublicPeers");
connectTimeout = Nxt.getIntProperty("nxt.connectTimeout");
readTimeout = Nxt.getIntProperty("nxt.readTimeout");
enableHallmarkProtection = Nxt.getBooleanProperty("nxt.enableHallmarkProtection");
pushThreshold = Nxt.getIntProperty("nxt.pushThreshold");
pullThreshold = Nxt.getIntProperty("nxt.pullThreshold");
blacklistingPeriod = Nxt.getIntProperty("nxt.blacklistingPeriod");
communicationLoggingMask = Nxt.getIntProperty("nxt.communicationLoggingMask");
sendToPeersLimit = Nxt.getIntProperty("nxt.sendToPeersLimit");
usePeersDb = Nxt.getBooleanProperty("nxt.usePeersDb") && ! Constants.isOffline;
savePeers = usePeersDb && Nxt.getBooleanProperty("nxt.savePeers");
getMorePeers = Nxt.getBooleanProperty("nxt.getMorePeers");
ThreadPool.runBeforeStart(new Runnable() {
private void loadPeers(List<Future<String>> unresolved, Collection<String> addresses) {
for (final String address : addresses) {
Future<String> unresolvedAddress = sendToPeersService.submit(new Callable<String>() {
public String call() {
Peer peer = Peers.addPeer(address);
return peer == null ? address : null;
}
});
unresolved.add(unresolvedAddress);
}
}
public void run() {
List<Future<String>> unresolvedPeers = new ArrayList<>();
if (! wellKnownPeers.isEmpty()) {
loadPeers(unresolvedPeers, wellKnownPeers);
}
if (usePeersDb) {
Logger.logDebugMessage("Loading known peers from the database...");
loadPeers(unresolvedPeers, PeerDb.loadPeers());
}
for (Future<String> unresolvedPeer : unresolvedPeers) {
try {
String badAddress = unresolvedPeer.get(5, TimeUnit.SECONDS);
if (badAddress != null) {
Logger.logDebugMessage("Failed to resolve peer address: " + badAddress);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
Logger.logDebugMessage("Failed to add peer", e);
} catch (TimeoutException e) {
}
}
Logger.logDebugMessage("Known peers: " + peers.size());
}
}, false);
*/
}
function Init4() {
/*
usePeersDb = Nxt.getBooleanProperty("nxt.usePeersDb");
if (usePeersDb) {
Logger.logDebugMessage("Loading known peers from the database...");
for (String savedPeer : PeerDb.loadPeers()) {
Peers.addPeer(savedPeer);
}
}
Logger.logDebugMessage("Known peers: " + peers.size());
savePeers = usePeersDb && Nxt.getBooleanProperty("nxt.savePeers");
*/
}
function Init8() {
Account.AddListener(Account.Event.BALANCE, function(account) {
/*
for (PeerImpl peer : Peers.peers.values()) {
if (peer.getHallmark() != null && peer.getHallmark().getAccountId().equals(account.getId())) {
Peers.listeners.Notify(Peers.Event.WEIGHT, peer);
}
}
*/
});
}
function Init9() {
/*
if (Peers.shareMyAddress) {
peerServer = new Server();
ServerConnector connector = new ServerConnector(peerServer);
final int port = Constants.isTestnet ? TESTNET_PEER_PORT : Peers.myPeerServerPort;
connector.setPort(port);
final String host = Nxt.getStringProperty("nxt.peerServerHost");
connector.setHost(host);
connector.setIdleTimeout(Nxt.getIntProperty("nxt.peerServerIdleTimeout"));
connector.setReuseAddress(true);
peerServer.addConnector(connector);
ServletHolder peerServletHolder = new ServletHolder(new PeerServlet());
boolean isGzipEnabled = Nxt.getBooleanProperty("nxt.enablePeerServerGZIPFilter");
peerServletHolder.setInitParameter("isGzipEnabled", Boolean.toString(isGzipEnabled));
ServletHandler peerHandler = new ServletHandler();
peerHandler.addServletWithMapping(peerServletHolder, "/*");
if (Nxt.getBooleanProperty("nxt.enablePeerServerDoSFilter")) {
FilterHolder dosFilterHolder = peerHandler.addFilterWithMapping(DoSFilter.class, "/*", FilterMapping.DEFAULT);
dosFilterHolder.setInitParameter("maxRequestsPerSec", Nxt.getStringProperty("nxt.peerServerDoSFilter.maxRequestsPerSec"));
dosFilterHolder.setInitParameter("delayMs", Nxt.getStringProperty("nxt.peerServerDoSFilter.delayMs"));
dosFilterHolder.setInitParameter("maxRequestMs", Nxt.getStringProperty("nxt.peerServerDoSFilter.maxRequestMs"));
dosFilterHolder.setInitParameter("trackSessions", "false");
dosFilterHolder.setAsyncSupported(true);
}
if (isGzipEnabled) {
FilterHolder gzipFilterHolder = peerHandler.addFilterWithMapping(GzipFilter.class, "/*", FilterMapping.DEFAULT);
gzipFilterHolder.setInitParameter("methods", "GET,POST");
gzipFilterHolder.setAsyncSupported(true);
}
peerServer.setHandler(peerHandler);
peerServer.setStopAtShutdown(true);
ThreadPool.runBeforeStart(new Runnable() {
public void run() {
try {
peerServer.start();
Logger.logMessage("Started peer networking server at " + host + ":" + port);
} catch (Exception e) {
Logger.logErrorMessage("Failed to start peer networking server", e);
throw new RuntimeException(e.toString(), e);
}
}
}, true);
} else {
peerServer = null;
Logger.logMessage("shareMyAddress is disabled, will not start peer networking server");
}
*/
}
function NotifyListeners(eventType, peer) {
listeners.Notify(eventType, peer);
}
function NormalizeHostAndPort(address) {
throw new Error('This is not implemented');
/*
try {
if (address == null) {
return null;
}
URI uri = new URI("http://" + address.trim());
String host = uri.getHost();
if (host == null || host.equals("") || host.equals("localhost") ||
host.equals("127.0.0.1") || host.equals("[0:0:0:0:0:0:0:1]")) {
return null;
}
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() ||
inetAddress.isLinkLocalAddress()) {
return null;
}
int port = uri.getPort();
return port == -1 ? host : host + ':' + port;
} catch (URISyntaxException |UnknownHostException e) {
return null;
}
*/
}
function OnGetState(response) {
response.numberOfPeers = allPeers.length;
}
function OnInitServer(app) {
var Api = require(__dirname + "/Api");
app.get("/api/decodeHallmark", Api.DecodeHallmark);
app.get("/api/getPeer", Api.GetPeer);
app.get("/api/getPeers", Api.GetPeers);
app.get("/api/markHost", Api.MarkHost); // post
/*
app.get("/api/addPeers", Api.AddPeers);
app.get("/api/getCumulativeDifficulty", Api.GetCumulativeDifficulty);
app.get("/api/getInfo", Api.GetInfo);
app.get("/api/getMilestoneBlockIds", Api.GetMilestoneBlockIds);
app.get("/api/getNextBlockIds", Api.GetNextBlockIds);
app.get("/api/getNextBlocks", Api.GetNextBlocks);
app.get("/api/getPeers", Api.GetPeers);
app.get("/api/getUnconfirmedTransactions", Api.GetUnconfirmedTransactions);
app.get("/api/processBlock", Api.ProcessBlock);
app.get("/api/processTransactions", Api.ProcessTransactions);
*/
}
function PeerConnectingThread() {
throw new Error('This is not implemented');
/*
try {
try {
if (getNumberOfConnectedPublicPeers() < Peers.maxNumberOfConnectedPublicPeers) {
PeerImpl peer = (PeerImpl)getAnyPeer(ThreadLocalRandom.current().nextInt(2) == 0 ? Peer.State.NON_CONNECTED : Peer.State.DISCONNECTED, false);
if (peer != null) {
peer.connect();
}
int now = Convert.getEpochTime();
for (PeerImpl peer : peers.values()) {
if (peer.getState() == Peer.State.CONNECTED && now - peer.getLastUpdated() > 3600) {
peer.connect();
}
}
}
} catch (Exception e) {
Logger.logDebugMessage("Error connecting to peer", e);
}
} catch (Throwable t) {
Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString());
t.printStackTrace();
System.exit(1);
}
*/
}
/*
private volatile boolean addedNewPeer;
{
Peers.addListener(new Listener<Peer>() {
@Override
public void notify(Peer peer) {
addedNewPeer = true;
}
}, Event.NEW_PEER);
}
*/
function PeerUnBlacklistingThread() {
throw new Error('This is not implemented');
/*
public void run() {
try {
try {
long curTime = System.currentTimeMillis();
for (PeerImpl peer : peers.values()) {
peer.updateBlacklistedStatus(curTime);
}
} catch (Exception e) {
Logger.logDebugMessage("Error un-blacklisting peer", e);
}
} catch (Throwable t) {
Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString());
t.printStackTrace();
System.exit(1);
}
}
*/
}
function RemoveListener(eventType, listener) {
return listeners.RemoveListener(eventType, listener);
}
function RemovePeer(peer) {
throw new Error('This is not implemented');
/*
if (peer.getAnnouncedAddress() != null) {
announcedAddresses.remove(peer.getAnnouncedAddress());
}
*/
}
function SendToSomePeersBlock(block) {
throw new Error('This is not implemented');
/*
JSONObject request = block.getJSONObject();
request.put("requestType", "processBlock");
sendToSomePeers(request);
*/
}
function SendToSomePeersRequest(request) {
throw new Error('This is not implemented');
/*
final JSONStreamAware jsonRequest = JSON.prepareRequest(request);
int successful = 0;
List<Future<JSONObject>> expectedResponses = new ArrayList<>();
for (final Peer peer : peers.values()) {
if (Peers.enableHallmarkProtection && peer.getWeight() < Peers.pushThreshold) {
continue;
}
if (! peer.isBlacklisted() && peer.getState() == Peer.State.CONNECTED && peer.getAnnouncedAddress() != null) {
Future<JSONObject> futureResponse = sendToPeersService.submit(new Callable<JSONObject>() {
@Override
public JSONObject call() {
return peer.send(jsonRequest);
}
});
expectedResponses.add(futureResponse);
}
if (expectedResponses.size() >= Peers.sendToPeersLimit - successful) {
for (Future<JSONObject> future : expectedResponses) {
try {
JSONObject response = future.get();
if (response != null && response.get("error") == null) {
successful += 1;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
Logger.logDebugMessage("Error in sendToSomePeers", e);
}
}
expectedResponses.clear();
}
if (successful >= Peers.sendToPeersLimit) {
return;
}
}
*/
}
function SendToSomePeersTransactions(transactions) {
throw new Error('This is not implemented');
/*
JSONObject request = new JSONObject();
JSONArray transactionsData = new JSONArray();
for (Transaction transaction : transactions) {
transactionsData.add(transaction.getJSONObject());
}
request.put("requestType", "processTransactions");
request.put("transactions", transactionsData);
sendToSomePeers(request);
*/
}
function Shutdown() {
throw new Error('This is not implemented');
/*
if (Init.peerServer != null) {
try {
Init.peerServer.stop();
} catch (Exception e) {
Logger.logDebugMessage("Failed to stop peer server", e);
}
}
String dumpPeersVersion = Nxt.getStringProperty("nxt.dumpPeersVersion");
if (dumpPeersVersion != null) {
StringBuilder buf = new StringBuilder();
for (Map.Entry<String,String> entry : announcedAddresses.entrySet()) {
Peer peer = peers.get(entry.getValue());
if (peer != null && peer.getState() == Peer.State.CONNECTED && peer.shareAddress() && !peer.isBlacklisted()
&& peer.getVersion() != null && peer.getVersion().startsWith(dumpPeersVersion)) {
buf.append("('").append(entry.getKey()).append("'), ");
}
}
Logger.logDebugMessage(buf.toString());
}
ThreadPool.shutdownExecutor(sendToPeersService);
*/
}
function UpdateAddress(peer) {
throw new Error('This is not implemented');
/*
String oldAddress = announcedAddresses.put(peer.getAnnouncedAddress(), peer.getPeerAddress());
if (oldAddress != null && !peer.getPeerAddress().equals(oldAddress)) {
Logger.logDebugMessage("Peer " + peer.getAnnouncedAddress() + " has changed address from " + oldAddress
+ " to " + peer.getPeerAddress());
Peer oldPeer = peers.remove(oldAddress);
if (oldPeer != null) {
Peers.notifyListeners(oldPeer, Peers.Event.REMOVE);
}
}
*/
}
return {
Event: Event,
State: State,
Statuses: Constants.NetStatuses,
AddListener: AddListener,
AddPeer1: AddPeer1,
AddPeer2: AddPeer2,
GetActivePeers: GetActivePeers,
GetAllPeers: GetAllPeers,
GetAnyPeer: GetAnyPeer,
GetNumberOfConnectedPublicPeers: GetNumberOfConnectedPublicPeers,
GetPeer: GetPeer,
Init: Init,
NotifyListeners: NotifyListeners,
NormalizeHostAndPort: NormalizeHostAndPort,
RemoveListener: RemoveListener,
RemovePeer: RemovePeer,
SendToSomePeersBlock: SendToSomePeersBlock,
SendToSomePeersRequest: SendToSomePeersRequest,
SendToSomePeersTransactions: SendToSomePeersTransactions,
Shutdown: Shutdown,
UpdateAddress: UpdateAddress
}
}();
/*
exports.Event = Event;
exports.State = State;
exports.AddListener = AddListener;
exports.AddPeer1 = AddPeer1;
exports.AddPeer2 = AddPeer2;
exports.GetActivePeers = GetActivePeers;
exports.GetAllPeers = GetAllPeers;
exports.GetAnyPeer = GetAnyPeer;
exports.GetNumberOfConnectedPublicPeers = GetNumberOfConnectedPublicPeers;
exports.GetPeer = GetPeer;
exports.Init = Init;
exports.NotifyListeners = NotifyListeners;
exports.NormalizeHostAndPort = NormalizeHostAndPort;
exports.RemoveListener = RemoveListener;
exports.RemovePeer = RemovePeer;
exports.SendToSomePeersBlock = SendToSomePeersBlock;
exports.SendToSomePeersRequest = SendToSomePeersRequest;
exports.SendToSomePeersTransactions = SendToSomePeersTransactions;
exports.Shutdown = Shutdown;
exports.UpdateAddress = UpdateAddress;
*/
if (typeof module !== "undefined") {
module.exports = Peers;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.