code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright 2011 Google Inc. 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. package com.google.android.apps.body.tdl; import android.opengl.Matrix; /** * Helper class for math. */ public class TdlMath { public static void perspective( float[] m, float angle, float aspect, float near, float far) { float f = (float)Math.tan(0.5 * (Math.PI - angle)); float range = near - far; m[0] = f / aspect; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = f; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = (far + near) / range; m[11] = -1; m[12] = 0; m[13] = 0; m[14] = 2.0f * far * near / range; m[15] = 0; } public static void pickMatrix( float[] m, float x, float y, float width, float height, float[] viewport) { m[0] = viewport[2] / width; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = viewport[3] / height; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = (viewport[2] + (viewport[0] - x)*2) / width; m[13] = (viewport[3] + (viewport[1] - y)*2) / height; m[14] = 0; m[15] = 1; } public static float[] subVector(float[] a, float[] b) { float[] result = { a[0] - b[0], a[1] - b[1], a[2] - b[2] }; return result; } public static float dot(float[] a, float[] b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } public static float[] normalize(float[] a) { float f = 1 / (float)Matrix.length(a[0], a[1], a[2]); float[] result = { a[0] * f, a[1] * f, a[2] * f }; return result; } public static float[] cross(float[] a, float[] b) { float[] result = { a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] }; return result; } }
frydsh/GoogleBody
src/com/google/android/apps/body/tdl/TdlMath.java
Java
apache-2.0
2,574
# -*- encoding: utf-8 -*- Dir[File.expand_path('support', File.dirname(__FILE__)) + "/**/*.rb"].each { |f| require f } if ENV['SCOV'] begin require 'simplecov' SimpleCov.start do add_filter "/spec/" end rescue LoadError end end require 'onstomp' require 'onstomp/open-uri' require 'onstomp/failover'
iande/onstomp
spec/spec_helper.rb
Ruby
apache-2.0
326
//: net/mindview/util/MapData.java // A Map filled with data using a generator object. package com.example.doun.chapter21concurrency.ReaderWriterMapPack; //package net.mindview.util; import java.util.*; public class MapData<K, V> extends LinkedHashMap<K, V> { // A single Pair Generator: public MapData(Generator<Pair<K, V>> gen, int quantity) { for (int i = 0; i < quantity; i++) { Pair<K, V> p = gen.next(); put(p.key, p.value); } } // Two separate Generators: public MapData(Generator<K> genK, Generator<V> genV, int quantity) { for (int i = 0; i < quantity; i++) { put(genK.next(), genV.next()); } } // A key Generator and a single value: public MapData(Generator<K> genK, V value, int quantity) { for (int i = 0; i < quantity; i++) { put(genK.next(), value); } } // An Iterable and a value Generator: public MapData(Iterable<K> genK, Generator<V> genV) { for (K key : genK) { put(key, genV.next()); } } // An Iterable and a single value: public MapData(Iterable<K> genK, V value) { for (K key : genK) { put(key, value); } } // Generic convenience methods: public static <K, V> MapData<K, V> map(Generator<Pair<K, V>> gen, int quantity) { return new MapData<K, V>(gen, quantity); } public static <K, V> MapData<K, V> map(Generator<K> genK, Generator<V> genV, int quantity) { return new MapData<K, V>(genK, genV, quantity); } public static <K, V> MapData<K, V> map(Generator<K> genK, V value, int quantity) { return new MapData<K, V>(genK, value, quantity); } public static <K, V> MapData<K, V> map(Iterable<K> genK, Generator<V> genV) { return new MapData<K, V>(genK, genV); } public static <K, V> MapData<K, V> map(Iterable<K> genK, V value) { return new MapData<K, V>(genK, value); } } ///:~
Doun2017/StudyJavaCode
Chapter21Concurrency/app/src/main/java/com/example/doun/chapter21concurrency/ReaderWriterMapPack/MapData.java
Java
apache-2.0
2,044
# # Author:: Bryan McLellan (btm@loftninjas.org) # Author:: Tyler Cloke (<tyler@chef.io>) # Copyright:: Copyright 2009-2016, Bryan McLellan # License:: Apache License, Version 2.0 # # 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. # require_relative "../resource" require_relative "helpers/cron_validations" require_relative "../provider/cron" # do not remove. we actually need this below class Chef class Resource class Cron < Chef::Resource unified_mode true provides :cron description "Use the **cron** resource to manage cron entries for time-based job scheduling. Properties for a schedule will default to * if not provided. The cron resource requires access to a crontab program, typically cron." state_attrs :minute, :hour, :day, :month, :weekday, :user default_action :create allowed_actions :create, :delete def initialize(name, run_context = nil) super @month = "*" @weekday = "*" end property :minute, [Integer, String], description: "The minute at which the cron entry should run (`0 - 59`).", default: "*", callbacks: { "should be a valid minute spec" => ->(spec) { Chef::ResourceHelpers::CronValidations.validate_numeric(spec, 0, 59) }, } property :hour, [Integer, String], description: "The hour at which the cron entry is to run (`0 - 23`).", default: "*", callbacks: { "should be a valid hour spec" => ->(spec) { Chef::ResourceHelpers::CronValidations.validate_numeric(spec, 0, 23) }, } property :day, [Integer, String], description: "The day of month at which the cron entry should run (`1 - 31`).", default: "*", callbacks: { "should be a valid day spec" => ->(spec) { Chef::ResourceHelpers::CronValidations.validate_numeric(spec, 1, 31) }, } property :month, [Integer, String], description: "The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`).", default: "*", callbacks: { "should be a valid month spec" => ->(spec) { Chef::ResourceHelpers::CronValidations.validate_month(spec) }, } def weekday(arg = nil) if arg.is_a?(Integer) converted_arg = arg.to_s else converted_arg = arg end begin error_message = "You provided '#{arg}' as a weekday, acceptable values are " error_message << Provider::Cron::WEEKDAY_SYMBOLS.map { |sym| ":#{sym}" }.join(", ") error_message << " and a string in crontab format" if (arg.is_a?(Symbol) && !Provider::Cron::WEEKDAY_SYMBOLS.include?(arg)) || (!arg.is_a?(Symbol) && integerize(arg) > 7) || (!arg.is_a?(Symbol) && integerize(arg) < 0) raise RangeError, error_message end rescue ArgumentError end set_or_return( :weekday, converted_arg, kind_of: [String, Symbol] ) end property :time, Symbol, description: "A time interval.", equal_to: Chef::Provider::Cron::SPECIAL_TIME_VALUES property :mailto, String, description: "Set the `MAILTO` environment variable." property :path, String, description: "Set the `PATH` environment variable." property :home, String, description: "Set the `HOME` environment variable." property :shell, String, description: "Set the `SHELL` environment variable." property :command, String, description: "The command to be run, or the path to a file that contains the command to be run.", identity: true property :user, String, description: "The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. This property is not applicable on the AIX platform.", default: "root" property :environment, Hash, description: "A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`.", default: lazy { {} } TIMEOUT_OPTS = %w{duration preserve-status foreground kill-after signal}.freeze TIMEOUT_REGEX = /\A\S+/.freeze property :time_out, Hash, description: "A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: `preserve-status` (BOOL, default: 'false'), `foreground` (BOOL, default: 'false'), `kill-after` (in seconds), `signal` (a name like 'HUP' or a number)", default: lazy { {} }, introduced: "15.7", coerce: proc { |h| if h.is_a?(Hash) invalid_keys = h.keys - TIMEOUT_OPTS unless invalid_keys.empty? error_msg = "Key of option time_out must be equal to one of: \"#{TIMEOUT_OPTS.join('", "')}\"! You passed \"#{invalid_keys.join(", ")}\"." raise Chef::Exceptions::ValidationFailed, error_msg end unless h.values.all? { |x| x =~ TIMEOUT_REGEX } error_msg = "Values of option time_out should be non-empty string without any leading whitespaces." raise Chef::Exceptions::ValidationFailed, error_msg end h elsif h.is_a?(Integer) || h.is_a?(String) { "duration" => h } end } private def integerize(integerish) Integer(integerish) rescue TypeError 0 end end end end
jaymzh/chef
lib/chef/resource/cron.rb
Ruby
apache-2.0
6,133
package com.rotoplastyc.util; public class NavDef { private final String i[]; public final static NavDef ERRO = new NavDef("err","mood_bad","ERRO"); public final static NavDef ERRO2 = new NavDef("err","mood","ERRO"); public NavDef(String contentPointer, String icon, String displayName) { i = new String[3]; i[0] = contentPointer; i[1] = icon; i[2] = displayName; } public String getContentPointer() { return i[0]; } public String getIcon() { return i[1]; } public String getDisplayName() { return i[2]; } }
lucasnoetzold/Viagens
src/java/com/rotoplastyc/util/NavDef.java
Java
apache-2.0
641
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.syncope.types; public enum CipherAlgorithm { MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), AES("AES"); final private String algorithm; CipherAlgorithm(String algorithm) { this.algorithm = algorithm; } public final String getAlgorithm() { return algorithm; } }
ilgrosso/oldSyncopeIdM
client/src/main/java/org/syncope/types/CipherAlgorithm.java
Java
apache-2.0
1,137
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Ilya S. Okomin * @version $Revision$ */ package java.awt.font; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import org.apache.harmony.misc.HashCode; public final class ShapeGraphicAttribute extends GraphicAttribute { // shape to render private Shape fShape; // flag, if the shape should be stroked (true) or filled (false) private boolean fStroke; // bounds of the shape private Rectangle2D fBounds; // X coordinate of the origin point private float fOriginX; // Y coordinate of the origin point private float fOriginY; // width of the shape private float fShapeWidth; // height of the shape private float fShapeHeight; public static final boolean STROKE = true; public static final boolean FILL = false; public ShapeGraphicAttribute(Shape shape, int alignment, boolean stroke) { super(alignment); this.fShape = shape; this.fStroke = stroke; this.fBounds = fShape.getBounds2D(); this.fOriginX = (float)fBounds.getMinX(); this.fOriginY = (float)fBounds.getMinY(); this.fShapeWidth = (float)fBounds.getWidth(); this.fShapeHeight = (float)fBounds.getHeight(); } @Override public int hashCode() { HashCode hash = new HashCode(); hash.append(fShape.hashCode()); hash.append(getAlignment()); return hash.hashCode(); } public boolean equals(ShapeGraphicAttribute sga) { if (sga == null) { return false; } if (sga == this) { return true; } return ( fStroke == sga.fStroke && getAlignment() == sga.getAlignment() && fShape.equals(sga.fShape)); } @Override public boolean equals(Object obj) { try { return equals((ShapeGraphicAttribute) obj); } catch(ClassCastException e) { return false; } } @Override public void draw(Graphics2D g2, float x, float y) { AffineTransform at = AffineTransform.getTranslateInstance(x, y); if (fStroke == STROKE){ Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke()); g2.draw(at.createTransformedShape(fShape)); g2.setStroke(oldStroke); } else { g2.fill(at.createTransformedShape(fShape)); } } @Override public float getAdvance() { return Math.max(0, fShapeWidth + fOriginX); } @Override public float getAscent() { return Math.max(0, -fOriginY); } @Override public Rectangle2D getBounds() { return (Rectangle2D)fBounds.clone(); } @Override public float getDescent() { return Math.max(0, fShapeHeight + fOriginY); } }
freeVM/freeVM
enhanced/archive/classlib/java6/modules/awt/src/main/java/common/java/awt/font/ShapeGraphicAttribute.java
Java
apache-2.0
3,798
<?php /** * The reasons for an OfflineConversionError. * @package Google_Api_Ads_AdWords_v201605 * @subpackage v201605 */ class OfflineConversionErrorReason { const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605"; const XSI_TYPE = "OfflineConversionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } }
SonicGD/google-adwords-api-light
Google/Api/Ads/AdWords/v201605/classes/OfflineConversionErrorReason.php
PHP
apache-2.0
738
package com.jikexueyuan.classdemo; /** * Created by zmzp on 14-12-4. */ class Student{ public void tell(){ System.out.println("Hello Jikexueyuan"); } } public class ClassDemo03 { public static void main(String[] args) { // Student stu = new Student(); // stu.tell(); //匿名对象 new Student().tell(); } }
bobo159357456/bobo
android_project/ClassDemo02/app/src/main/java/com/jikexueyuan/classdemo/ClassDemo03.java
Java
apache-2.0
365
/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _WIN32 #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #else #ifndef NOMINMAX #define NOMINMAX #endif // !NOMINMAX #include <Windows.h> #include "StringUtil.h" #endif #include <string> #include <cstring> #include "util/MemoryMappedFile.h" #include "util/Exceptions.h" #include "util/ScopeUtils.h" namespace aeron { namespace util { #ifdef _WIN32 bool MemoryMappedFile::fill(FileHandle fd, std::size_t size, std::uint8_t value) { std::uint8_t buffer[8196]; memset(buffer, value, m_page_size); DWORD written = 0; while (size >= m_page_size) { if (!::WriteFile(fd.handle, buffer, (DWORD)m_page_size, &written, nullptr)) { return false; } size -= written; } if (size) { if (!::WriteFile(fd.handle, buffer, (DWORD)size, &written, nullptr)) { return false; } } return true; } MemoryMappedFile::ptr_t MemoryMappedFile::createNew(const char *filename, std::size_t offset, std::size_t size) { FileHandle fd{}; fd.handle = ::CreateFile( filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == fd.handle) { throw IOException( std::string("failed to create file: ") + filename + " " + toString(GetLastError()), SOURCEINFO); } OnScopeExit tidy( [&]() { if (INVALID_HANDLE_VALUE != fd.handle) { ::CloseHandle(fd.handle); } }); if (!fill(fd, size, 0)) { throw IOException( std::string("failed to write to file: ") + filename + " " + toString(GetLastError()), SOURCEINFO); } auto obj = MemoryMappedFile::ptr_t(new MemoryMappedFile(fd, offset, size, false)); fd.handle = INVALID_HANDLE_VALUE; return obj; } MemoryMappedFile::ptr_t MemoryMappedFile::mapExisting( const char *filename, std::size_t offset, std::size_t size, bool readOnly) { DWORD dwDesiredAccess = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE); DWORD dwSharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE; FileHandle fd{}; fd.handle = ::CreateFile( filename, dwDesiredAccess, dwSharedMode, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == fd.handle) { throw IOException( std::string("failed to create file: ") + filename + " " + toString(GetLastError()), SOURCEINFO); } OnScopeExit tidy( [&]() { if (INVALID_HANDLE_VALUE != fd.handle) { ::CloseHandle(fd.handle); } }); auto obj = MemoryMappedFile::ptr_t(new MemoryMappedFile(fd, offset, size, readOnly)); fd.handle = INVALID_HANDLE_VALUE; return obj; } #else bool MemoryMappedFile::fill(FileHandle fd, std::size_t size, std::uint8_t value) { std::unique_ptr<std::uint8_t[]> buffer(new std::uint8_t[m_page_size]); memset(buffer.get(), value, m_page_size); while (size >= m_page_size) { if (static_cast<std::size_t>(::write(fd.handle, buffer.get(), m_page_size)) != m_page_size) { return false; } size -= m_page_size; } if (size) { if (static_cast<std::size_t>(::write(fd.handle, buffer.get(), size)) != size) { return false; } } return true; } MemoryMappedFile::ptr_t MemoryMappedFile::createNew(const char *filename, off_t offset, std::size_t size) { FileHandle fd{}; fd.handle = ::open(filename, O_RDWR | O_CREAT, 0666); if (fd.handle < 0) { throw IOException(std::string("failed to create file: ") + filename, SOURCEINFO); } OnScopeExit tidy( [&]() { close(fd.handle); }); if (!fill(fd, size, 0)) { throw IOException(std::string("failed to write to file: ") + filename, SOURCEINFO); } return MemoryMappedFile::ptr_t(new MemoryMappedFile(fd, offset, size, false)); } MemoryMappedFile::ptr_t MemoryMappedFile::mapExisting( const char *filename, off_t offset, std::size_t length, bool readOnly) { FileHandle fd{}; fd.handle = ::open(filename, (readOnly ? O_RDONLY : O_RDWR), 0666); if (fd.handle < 0) { throw IOException(std::string("failed to open existing file: ") + filename, SOURCEINFO); } OnScopeExit tidy( [&]() { close(fd.handle); }); return MemoryMappedFile::ptr_t(new MemoryMappedFile(fd, offset, length, readOnly)); } #endif MemoryMappedFile::ptr_t MemoryMappedFile::mapExisting(const char *filename, bool readOnly) { return mapExisting(filename, 0, 0, readOnly); } std::uint8_t *MemoryMappedFile::getMemoryPtr() const { return m_memory; } std::size_t MemoryMappedFile::getMemorySize() const { return m_memorySize; } std::size_t MemoryMappedFile::m_page_size = getPageSize(); #ifdef _WIN32 MemoryMappedFile::MemoryMappedFile(FileHandle fd, std::size_t offset, std::size_t length, bool readOnly) { m_file = fd.handle; if (0 == length && 0 == offset) { LARGE_INTEGER fileSize; if (!::GetFileSizeEx(fd.handle, &fileSize)) { cleanUp(); throw IOException( std::string("failed query size of existing file: ") + toString(GetLastError()), SOURCEINFO); } length = static_cast<std::size_t>(fileSize.QuadPart); } m_memorySize = length; m_memory = doMapping(m_memorySize, fd, offset, readOnly); if (!m_memory) { cleanUp(); throw IOException(std::string("failed to Map Memory: ") + toString(GetLastError()), SOURCEINFO); } } void MemoryMappedFile::cleanUp() { if (m_memory) { ::UnmapViewOfFile(m_memory); m_memory = nullptr; } if (m_mapping) { ::CloseHandle(m_mapping); m_mapping = nullptr; } if (m_file) { ::CloseHandle(m_file); m_file = nullptr; } } MemoryMappedFile::~MemoryMappedFile() { cleanUp(); } uint8_t *MemoryMappedFile::doMapping(std::size_t size, FileHandle fd, std::size_t offset, bool readOnly) { DWORD flProtect = readOnly ? PAGE_READONLY : PAGE_READWRITE; m_mapping = ::CreateFileMapping(fd.handle, nullptr, flProtect, 0, static_cast<DWORD>(size), nullptr); if (nullptr == m_mapping) { return nullptr; } DWORD dwDesiredAccess = readOnly ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS; void *memory = (LPTSTR)::MapViewOfFile(m_mapping, dwDesiredAccess, 0, static_cast<DWORD>(offset), size); return static_cast<std::uint8_t *>(memory); } std::size_t MemoryMappedFile::getPageSize() noexcept { SYSTEM_INFO system_info; ::GetSystemInfo(&system_info); return static_cast<std::size_t>(system_info.dwPageSize); } std::int64_t MemoryMappedFile::getFileSize(const char *filename) { WIN32_FILE_ATTRIBUTE_DATA fad; if (::GetFileAttributesEx(filename, GetFileExInfoStandard, &fad) == 0) { return -1; } LARGE_INTEGER size; size.HighPart = fad.nFileSizeHigh; size.LowPart = fad.nFileSizeLow; return size.QuadPart; } #else MemoryMappedFile::MemoryMappedFile(FileHandle fd, off_t offset, std::size_t length, bool readOnly) { if (0 == length && 0 == offset) { struct stat statInfo{}; ::fstat(fd.handle, &statInfo); length = static_cast<std::size_t>(statInfo.st_size); } m_memorySize = length; m_memory = doMapping(m_memorySize, fd, static_cast<std::size_t>(offset), readOnly); } MemoryMappedFile::~MemoryMappedFile() { if (m_memory && m_memorySize) { ::munmap(m_memory, m_memorySize); } } std::uint8_t *MemoryMappedFile::doMapping(std::size_t length, FileHandle fd, std::size_t offset, bool readOnly) { void *memory = ::mmap( nullptr, length, readOnly ? PROT_READ : (PROT_READ | PROT_WRITE), MAP_SHARED, fd.handle, static_cast<off_t>(offset)); if (MAP_FAILED == memory) { throw IOException("failed to Memory Map file", SOURCEINFO); } return static_cast<std::uint8_t *>(memory); } std::size_t MemoryMappedFile::getPageSize() noexcept { return static_cast<std::size_t>(::getpagesize()); } std::int64_t MemoryMappedFile::getFileSize(const char *filename) { struct stat statInfo{}; if (::stat(filename, &statInfo) < 0) { return -1; } return statInfo.st_size; } #endif }}
EvilMcJerkface/Aeron
aeron-client/src/main/cpp/util/MemoryMappedFile.cpp
C++
apache-2.0
9,367
using Meridian.ViewModel.Common; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Meridian.View.Common { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class NowPlayingView : Page { public NowPlayingViewModel ViewModel => DataContext as NowPlayingViewModel; public NowPlayingView() { this.InitializeComponent(); } } }
Stealth2012/meridian-uwp
Meridian/View/Common/NowPlayingView.xaml.cs
C#
apache-2.0
562
package com.polarion.starter.utility; /** * Created by scottrichards on 9/5/15. */ public class URLService extends Object { private static String baseURL = "http://54.183.27.217"; // return url formed by adding the specified ending url to the base url static public String buildUrl(String url) { String fullUrl; if (url.charAt(0) != '/') { fullUrl = baseURL + '/' + url; } else { fullUrl = baseURL + url; } return fullUrl; } }
scottrichards/PolarionLive2015Android
ParseStarterProject/src/main/java/com/polarion/starter/utility/URLService.java
Java
apache-2.0
511
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ $(function() { var obtainFormMeta = function(formId) { return $(formId).data(); }; $('#form-asset-update').ajaxForm({ beforeSubmit:function(){ PublisherUtils.blockButtons({ container:'updateButtons', msg:'Updating '+PublisherUtils.resolveCurrentPageAssetType()+' instance' }); }, success: function() { alert('Updated the '+PublisherUtils.resolveCurrentPageAssetType()+ ' successfully'); PublisherUtils.unblockButtons({ container:'updateButtons' }); }, error: function() { alert('Unable to update the '+PublisherUtils.resolveCurrentPageAssetType()); PublisherUtils.unblockButtons({ container:'updateButtons' }); } }); var initDatePicker = function(){ console.info('init date picker'); if($(this).attr('data-render-options') == "date-time"){ var dateField = this; $(this).DatePicker({ mode: 'single', position: 'right', onBeforeShow: function(el){ if($(dateField).val().replace(/^\s+|\s+$/g,"")){ $(dateField).DatePickerSetDate($(dateField).val(), true); } }, onChange: function(date, el) { $(el).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear()); if($('#closeOnSelect input').attr('checked')) { $(el).DatePickerHide(); } } }); } }; $('#form-asset-update input[type="text"]').each(initDatePicker); var removeUnboundRow = function(link){ var table = link.closest('table'); if($('tr',table).length == 2){ table.hide(); } link.closest('tr').remove(); }; $('.js-add-unbounded-row').click(function(){ var tableName = $(this).attr('data-name'); var table = $('#table_'+tableName); var referenceRow = $('#table_reference_'+tableName); var newRow = referenceRow.clone().removeAttr('id'); table.show().append(newRow); $('input[type="text"]',newRow).each(initDatePicker); }); $('.js-unbounded-table').on('click','a',function(event){ removeUnboundRow($(event.target)); }); $('#tmp_refernceTableForUnbounded').detach().attr('id','refernceTableForUnbounded').appendTo('body'); $('#tmp_refernceTableForUnbounded').remove(); });
srsharon/carbon-store
apps/publisher/themes/default/js/update_asset.js
JavaScript
apache-2.0
3,312
/* * The University of Wales, Cardiff Triana Project Software License (Based * on the Apache Software License Version 1.1) * * Copyright (c) 2007 University of Wales, Cardiff. All rights reserved. * * Redistribution and use of the software 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. The end-user documentation included with the redistribution, if any, * must include the following acknowledgment: "This product includes * software developed by the University of Wales, Cardiff for the Triana * Project (http://www.trianacode.org)." Alternately, this * acknowledgment may appear in the software itself, if and wherever * such third-party acknowledgments normally appear. * * 4. The names "Triana" and "University of Wales, Cardiff" must not be * used to endorse or promote products derived from this software * without prior written permission. For written permission, please * contact triana@trianacode.org. * * 5. Products derived from this software may not be called "Triana," nor * may Triana appear in their name, without prior written permission of * the University of Wales, Cardiff. * * 6. This software may not be sold, used or incorporated into any product * for sale to third parties. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 UNIVERSITY OF WALES, CARDIFF 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. * * ------------------------------------------------------------------------ * * This software consists of voluntary contributions made by many * individuals on behalf of the Triana Project. For more information on the * Triana Project, please see. http://www.trianacode.org. * * This license is based on the BSD license as adopted by the Apache * Foundation and is governed by the laws of England and Wales. * */ package org.trianacode.gui.help; import java.net.URL; import java.util.Enumeration; import java.util.Vector; /** * @version $Revision: 4048 $ */ public class UrlHistory extends Vector { private int urlIndex; private int urlCount; // A vector which contains the UrlEventListeners protected Vector urlEventVector; public UrlHistory() { super(); urlEventVector = new Vector(); urlIndex = -1; urlCount = 0; // System.out.println("*** Creating UrlHistory ***"); } public void addUrl(URL url) { urlIndex++; urlCount = urlIndex + 1; if (urlCount > elementCount) { setSize(urlCount + 10); } setElementAt(url, urlIndex); // System.out.println("*** Adding URL ***"); processUrlEvent(new UrlEvent(this)); } public URL getPreviousUrl() { if (urlIndex <= 0) { return null; } urlIndex--; processUrlEvent(new UrlEvent(this)); return (URL) elementAt(urlIndex); } public URL getNextUrl() { if (urlIndex >= (urlCount - 1)) { return null; } urlIndex++; processUrlEvent(new UrlEvent(this)); return (URL) elementAt(urlIndex); } public int getIndex() { return urlIndex; } public int countUrls() { return urlCount; } public void addUrlEventListener(UrlEventListener urlListener) { urlEventVector.addElement(urlListener); } public void removeUrlEventListener(UrlEventListener urlListener) { urlEventVector.removeElement(urlListener); } private void processUrlEvent(UrlEvent event) { UrlEventListener listener; Enumeration e = urlEventVector.elements(); while (e.hasMoreElements()) { // System.out.println("*** Throwing UrlEvent ***"); listener = (UrlEventListener) e.nextElement(); listener.indexChanged(event); } } }
CSCSI/Triana
triana-gui/src/main/java/org/trianacode/gui/help/UrlHistory.java
Java
apache-2.0
4,922
# # Copyright 2014-2015 Boundary, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from boundary import ApiCli class SourceList(ApiCli): def __init__(self): ApiCli.__init__(self) self.path = "v1/account/sources/" self.method = "GET" def getDescription(self): return "Lists the sources in a Boundary account"
wcainboundary/boundary-api-cli
boundary/source_list.py
Python
apache-2.0
856
package vpc //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // ModifyVpcAttribute invokes the vpc.ModifyVpcAttribute API synchronously // api document: https://help.aliyun.com/api/vpc/modifyvpcattribute.html func (client *Client) ModifyVpcAttribute(request *ModifyVpcAttributeRequest) (response *ModifyVpcAttributeResponse, err error) { response = CreateModifyVpcAttributeResponse() err = client.DoAction(request, response) return } // ModifyVpcAttributeWithChan invokes the vpc.ModifyVpcAttribute API asynchronously // api document: https://help.aliyun.com/api/vpc/modifyvpcattribute.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) ModifyVpcAttributeWithChan(request *ModifyVpcAttributeRequest) (<-chan *ModifyVpcAttributeResponse, <-chan error) { responseChan := make(chan *ModifyVpcAttributeResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.ModifyVpcAttribute(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // ModifyVpcAttributeWithCallback invokes the vpc.ModifyVpcAttribute API asynchronously // api document: https://help.aliyun.com/api/vpc/modifyvpcattribute.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) ModifyVpcAttributeWithCallback(request *ModifyVpcAttributeRequest, callback func(response *ModifyVpcAttributeResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *ModifyVpcAttributeResponse var err error defer close(result) response, err = client.ModifyVpcAttribute(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // ModifyVpcAttributeRequest is the request struct for api ModifyVpcAttribute type ModifyVpcAttributeRequest struct { *requests.RpcRequest VpcName string `position:"Query" name:"VpcName"` ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` VpcId string `position:"Query" name:"VpcId"` OwnerAccount string `position:"Query" name:"OwnerAccount"` CidrBlock string `position:"Query" name:"CidrBlock"` Description string `position:"Query" name:"Description"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` } // ModifyVpcAttributeResponse is the response struct for api ModifyVpcAttribute type ModifyVpcAttributeResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` } // CreateModifyVpcAttributeRequest creates a request to invoke ModifyVpcAttribute API func CreateModifyVpcAttributeRequest() (request *ModifyVpcAttributeRequest) { request = &ModifyVpcAttributeRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Vpc", "2016-04-28", "ModifyVpcAttribute", "vpc", "openAPI") return } // CreateModifyVpcAttributeResponse creates a response to parse from ModifyVpcAttribute response func CreateModifyVpcAttributeResponse() (response *ModifyVpcAttributeResponse) { response = &ModifyVpcAttributeResponse{ BaseResponse: &responses.BaseResponse{}, } return }
xiaozhu36/terraform-provider
vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/vpc/modify_vpc_attribute.go
GO
apache-2.0
4,314
/** Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags 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 bftsmart.demo.listvalue; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import java.util.List; /** * * @author sweta */ public class BFTMapList implements Serializable { private static final long serialVersionUID = -8898539992606449057L; private Map<String, List<String>> tableList = null; public BFTMapList() { tableList=new HashMap<String, List<String>>(); } public Map<String, List<String>> getLists() { return tableList; } public List<String> addList(String key, List<String> list) { return tableList.put(key, list); } public boolean addData(String tableName, String value) { List <String> list = tableList.get(tableName); return list.add(value); } public List<String> getName(String tableName) { return tableList.get(tableName); } public String getEntry(String tableName, int index) { System.out.println("Table name: "+tableName); System.out.println("Entry index: "+ index); List<String> info= tableList.get(tableName); System.out.println("Table: "+info); return info.get(index); } public int getSizeofList() { return tableList.size(); } public int getSize(String tableName) { List<String> table = tableList.get(tableName); return table.size(); } public List<String> removeList(String tableName) { return tableList.remove(tableName); } public String removeEntry(String tableName,int index) { List<String> info= tableList.get(tableName); return info.remove(index); } }
fmrsabino/library
src/bftsmart/demo/listvalue/BFTMapList.java
Java
apache-2.0
2,180
/* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with 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. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * * This file uses NAN: * * Copyright (c) 2015 NAN contributors * * NAN contributors listed at https://github.com/rvagg/nan#contributors * * 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. * * NAME * njsPool.cpp * * DESCRIPTION * Pool class implementation. * *****************************************************************************/ #include "node.h" #include <string> #include "njsOracle.h" #include "njsPool.h" #include "njsConnection.h" using namespace std; using namespace node; using namespace v8; // peristent Pool class handle Nan::Persistent<FunctionTemplate> njsPool::poolTemplate_s; //----------------------------------------------------------------------------- // njsPool::Init() // Initialization function of Pool class. Maps functions and properties // from JS to C++. //----------------------------------------------------------------------------- void njsPool::Init(Local<Object> target) { Nan::HandleScope scope; Local<FunctionTemplate> temp = Nan::New<FunctionTemplate>(New); temp->InstanceTemplate()->SetInternalFieldCount(1); temp->SetClassName(Nan::New<v8::String>("Pool").ToLocalChecked()); Nan::SetPrototypeMethod(temp, "close", Close); Nan::SetPrototypeMethod(temp, "getConnection", GetConnection); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("poolMax").ToLocalChecked(), njsPool::GetPoolMax, njsPool::SetPoolMax); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("poolMin").ToLocalChecked(), njsPool::GetPoolMin, njsPool::SetPoolMin); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("poolIncrement").ToLocalChecked(), njsPool::GetPoolIncrement, njsPool::SetPoolIncrement); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("poolTimeout").ToLocalChecked(), njsPool::GetPoolTimeout, njsPool::SetPoolTimeout); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("connectionsOpen").ToLocalChecked(), njsPool::GetConnectionsOpen, njsPool::SetConnectionsOpen); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("connectionsInUse").ToLocalChecked(), njsPool::GetConnectionsInUse, njsPool::SetConnectionsInUse); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("stmtCacheSize").ToLocalChecked(), njsPool::GetStmtCacheSize, njsPool::SetStmtCacheSize); Nan::SetAccessor(temp->InstanceTemplate(), Nan::New<v8::String>("poolPingInterval").ToLocalChecked(), njsPool::GetPoolPingInterval, njsPool::SetPoolPingInterval); poolTemplate_s.Reset(temp); Nan::Set(target, Nan::New<v8::String>("Pool").ToLocalChecked(), temp->GetFunction()); } //----------------------------------------------------------------------------- // njsPool::CreateFromBaton() // Create a new pool from the baton. //----------------------------------------------------------------------------- Local<Object> njsPool::CreateFromBaton(njsBaton *baton) { Nan::EscapableHandleScope scope; Local<Function> func; Local<Object> obj; njsPool *pool; func = Nan::GetFunction( Nan::New<FunctionTemplate>(poolTemplate_s)).ToLocalChecked(); obj = Nan::NewInstance(func).ToLocalChecked(); pool = Nan::ObjectWrap::Unwrap<njsPool>(obj); pool->dpiPoolHandle = baton->dpiPoolHandle; baton->dpiPoolHandle = NULL; pool->jsOracledb.Reset(baton->jsOracledb); pool->poolMax = baton->poolMax; pool->poolMin = baton->poolMin; pool->poolIncrement = baton->poolIncrement; pool->poolTimeout = baton->poolTimeout; pool->poolPingInterval = baton->poolPingInterval; pool->stmtCacheSize = baton->stmtCacheSize; pool->lobPrefetchSize = baton->lobPrefetchSize; return scope.Escape(obj); } //----------------------------------------------------------------------------- // njsPool::New() // Create new object accesible from JS. This is always called from within // njsPool::CreateFromBaton() and never from any external JS. //----------------------------------------------------------------------------- NAN_METHOD(njsPool::New) { njsPool *pool = new njsPool(); pool->Wrap(info.Holder()); info.GetReturnValue().Set(info.Holder()); } //----------------------------------------------------------------------------- // njsPool::GetPoolMin() // Get accessor of "poolMin" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetPoolMin) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->poolMin); } //----------------------------------------------------------------------------- // njsPool::GetPoolMax() // Get accessor of "poolMax" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetPoolMax) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->poolMax); } //----------------------------------------------------------------------------- // njsPool::GetPoolIncrement() // Get accessor of "poolIncrement" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetPoolIncrement) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->poolIncrement); } //----------------------------------------------------------------------------- // njsPool::GetPoolTimeout() // Get accessor of "poolTimeout" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetPoolTimeout) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->poolTimeout); } //----------------------------------------------------------------------------- // njsPool::GetConnectionsOpen() // Get accessor of "connectionsOpen" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetConnectionsOpen) { njsPool *pool = (njsPool*) ValidateGetter(info); if (!pool) return; if (!pool->IsValid()) { info.GetReturnValue().Set(Nan::Undefined()); return; } uint32_t value; if (dpiPool_getOpenCount(pool->dpiPoolHandle, &value) < 0) { njsOracledb::ThrowDPIError(); return; } info.GetReturnValue().Set(value); } //----------------------------------------------------------------------------- // njsPool::GetConnectionsInUse() // Get accessor of "connectionsInUse" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetConnectionsInUse) { njsPool *pool = (njsPool*) ValidateGetter(info); if (!pool) return; if (!pool->IsValid()) { info.GetReturnValue().Set(Nan::Undefined()); return; } uint32_t value; if (dpiPool_getBusyCount(pool->dpiPoolHandle, &value) < 0) { njsOracledb::ThrowDPIError(); return; } info.GetReturnValue().Set(value); } //----------------------------------------------------------------------------- // njsPool::GetPoolPingInterval() // Get accessor of "poolPingInterval" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetPoolPingInterval) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->poolPingInterval); } //----------------------------------------------------------------------------- // njsPool::GetStmtCacheSize() // Get accessor of "stmtCacheSize" property. //----------------------------------------------------------------------------- NAN_GETTER(njsPool::GetStmtCacheSize) { njsPool *pool = (njsPool*) ValidateGetter(info); if (pool) info.GetReturnValue().Set(pool->stmtCacheSize); } //----------------------------------------------------------------------------- // njsPool::SetPoolMin() // Set accessor of "poolMin" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetPoolMin) { PropertyIsReadOnly("poolMin"); } //----------------------------------------------------------------------------- // njsPool::SetPoolMax() // Set accessor of "poolMax" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetPoolMax) { PropertyIsReadOnly("poolMax"); } //----------------------------------------------------------------------------- // njsPool::SetPoolIncrement() // Set accessor of "poolIncrement" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetPoolIncrement) { PropertyIsReadOnly("poolIncrement"); } //----------------------------------------------------------------------------- // njsPool::SetPoolTimeout() // Set accessor of "poolTimeout" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetPoolTimeout) { PropertyIsReadOnly("poolTimeout"); } //----------------------------------------------------------------------------- // njsPool::SetConnectionsOpen() // Set accessor of "connectionsOpen" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetConnectionsOpen) { PropertyIsReadOnly("connectionsOpen"); } //----------------------------------------------------------------------------- // njsPool::SetConnectionsInUse() // Set accessor of "connectionsInUse" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetConnectionsInUse) { PropertyIsReadOnly("connectionsInUse"); } //----------------------------------------------------------------------------- // njsPool::SetPoolPingInterval() // Set accessor of "stmtCacheSize" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetPoolPingInterval) { PropertyIsReadOnly("poolPingInterval"); } //----------------------------------------------------------------------------- // njsPool::SetStmtCacheSize() // Set accessor of "stmtCacheSize" property. //----------------------------------------------------------------------------- NAN_SETTER(njsPool::SetStmtCacheSize) { PropertyIsReadOnly("stmtCacheSize"); } //----------------------------------------------------------------------------- // njsPool::GetConnection() // Get a connection from the pool and return it. // // PARAMETERS // - JS callback which will receive (error, connection) //----------------------------------------------------------------------------- NAN_METHOD(njsPool::GetConnection) { njsBaton *baton; njsPool *pool; Local<Object> connProps; pool = (njsPool*) ValidateArgs(info, 2, 2); if (!pool) return; /* Get optional connection properties: argument may have empty json */ if (!pool->GetObjectArg(info, 0, connProps)) return; baton = pool->CreateBaton(info); if (!baton) return; if (baton->error.empty()) { /* Connection Properties: If empty json, values will be empty */ baton->GetStringFromJSON(connProps, "user", 0, baton->user); baton->GetStringFromJSON(connProps, "password", 0, baton->password); baton->jsOracledb.Reset(pool->jsOracledb); njsOracledb *oracledb = baton->GetOracledb(); baton->connClass = oracledb->getConnectionClass(); baton->lobPrefetchSize = pool->lobPrefetchSize; baton->SetDPIPoolHandle(pool->dpiPoolHandle); } baton->QueueWork("GetConnection", Async_GetConnection, Async_AfterGetConnection, 2); } //----------------------------------------------------------------------------- // njsPool::Async_GetConnection() // Worker function for njsPool::GetConnection() method. //----------------------------------------------------------------------------- void njsPool::Async_GetConnection(njsBaton *baton) { dpiConnCreateParams params; dpiContext *context; context = njsOracledb::GetDPIContext(); if (dpiContext_initConnCreateParams(context, &params) < 0) { baton->GetDPIError(); return; } if (!baton->connClass.empty()) { params.connectionClass = baton->connClass.c_str(); params.connectionClassLength = baton->connClass.length(); } if (dpiPool_acquireConnection(baton->dpiPoolHandle, baton->user.empty() ? NULL : baton->user.c_str(), baton->user.empty() ? 0 : baton->user.length(), baton->password.empty () ? NULL : baton->password.c_str(), baton->password.empty () ? 0 : baton->password.length(), &params, &baton->dpiConnHandle) < 0) baton->GetDPIError(); } //----------------------------------------------------------------------------- // njsPool::Async_AfterGetConnection() // Sets up the arguments for the callback to JS. The connection object is // created and passed as the second argument. The first argument is the error // and at this point it is known that no error has taken place. //----------------------------------------------------------------------------- void njsPool::Async_AfterGetConnection(njsBaton *baton, Local<Value> argv[]) { argv[1] = njsConnection::CreateFromBaton(baton); } //----------------------------------------------------------------------------- // njsPool::Close() // Close the pool. The reference to the DPI handle is transferred to the // baton so that it will cleared automatically upon success and so that the // pool is marked as invalid immediately. // // PARAMETERS // - JS callback which will receive (error) //----------------------------------------------------------------------------- NAN_METHOD(njsPool::Close) { njsBaton *baton; njsPool *pool; pool = (njsPool*) ValidateArgs(info, 2, 2); if (!pool) return; baton = pool->CreateBaton(info); if (!baton) return; baton->GetBoolFromJSON(info[0].As<Object>(), "forceClose", 0, &baton->force); baton->dpiPoolHandle = pool->dpiPoolHandle; pool->dpiPoolHandle = NULL; baton->QueueWork("Close", Async_Close, NULL, 1); } //----------------------------------------------------------------------------- // njsPool::Async_Close() // Worker function for njsPool::Close() method. If the attempt to // close the pool fails, the reference to the DPI handle is transferred back // from the baton to the pool. //----------------------------------------------------------------------------- void njsPool::Async_Close(njsBaton *baton) { dpiPoolCloseMode mode = (baton->force) ? DPI_MODE_POOL_CLOSE_FORCE : DPI_MODE_POOL_CLOSE_DEFAULT; if (dpiPool_close(baton->dpiPoolHandle, mode) < 0) { njsPool *pool = (njsPool*) baton->callingObj; pool->dpiPoolHandle = baton->dpiPoolHandle; baton->dpiPoolHandle = NULL; baton->GetDPIError(); } }
mrtequino/JSW
nodejs/BIGDATA/node_modules/oracledb/src/njsPool.cpp
C++
apache-2.0
17,291
namespace QI4N.Framework { using System; public interface TransientBuilderFactory { T NewTransient<T>(); TransientBuilder<T> NewTransientBuilder<T>(); TransientBuilder<object> NewTransientBuilder(Type fragmentType); } }
rogeralsing/qi4n
QI4N.Framework/Transient/TransientBuilderFactory.cs
C#
apache-2.0
262
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * Inspection that reports unresolved and unused references. * You can inject logic to mark some unused imports as used. See extension points in this package. * @author Ilya.Kazakevich */ package vgrechka.phizdetsidea.phizdets.inspections.unresolvedReference;
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/inspections/unresolvedReference/package-info.java
Java
apache-2.0
871
'use strict'; var React = require('react'), coreViews = require('../../core/views'), mixins = require('../mixins'); var Map = React.createBackboneClass({ mixins: [ mixins.LayersMixin() ], componentDidMount: function() { this.mapView = new coreViews.MapView({ el: '#map' }); }, componentWillUnmount: function() { this.mapView.destroy(); }, componentDidUpdate: function() { var model = this.getActiveLayer(); this.mapView.clearLayers(); if (model) { this.mapView.addLayer(model.getLeafletLayer(), model.getBounds()); this.mapView.fitBounds(model.getBounds()); } }, render: function() { return ( <div id="map-container"> <div id="map"></div> </div> ); } }); module.exports = Map;
kdeloach/raster-foundry
src/rf/js/src/home/components/map.js
JavaScript
apache-2.0
888
/* * Copyright 2012-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. */ package com.amazonaws.services.cloudwatchevents.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Contains the parameters needed for you to provide custom input to a target based on one or more pieces of data * extracted from the event. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/InputTransformer" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InputTransformer implements Serializable, Cloneable, StructuredPojo { /** * <p> * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON path. * </p> */ private java.util.Map<String, String> inputPathsMap; /** * <p> * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the data * sent to the target. * </p> */ private String inputTemplate; /** * <p> * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON path. * </p> * * @return Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON * path. */ public java.util.Map<String, String> getInputPathsMap() { return inputPathsMap; } /** * <p> * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON path. * </p> * * @param inputPathsMap * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON * path. */ public void setInputPathsMap(java.util.Map<String, String> inputPathsMap) { this.inputPathsMap = inputPathsMap; } /** * <p> * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON path. * </p> * * @param inputPathsMap * Map of JSON paths to be extracted from the event. These are key-value pairs, where each value is a JSON * path. * @return Returns a reference to this object so that method calls can be chained together. */ public InputTransformer withInputPathsMap(java.util.Map<String, String> inputPathsMap) { setInputPathsMap(inputPathsMap); return this; } public InputTransformer addInputPathsMapEntry(String key, String value) { if (null == this.inputPathsMap) { this.inputPathsMap = new java.util.HashMap<String, String>(); } if (this.inputPathsMap.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.inputPathsMap.put(key, value); return this; } /** * Removes all the entries added into InputPathsMap. * * @return Returns a reference to this object so that method calls can be chained together. */ public InputTransformer clearInputPathsMapEntries() { this.inputPathsMap = null; return this; } /** * <p> * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the data * sent to the target. * </p> * * @param inputTemplate * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the * data sent to the target. */ public void setInputTemplate(String inputTemplate) { this.inputTemplate = inputTemplate; } /** * <p> * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the data * sent to the target. * </p> * * @return Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the * data sent to the target. */ public String getInputTemplate() { return this.inputTemplate; } /** * <p> * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the data * sent to the target. * </p> * * @param inputTemplate * Input template where you can use the values of the keys from <code>InputPathsMap</code> to customize the * data sent to the target. * @return Returns a reference to this object so that method calls can be chained together. */ public InputTransformer withInputTemplate(String inputTemplate) { setInputTemplate(inputTemplate); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInputPathsMap() != null) sb.append("InputPathsMap: ").append(getInputPathsMap()).append(","); if (getInputTemplate() != null) sb.append("InputTemplate: ").append(getInputTemplate()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof InputTransformer == false) return false; InputTransformer other = (InputTransformer) obj; if (other.getInputPathsMap() == null ^ this.getInputPathsMap() == null) return false; if (other.getInputPathsMap() != null && other.getInputPathsMap().equals(this.getInputPathsMap()) == false) return false; if (other.getInputTemplate() == null ^ this.getInputTemplate() == null) return false; if (other.getInputTemplate() != null && other.getInputTemplate().equals(this.getInputTemplate()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInputPathsMap() == null) ? 0 : getInputPathsMap().hashCode()); hashCode = prime * hashCode + ((getInputTemplate() == null) ? 0 : getInputTemplate().hashCode()); return hashCode; } @Override public InputTransformer clone() { try { return (InputTransformer) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cloudwatchevents.model.transform.InputTransformerMarshaller.getInstance().marshall(this, protocolMarshaller); } }
dagnir/aws-sdk-java
aws-java-sdk-events/src/main/java/com/amazonaws/services/cloudwatchevents/model/InputTransformer.java
Java
apache-2.0
7,772
<link href="<?php echo base_url('html/css/module/leocamera/style.css');?>" rel="stylesheet" type="text/css"> <div class="leocamera_container" > <div id="leo-camera" class="camera_wrap" > <div data-thumb="http://demo4leotheme.com/prestashop/leo_metro/cache/cachefs/leocamera/180_90_sample-2.jpg" data-src="http://demo4leotheme.com/prestashop/leo_metro/cache/cachefs/leocamera/940_438_sample-2.jpg" data-link="#"> <div class="camera_caption fadeFromBottom" > <div> <div class="leo_camera_title"> <a href="#" title="Sample 2"> Sample 2 </a> </div> <div class="leo_camara_desc"> Lorem ipsum dolor sit amet consectetur adipiscing quis habitant morbi tristique senectus et netus et malesuada fames </div> </div> </div> </div> <div data-thumb="http://demo4leotheme.com/prestashop/leo_metro/cache/cachefs/leocamera/180_90_sample-1.jpg" data-src="http://demo4leotheme.com/prestashop/leo_metro/cache/cachefs/leocamera/940_438_sample-1.jpg" data-link="#"> <div class="camera_caption fadeFromBottom" > <div> <div class="leo_camera_title"> <a href="#" title="Sample 2"> Sample 2 </a> </div> <div class="leo_camara_desc"> Lorem ipsum dolor sit amet consectetur adipiscing quis habitant morbi tristique senectus et netus et malesuada fames </div> </div> </div> </div> </div> </div> <script> $(document).ready(function() { $('#leo-camera').camera({ height:'438px', alignment : 'center', autoAdvance : true, barDirection : 'leftToRight', barPosition : 'bottom', cols : 6, easing : 'easeInOutExpo', fx : 'random', hover : false, loader : 'pie', navigation : false, navigationHover : true, pagination : false, playPause : false, pauseOnClick : false, thumbnails : false, time : 7000, transPeriod : 1500 } ); } ); </script>
iceriver102/php
Website/application/views/leocamera.php
PHP
apache-2.0
2,433
/* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package springfox.test.contract.swagger.models; public class SameFancyPet extends SamePet { private SameCategory extendedCategory; public SameCategory getExtendedCategory() { return extendedCategory; } public void setExtendedCategory(SameCategory extendedCategories) { this.extendedCategory = extendedCategories; } }
springfox/springfox
swagger-contract-tests/src/main/java/springfox/test/contract/swagger/models/SameFancyPet.java
Java
apache-2.0
976
--TEST-- FLOAT implementation test --SKIPIF-- <?php require_once(dirname(__FILE__) . '/skipif.inc'); ?> --FILE-- <?php require_once(dirname(__FILE__) . '/config.inc'); $db = new PDO($dsn, $username, $password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $db->exec ("DROP KEYSPACE {$keyspace}"); } catch (PDOException $e) {} $db->exec ("CREATE KEYSPACE {$keyspace} WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor': 1}"); $db->exec ("USE {$keyspace}"); $db->exec ("CREATE COLUMNFAMILY cf (my_key int PRIMARY KEY, my_float float, my_double double)"); function insert_in_base($db, $key, $value, $type = 0) { $stmt = ''; if ($type == 0) { $stmt = $db->prepare ("UPDATE cf SET my_float=:my_float WHERE my_key=:my_key;"); $stmt->bindValue (':my_float', $value, PDO::PARAM_INT); } else { $stmt = $db->prepare ("UPDATE cf SET my_double=:my_double WHERE my_key=:my_key;"); $stmt->bindValue (':my_double', $value, PDO::PARAM_INT); } $stmt->bindValue (':my_key', $key, PDO::PARAM_INT); $stmt->execute(); } function dump_value($db, $key, $type = 0) { $stmt = $db->prepare("SELECT * FROM cf WHERE my_key=:my_key"); $stmt->bindValue (':my_key', $key, PDO::PARAM_INT); $stmt->execute(); $res = $stmt->fetchAll(); if ($type == 0) var_dump($res[0]['my_float']); else var_dump($res[0]['my_double']); } // Float insertions insert_in_base($db, 21, 42.42); insert_in_base($db, 22, -42.42); insert_in_base($db, 23, -4242); insert_in_base($db, 24, +4242); insert_in_base($db, 25, -4.39518E+7); insert_in_base($db, 26, 4.39518E+7); dump_value($db, 21); dump_value($db, 22); dump_value($db, 23); dump_value($db, 24); dump_value($db, 25); dump_value($db, 26); // Double insertions insert_in_base($db, 26, 4.395181234567E+73, 1); insert_in_base($db, 27, -4.395181234567E+73, 1); dump_value($db, 26, 1); dump_value($db, 27, 1); --EXPECT-- float(42.419998168945) float(-42.419998168945) float(-4242) float(4242) float(-43951800) float(43951800) float(4.395181234567E+73) float(-4.395181234567E+73)
Orange-OpenSource/YACassandraPDO
tests/033-float.phpt
PHP
apache-2.0
2,105
@extends('layouts.layout') @section('content') <div class="title">Be right back.</div>@endsection
sillywiz/Pizza-Narza
resources/views/errors/503.blade.php
PHP
apache-2.0
98
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/pubsublite/v1/topic_stats.proto #include "google/cloud/pubsublite/internal/topic_stats_auth_decorator.h" #include <google/cloud/pubsublite/v1/topic_stats.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace pubsublite_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN TopicStatsServiceAuth::TopicStatsServiceAuth( std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth, std::shared_ptr<TopicStatsServiceStub> child) : auth_(std::move(auth)), child_(std::move(child)) {} StatusOr<google::cloud::pubsublite::v1::ComputeMessageStatsResponse> TopicStatsServiceAuth::ComputeMessageStats( grpc::ClientContext& context, google::cloud::pubsublite::v1::ComputeMessageStatsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ComputeMessageStats(context, request); } StatusOr<google::cloud::pubsublite::v1::ComputeHeadCursorResponse> TopicStatsServiceAuth::ComputeHeadCursor( grpc::ClientContext& context, google::cloud::pubsublite::v1::ComputeHeadCursorRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ComputeHeadCursor(context, request); } StatusOr<google::cloud::pubsublite::v1::ComputeTimeCursorResponse> TopicStatsServiceAuth::ComputeTimeCursor( grpc::ClientContext& context, google::cloud::pubsublite::v1::ComputeTimeCursorRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ComputeTimeCursor(context, request); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsublite_internal } // namespace cloud } // namespace google
googleapis/google-cloud-cpp
google/cloud/pubsublite/internal/topic_stats_auth_decorator.cc
C++
apache-2.0
2,452
<?php /** * @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com) */ namespace Magento\Eav\Model\Entity\Attribute\Source; class Table extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource { /** * Default values for option cache * * @var array */ protected $_optionsDefault = []; /** * Core data * * @var \Magento\Core\Helper\Data */ protected $_coreData = null; /** * @var \Magento\Eav\Model\Resource\Entity\Attribute\Option\CollectionFactory */ protected $_attrOptionCollectionFactory; /** * @var \Magento\Eav\Model\Resource\Entity\Attribute\OptionFactory */ protected $_attrOptionFactory; /** * @param \Magento\Core\Helper\Data $coreData * @param \Magento\Eav\Model\Resource\Entity\Attribute\Option\CollectionFactory $attrOptionCollectionFactory * @param \Magento\Eav\Model\Resource\Entity\Attribute\OptionFactory $attrOptionFactory */ public function __construct( \Magento\Core\Helper\Data $coreData, \Magento\Eav\Model\Resource\Entity\Attribute\Option\CollectionFactory $attrOptionCollectionFactory, \Magento\Eav\Model\Resource\Entity\Attribute\OptionFactory $attrOptionFactory ) { $this->_coreData = $coreData; $this->_attrOptionCollectionFactory = $attrOptionCollectionFactory; $this->_attrOptionFactory = $attrOptionFactory; } /** * Retrieve Full Option values array * * @param bool $withEmpty Add empty option to array * @param bool $defaultValues * @return array */ public function getAllOptions($withEmpty = true, $defaultValues = false) { $storeId = $this->getAttribute()->getStoreId(); if (!is_array($this->_options)) { $this->_options = []; } if (!is_array($this->_optionsDefault)) { $this->_optionsDefault = []; } if (!isset($this->_options[$storeId])) { $collection = $this->_attrOptionCollectionFactory->create()->setPositionOrder( 'asc' )->setAttributeFilter( $this->getAttribute()->getId() )->setStoreFilter( $this->getAttribute()->getStoreId() )->load(); $this->_options[$storeId] = $collection->toOptionArray(); $this->_optionsDefault[$storeId] = $collection->toOptionArray('default_value'); } $options = $defaultValues ? $this->_optionsDefault[$storeId] : $this->_options[$storeId]; if ($withEmpty) { array_unshift($options, ['label' => '', 'value' => '']); } return $options; } /** * Retrieve Option values array by ids * * @param string|array $ids * @param bool $withEmpty Add empty option to array * @return array */ public function getSpecificOptions($ids, $withEmpty = true) { $options = $this->_attrOptionCollectionFactory->create() ->setPositionOrder('asc') ->setAttributeFilter($this->getAttribute()->getId()) ->addFieldToFilter('main_table.option_id', ['in' => $ids]) ->setStoreFilter($this->getAttribute()->getStoreId()) ->load() ->toOptionArray(); if ($withEmpty) { array_unshift($options, ['label' => '', 'value' => '']); } return $options; } /** * Get a text for option value * * @param string|integer $value * @return array|string|bool */ public function getOptionText($value) { $isMultiple = false; if (strpos($value, ',')) { $isMultiple = true; $value = explode(',', $value); } $options = $this->getSpecificOptions($value, false); if ($isMultiple) { $values = []; foreach ($options as $item) { if (in_array($item['value'], $value)) { $values[] = $item['label']; } } return $values; } foreach ($options as $item) { if ($item['value'] == $value) { return $item['label']; } } return false; } /** * Add Value Sort To Collection Select * * @param \Magento\Eav\Model\Entity\Collection\AbstractCollection $collection * @param string $dir * * @return $this */ public function addValueSortToCollection($collection, $dir = \Magento\Framework\DB\Select::SQL_ASC) { $valueTable1 = $this->getAttribute()->getAttributeCode() . '_t1'; $valueTable2 = $this->getAttribute()->getAttributeCode() . '_t2'; $collection->getSelect()->joinLeft( [$valueTable1 => $this->getAttribute()->getBackend()->getTable()], "e.entity_id={$valueTable1}.entity_id" . " AND {$valueTable1}.attribute_id='{$this->getAttribute()->getId()}'" . " AND {$valueTable1}.store_id=0", [] )->joinLeft( [$valueTable2 => $this->getAttribute()->getBackend()->getTable()], "e.entity_id={$valueTable2}.entity_id" . " AND {$valueTable2}.attribute_id='{$this->getAttribute()->getId()}'" . " AND {$valueTable2}.store_id='{$collection->getStoreId()}'", [] ); $valueExpr = $collection->getSelect()->getAdapter()->getCheckSql( "{$valueTable2}.value_id > 0", "{$valueTable2}.value", "{$valueTable1}.value" ); $this->_attrOptionFactory->create()->addOptionValueToCollection( $collection, $this->getAttribute(), $valueExpr ); $collection->getSelect()->order("{$this->getAttribute()->getAttributeCode()} {$dir}"); return $this; } /** * Retrieve Column(s) for Flat * * @return array */ public function getFlatColumns() { $columns = []; $attributeCode = $this->getAttribute()->getAttributeCode(); $isMulti = $this->getAttribute()->getFrontend()->getInputType() == 'multiselect'; $type = $isMulti ? \Magento\Framework\DB\Ddl\Table::TYPE_TEXT : \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER; $columns[$attributeCode] = [ 'type' => $type, 'length' => $isMulti ? '255' : null, 'unsigned' => false, 'nullable' => true, 'default' => null, 'extra' => null, 'comment' => $attributeCode . ' column', ]; if (!$isMulti) { $columns[$attributeCode . '_value'] = [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 'length' => 255, 'unsigned' => false, 'nullable' => true, 'default' => null, 'extra' => null, 'comment' => $attributeCode . ' column', ]; } return $columns; } /** * Retrieve Indexes for Flat * * @return array */ public function getFlatIndexes() { $indexes = []; $index = sprintf('IDX_%s', strtoupper($this->getAttribute()->getAttributeCode())); $indexes[$index] = ['type' => 'index', 'fields' => [$this->getAttribute()->getAttributeCode()]]; $sortable = $this->getAttribute()->getUsedForSortBy(); if ($sortable && $this->getAttribute()->getFrontend()->getInputType() != 'multiselect') { $index = sprintf('IDX_%s_VALUE', strtoupper($this->getAttribute()->getAttributeCode())); $indexes[$index] = [ 'type' => 'index', 'fields' => [$this->getAttribute()->getAttributeCode() . '_value'], ]; } return $indexes; } /** * Retrieve Select For Flat Attribute update * * @param int $store * @return \Magento\Framework\DB\Select|null */ public function getFlatUpdateSelect($store) { return $this->_attrOptionFactory->create()->getFlatUpdateSelect($this->getAttribute(), $store); } }
webadvancedservicescom/magento
app/code/Magento/Eav/Model/Entity/Attribute/Source/Table.php
PHP
apache-2.0
8,190
/* 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.flowable.engine.impl.persistence.cache; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.flowable.engine.common.impl.persistence.entity.Entity; /** * @author Joram Barrez */ public class EntityCacheImpl implements EntityCache { protected Map<Class<?>, Map<String, CachedEntity>> cachedObjects = new HashMap<Class<?>, Map<String,CachedEntity>>(); @Override public CachedEntity put(Entity entity, boolean storeState) { Map<String, CachedEntity> classCache = cachedObjects.get(entity.getClass()); if (classCache == null) { classCache = new HashMap<String, CachedEntity>(); cachedObjects.put(entity.getClass(), classCache); } CachedEntity cachedObject = new CachedEntity(entity, storeState); classCache.put(entity.getId(), cachedObject); return cachedObject; } @Override @SuppressWarnings("unchecked") public <T> T findInCache(Class<T> entityClass, String id) { CachedEntity cachedObject = null; Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache == null) { classCache = findClassCacheByCheckingSubclasses(entityClass); } if (classCache != null) { cachedObject = classCache.get(id); } if (cachedObject != null) { return (T) cachedObject.getEntity(); } return null; } protected Map<String, CachedEntity> findClassCacheByCheckingSubclasses(Class<?> entityClass) { for (Class<?> clazz : cachedObjects.keySet()) { if (entityClass.isAssignableFrom(clazz)) { return cachedObjects.get(clazz); } } return null; } @Override public void cacheRemove(Class<?> entityClass, String entityId) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache == null) { return; } classCache.remove(entityId); } @Override public <T> Collection<CachedEntity> findInCacheAsCachedObjects(Class<T> entityClass) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache != null) { return classCache.values(); } return null; } @Override @SuppressWarnings("unchecked") public <T> List<T> findInCache(Class<T> entityClass) { Map<String, CachedEntity> classCache = cachedObjects.get(entityClass); if (classCache == null) { classCache = findClassCacheByCheckingSubclasses(entityClass); } if (classCache != null) { List<T> entities = new ArrayList<T>(classCache.size()); for (CachedEntity cachedObject : classCache.values()) { entities.add((T) cachedObject.getEntity()); } return entities; } return Collections.emptyList(); } public Map<Class<?>, Map<String, CachedEntity>> getAllCachedEntities() { return cachedObjects; } @Override public void close() { } @Override public void flush() { } }
motorina0/flowable-engine
modules/flowable-engine/src/main/java/org/flowable/engine/impl/persistence/cache/EntityCacheImpl.java
Java
apache-2.0
3,610
/* *===================================================================== * This file is part of JSatTrak. * * Copyright 2007-2013 Shawn E. Gano * * 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 name.gano.math.nonlinsolvers; /** * * @author Shawn */ public class TestDC implements NonLinearEquationSystemProblem { // main function public static void main(String args[]) { TestDC prob = new TestDC(); double[] fgoals = new double[] {0.0,0.0}; double[] X0 = new double[] {0,0}; //NonLinearEquationSystemSolver dc = new ModifiedNewtonFiniteDiffSolver(prob, fgoals, X0); NonLinearEquationSystemSolver dc = new ModifiedBroydenSolver(prob, fgoals, X0); dc.setVerbose(true); dc.solve(); System.out.println("\n" + dc.getOutputMessage()); } public double[] evaluateSystemOfEquations(double[] x) { double[] f = new double[2]; // f[0] = Math.sin(x[0]); // f[1] = Math.cos(x[1]) + 0.0; // f[0] = -2.0*x[0] + 3.0*x[1] -8.0; // f[1] = 3.0*x[0] - 1.0*x[1] + 5.0; // f[0] = x[0] - x[1]*x[1]; // f[1] = -2.0*x[0]*x[1] + 2.0*x[1]; // himmelblau // f[0] = 4*x[0]*x[0]*x[0] + 4*x[0]*x[1]+2*x[1]*x[1] - 42*x[0] -14; // f[1] = 4*x[1]*x[1]*x[1] + 4*x[0]*x[1]+2*x[0]*x[0] - 26*x[1] -22; // Ferrais f[0] = 0.25/Math.PI*x[1]+0.5*x[0]-0.5*Math.sin(x[0]*x[1]); f[1] = Math.E/Math.PI*x[1]-2*Math.E*x[0]+(1-0.25/Math.PI)*(Math.exp(2*x[0])-Math.E); return f; } }
rrr6399/JSatTrakLib
src/name/gano/math/nonlinsolvers/TestDC.java
Java
apache-2.0
2,369
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.TagsOperationParameters; import org.ovirt.engine.core.common.businessentities.Tags; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public class AddTagCommand<T extends TagsOperationParameters> extends TagsCommandOperationBase<T> { public AddTagCommand(T parameters) { super(parameters); } @Override protected void executeCommand() { DbFacade.getInstance().getTagDao().save(getTag()); TagsDirector.getInstance().addTag(getTag()); setSucceeded(true); } @Override protected boolean validate() { Tags tag = DbFacade.getInstance().getTagDao() .getByName(getParameters().getTag().getTagName()); if (tag != null) { addValidationMessage(EngineMessage.TAGS_SPECIFY_TAG_IS_IN_USE); return false; } return true; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_ADD_TAG : AuditLogType.USER_ADD_TAG_FAILED; } }
OpenUniversity/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/AddTagCommand.java
Java
apache-2.0
1,202
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pivotal.strepsirrhini.chaosloris.web; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; /** * Input for schedule creation */ public final class ScheduleCreateInput { @NotNull private final String expression; @NotNull private final String name; @JsonCreator ScheduleCreateInput(@JsonProperty("expression") String expression, @JsonProperty("name") String name) { this.expression = expression; this.name = name; } String getExpression() { return this.expression; } String getName() { return this.name; } }
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ScheduleCreateInput.java
Java
apache-2.0
1,325
const FormatNumber = (value) => { return value.toLocaleString("en-GB", { minimumFractionDigits: 2 }); }; export default FormatNumber;
martincostello/credit-card-splitter
src/Helpers.js
JavaScript
apache-2.0
137
package org.turbogwt.mvp; import com.google.gwt.user.client.ui.Composite; /** * Abstract class for every View in the TurboGWT-MVP framework. * <p> * It provides access to its Presenter via the {@link #getPresenter} method. * * @param <P> the Presenter that is attached to this View, whenever it is displayed * * @author Danilo Reinert */ public abstract class AbstractView<P extends Presenter> extends Composite implements View<P> { private P presenter; public P getPresenter() { if (presenter == null) { throw new IllegalStateException("Presenter is not set. The Presenter must attach itself to the View via " + "#setPresenter, before the View can use it."); } return presenter; } public void setPresenter(P presenter) { this.presenter = presenter; } }
growbit/turbogwt
turbogwt-mvp/src/main/java/org/turbogwt/mvp/AbstractView.java
Java
apache-2.0
851
/* * 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. */ #include <aws/securityhub/model/ComplianceStatus.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { namespace ComplianceStatusMapper { static const int PASSED_HASH = HashingUtils::HashString("PASSED"); static const int WARNING_HASH = HashingUtils::HashString("WARNING"); static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int NOT_AVAILABLE_HASH = HashingUtils::HashString("NOT_AVAILABLE"); ComplianceStatus GetComplianceStatusForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == PASSED_HASH) { return ComplianceStatus::PASSED; } else if (hashCode == WARNING_HASH) { return ComplianceStatus::WARNING; } else if (hashCode == FAILED_HASH) { return ComplianceStatus::FAILED; } else if (hashCode == NOT_AVAILABLE_HASH) { return ComplianceStatus::NOT_AVAILABLE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ComplianceStatus>(hashCode); } return ComplianceStatus::NOT_SET; } Aws::String GetNameForComplianceStatus(ComplianceStatus enumValue) { switch(enumValue) { case ComplianceStatus::PASSED: return "PASSED"; case ComplianceStatus::WARNING: return "WARNING"; case ComplianceStatus::FAILED: return "FAILED"; case ComplianceStatus::NOT_AVAILABLE: return "NOT_AVAILABLE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ComplianceStatusMapper } // namespace Model } // namespace SecurityHub } // namespace Aws
cedral/aws-sdk-cpp
aws-cpp-sdk-securityhub/source/model/ComplianceStatus.cpp
C++
apache-2.0
3,007
<?php /** * * @package Google_Api_Ads_AdWords_v201605 * @subpackage v201605 */ class BatchJobServiceMutateResponse { const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605"; const XSI_TYPE = ""; /** * @access public * @var BatchJobReturnValue */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } }
SonicGD/google-adwords-api-light
Google/Api/Ads/AdWords/v201605/classes/BatchJobServiceMutateResponse.php
PHP
apache-2.0
797
import React, { PureComponent, ReactNode, ComponentType } from 'react'; import { captureException } from '@sentry/browser'; import { Alert } from '../Alert/Alert'; import { ErrorWithStack } from './ErrorWithStack'; export interface ErrorInfo { componentStack: string; } export interface ErrorBoundaryApi { error: Error | null; errorInfo: ErrorInfo | null; } interface Props { children: (r: ErrorBoundaryApi) => ReactNode; } interface State { error: Error | null; errorInfo: ErrorInfo | null; } export class ErrorBoundary extends PureComponent<Props, State> { readonly state: State = { error: null, errorInfo: null, }; componentDidCatch(error: Error, errorInfo: ErrorInfo) { captureException(error, { contexts: { react: { componentStack: errorInfo.componentStack } } }); this.setState({ error: error, errorInfo: errorInfo, }); } render() { const { children } = this.props; const { error, errorInfo } = this.state; return children({ error, errorInfo, }); } } /** * Props for the ErrorBoundaryAlert component * * @public */ export interface ErrorBoundaryAlertProps { /** Title for the error boundary alert */ title?: string; /** Component to be wrapped with an error boundary */ children: ReactNode; /** 'page' will render full page error with stacktrace. 'alertbox' will render an <Alert />. Default 'alertbox' */ style?: 'page' | 'alertbox'; } export class ErrorBoundaryAlert extends PureComponent<ErrorBoundaryAlertProps> { static defaultProps: Partial<ErrorBoundaryAlertProps> = { title: 'An unexpected error happened', style: 'alertbox', }; render() { const { title, children, style } = this.props; return ( <ErrorBoundary> {({ error, errorInfo }) => { if (!errorInfo) { return children; } if (style === 'alertbox') { return ( <Alert title={title || ''}> <details style={{ whiteSpace: 'pre-wrap' }}> {error && error.toString()} <br /> {errorInfo.componentStack} </details> </Alert> ); } return <ErrorWithStack title={title || ''} error={error} errorInfo={errorInfo} />; }} </ErrorBoundary> ); } } /** * HOC for wrapping a component in an error boundary. * * @param Component - the react component to wrap in error boundary * @param errorBoundaryProps - error boundary options * * @public */ export function withErrorBoundary<P = {}>( Component: ComponentType<P>, errorBoundaryProps: Omit<ErrorBoundaryAlertProps, 'children'> = {} ): ComponentType<P> { const comp = (props: P) => ( <ErrorBoundaryAlert {...errorBoundaryProps}> <Component {...props} /> </ErrorBoundaryAlert> ); comp.displayName = 'WithErrorBoundary'; return comp; }
teamsaas/meq
ui/src/packages/datav-core/src/ui/components/ErrorBoundary/ErrorBoundary.tsx
TypeScript
apache-2.0
2,940
shared_examples_for 'will be skipped for this record' do |message| it message.to_s do view_context = @view_context || setup_view_context_with_sandbox({}) button = described_class.new(view_context, {}, {'record' => @record}, {}) expect(button.visible?).to be_falsey end end shared_examples_for 'will not be skipped for this record' do |message| it message.to_s do view_context = @view_context || setup_view_context_with_sandbox({}) button = described_class.new(view_context, {}, {'record' => @record}, {}) expect(button.visible?).to be_truthy end end
ManageIQ/manageiq-ui-classic
spec/shared/helpers/application_helper_buttons.rb
Ruby
apache-2.0
583
package redis.clients.jedis; import com.esotericsoftware.reflectasm.MethodAccess; import org.apache.log4j.Logger; import java.util.Map; public abstract class Command { private final static Logger LOG = Logger.getLogger(Command.class); private final static MethodAccess access = MethodAccess .get(ShardedJedis.class); protected ShardedJedisSentinelPool pool; public String set(String key, String value) { return String.valueOf(this.invoke("set", new String[] { key, value }, new Class[] { String.class, String.class })); } public String get(String key) { return String.valueOf(this.invoke("get", new String[] { key }, String.class)); } public long del(String key) { return (long) this.invoke("del", new String[] { key }, String.class); } public String lpopList(String key) { return String.valueOf(this.invoke("lpop", new String[] { key }, String.class)); } public long rpushList(String key, String... values) { return (long) this.invoke("rpush", new Object[] { key, values }, new Class[] { String.class, String[].class }); } public long expire(String key, int time) { return (long) this.invoke("expire", new Object[] { key, time }, new Class[] { String.class, int.class }); } public long hsetnx(String key, String field, String value) { return (long) this.invoke("hsetnx", new String[] { key, field, value }, new Class[] { String.class, String.class, String.class }); } public boolean exist(String key) { return (boolean) this.invoke("exists", new String[] { key }, String.class); } public boolean existInSet(String key, String member) { return (boolean) this.invoke("sismember", new String[] { key, member }, new Class[] { String.class, String.class }); } public long saddSet(String key, String... members) { return (long) this.invoke("sadd", new Object[] { key, members }, new Class[] { String.class, String[].class }); } public long sremSet(String key, String... members) { return (long) this.invoke("srem", new Object[] { key, members }, new Class[] { String.class, String[].class }); } public String spopSet(String key) { return String.valueOf(this.invoke("spop", new Object[] { key }, new Class[] { String.class })); } public long hSet(byte[] key, byte[] field, byte[] value) { return (long) this.invoke("hset", new Object[] { key, field, value }, new Class[] { byte[].class, byte[].class, byte[].class }); } @SuppressWarnings("unchecked") public Map<byte[], byte[]> hGetAll(byte[] key) { return (Map<byte[], byte[]>) this.invoke("hgetAll", new Object[] { key }, new Class[] { byte[].class }); } public byte[] hGet(byte[] key, byte[] field) { return (byte[]) this.invoke("hget", new Object[] { key, field }, new Class[] { byte[].class, byte[].class }); } public long del(byte[] key) { return (long) this.invoke("del", new Object[] { key }, byte[].class); } protected Object invoke(String methodName, Object[] args, Class<?>... parameterTypes) { Object ret = null; ShardedJedis jedis = pool.getResource(); try { /* * Method method = clazz.getMethod(methodName, parameterTypes); ret * = method.invoke(jedis, args); */ ret = access.invoke(jedis, methodName, parameterTypes, args); } catch (Exception e) { LOG.error(e.getMessage(), e); pool.returnBrokenResource(jedis); } finally { pool.returnResource(jedis); } return ret; } }
kelongxhu/jedis-sentinel-pool
src/main/java/redis/clients/jedis/Command.java
Java
apache-2.0
3,425
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.text.identifier; import org.conqat.engine.commons.util.ConQATInputProcessorBase; import org.conqat.engine.core.core.ConQATException; import org.conqat.engine.sourcecode.resource.ITokenElement; import org.conqat.engine.sourcecode.resource.ITokenResource; import org.conqat.engine.sourcecode.resource.TokenElementUtils; import org.conqat.lib.scanner.ETokenType.ETokenClass; import org.conqat.lib.scanner.IToken; /** * Base class for processors working on identifiers. * * @param <T> * the return type of this processor. * * @author $Author: juergens $ * @version $Rev: 35207 $ * @ConQAT.Rating GREEN Hash: 69177F56B4A8847260A2E8EDB12F972C */ public abstract class IdentifierProcessorBase<T> extends ConQATInputProcessorBase<ITokenResource> { /** {@inheritDoc} */ @Override public T process() throws ConQATException { for (ITokenElement element : TokenElementUtils.listTokenElements(input)) { processElement(element); } return obtainResult(); } /** Template method that calculates and returns the processor's result. */ protected abstract T obtainResult(); /** Process a single source element. */ private void processElement(ITokenElement element) throws ConQATException { for (IToken token : element.getTokens(getLogger())) { if (token.getType().getTokenClass() == ETokenClass.IDENTIFIER) { processIdentifier(token.getText()); } } } /** Template method that is called for each identifier. */ protected abstract void processIdentifier(String identifier); }
vimaier/conqat
org.conqat.engine.text/src/org/conqat/engine/text/identifier/IdentifierProcessorBase.java
Java
apache-2.0
2,775
/* * * Autopsy Forensic Browser * * Copyright 2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.commonfilesearch; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.openide.nodes.ChildFactory; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.Sheet; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.datamodel.DisplayableItemNode; import org.sleuthkit.autopsy.datamodel.DisplayableItemNodeVisitor; import org.sleuthkit.autopsy.datamodel.NodeProperty; /** * Node used to indicate the number of matches found with the MD5 children of * this Node. */ final public class InstanceCountNode extends DisplayableItemNode { private static final Logger logger = Logger.getLogger(InstanceCountNode.class.getName()); final private int instanceCount; final private CommonAttributeValueList attributeValues; /** * Create a node with the given number of instances, and the given selection * of metadata. * * @param instanceCount * @param attributeValues */ @NbBundle.Messages({ "InstanceCountNode.displayName=Files with %s instances (%s)" }) public InstanceCountNode(int instanceCount, CommonAttributeValueList attributeValues) { super(Children.create(new CommonAttributeValueNodeFactory(attributeValues.getMetadataList()), true)); this.instanceCount = instanceCount; this.attributeValues = attributeValues; this.setDisplayName(String.format(Bundle.InstanceCountNode_displayName(), Integer.toString(instanceCount), attributeValues.getCommonAttributeListSize())); this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/fileset-icon-16.png"); //NON-NLS } /** * Number of matches found for each of the MD5 children. * * @return int match count */ int getInstanceCount() { return this.instanceCount; } /** * Refresh the node, by dynamically loading in the children when called, and * calling the CommonAttributeValueNodeFactory to generate nodes for the * children in attributeValues. */ public void refresh() { attributeValues.displayDelayedMetadata(); setChildren(Children.create(new CommonAttributeValueNodeFactory(attributeValues.getMetadataList()), true)); } /** * Get a list of metadata for the MD5s which are children of this object. * * @return List<Md5Metadata> */ CommonAttributeValueList getAttributeValues() { return this.attributeValues; } @Override public <T> T accept(DisplayableItemNodeVisitor<T> visitor) { return visitor.visit(this); } @Override public boolean isLeafTypeNode() { return false; } @Override public String getItemType() { return getClass().getName(); } @NbBundle.Messages({"InstanceCountNode.createSheet.noDescription= "}) @Override protected Sheet createSheet() { Sheet sheet = new Sheet(); Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES); if (sheetSet == null) { sheetSet = Sheet.createPropertiesSet(); sheet.put(sheetSet); } final String NO_DESCR = Bundle.InstanceCountNode_createSheet_noDescription(); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_instancesColLbl(), Bundle.CommonFilesSearchResultsViewerTable_instancesColLbl(), NO_DESCR, this.getInstanceCount())); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), NO_DESCR, "")); sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_tagsColLbl1(), Bundle.CommonFilesSearchResultsViewerTable_tagsColLbl1(), NO_DESCR, "")); return sheet; } /** * ChildFactory which builds CommonFileParentNodes from the * CommonAttributeValue metadata models. */ static class CommonAttributeValueNodeFactory extends ChildFactory<String> { /** * List of models, each of which is a parent node matching a single md5, * containing children FileNodes. */ // maps sting version of value to value Object (??) private final Map<String, CommonAttributeValue> metadata; CommonAttributeValueNodeFactory(List<CommonAttributeValue> attributeValues) { this.metadata = new HashMap<>(); Iterator<CommonAttributeValue> iterator = attributeValues.iterator(); while (iterator.hasNext()) { CommonAttributeValue attributeValue = iterator.next(); this.metadata.put(attributeValue.getValue(), attributeValue); } } @Override protected boolean createKeys(List<String> list) { // @@@ We should just use CommonAttributeValue as the key... list.addAll(this.metadata.keySet()); return true; } @Override protected Node createNodeForKey(String attributeValue) { CommonAttributeValue md5Metadata = this.metadata.get(attributeValue); return new CommonAttributeValueNode(md5Metadata); } } }
millmanorama/autopsy
Core/src/org/sleuthkit/autopsy/commonfilesearch/InstanceCountNode.java
Java
apache-2.0
6,850
# Задача 2. Вариант 8. #Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Лао-Цзы. Не забудьте о том, что автор должен быть упомянут на отдельной строке. # Ionova A. K. #30.04.2016 print("Нельзя обожествлять бесов.\n\t\t\t\t\t\t\t\tЛао-цзы") input("Нажмите ENTER для выхода.")
Mariaanisimova/pythonintask
INBa/2015/Ionova_A_K/task_2_8.py
Python
apache-2.0
579
package com.java110.fee.bmo.feeDiscount; import com.alibaba.fastjson.JSONArray; import com.java110.po.feeDiscount.FeeDiscountPo; import org.springframework.http.ResponseEntity; public interface IUpdateFeeDiscountBMO { /** * 修改费用折扣 * add by wuxw * * @param feeDiscountPo * @return */ ResponseEntity<String> update(FeeDiscountPo feeDiscountPo, JSONArray feeDiscountRuleSpecs); }
java110/MicroCommunity
service-fee/src/main/java/com/java110/fee/bmo/feeDiscount/IUpdateFeeDiscountBMO.java
Java
apache-2.0
433
package main import ( "fmt" "github.com/monax/hoard/v8/project" ) func main() { fmt.Println(project.History.MustChangelog()) }
monax/hoard
project/cmd/changelog/main.go
GO
apache-2.0
133
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.openstacknetworking.web; /** * Handles Rest API call from Neutron ML2 plugin. */ import org.onosproject.rest.AbstractWebResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.InputStream; @Path("subnets") public class OpenstackSubnetWebResource extends AbstractWebResource { protected static final Logger log = LoggerFactory .getLogger(OpenstackSubnetWebResource.class); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createSubnet(InputStream input) { return Response.status(Response.Status.OK).build(); } @PUT @Path("{subnetId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response updateSubnet(@PathParam("subnetId") String id, final InputStream input) { return Response.status(Response.Status.OK).build(); } @DELETE @Path("{subnetId}") @Produces(MediaType.APPLICATION_JSON) public Response deleteSubnet(@PathParam("subnetId") String id) { return Response.status(Response.Status.OK).build(); } }
sonu283304/onos
apps/openstacknetworking/web/src/main/java/org/onosproject/openstacknetworking/web/OpenstackSubnetWebResource.java
Java
apache-2.0
2,056
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Extends the Tank Auth Users model with minimal support for groups * * @author John.Wright */ class TA_Groups_Users extends Users { //may be issues if you use table name prefix in config... hasn't been tested //see parent constructor. protected $table_name = 'users'; // user accounts function __construct() { parent::__construct(); } /** * Set group_id for user. * * @param int * @param int * @return bool */ function set_group_id($user_id, $group_id) { $this->db->set('group_id', $group_id); $this->db->where('id', $user_id); $this->db->update($this->table_name); return $this->db->affected_rows() > 0; } }
Sundfjord/rockEnroll
application/models/tank_auth/TA_Groups_Users.php
PHP
apache-2.0
919
<?php /* Smarty version Smarty-3.1.10, created on 2014-07-08 17:30:38 compiled from "D:\phpfind\WWW\themes\default\header.html" */ ?> <?php /*%%SmartyHeaderCode:143353bbba3e25eb53-92782547%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '36a2c2cd7233b83ae477006fde1bfc60f4006267' => array ( 0 => 'D:\\phpfind\\WWW\\themes\\default\\header.html', 1 => 1404555682, 2 => 'file', ), ), 'nocache_hash' => '143353bbba3e25eb53-92782547', 'function' => array ( ), 'variables' => array ( 'site_url' => 0, 'site_title' => 0, 'cate' => 0, 'cfg' => 0, 'site_root' => 0, 'site_path' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.10', 'unifunc' => 'content_53bbba3e5be0a1_32061055', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_53bbba3e5be0a1_32061055')) {function content_53bbba3e5be0a1_32061055($_smarty_tpl) {?> <div id="header"> <div id="topbox"> <a href="<?php echo $_smarty_tpl->tpl_vars['site_url']->value;?> " class="logo" title="<?php echo $_smarty_tpl->tpl_vars['site_title']->value;?> "></a> <div id="sobox"> <form name="sofrm" class="sofrm" method="get" action="" onSubmit="return rewrite_search()"> <input name="mod" type="hidden" id="mod" value="search" /> <input name="type" type="hidden" id="type" value="name" /> <div id="selopt"> <div id="cursel">网站名称</div> <ul id="options"> <li><a href="javascript: void(0);" name="name">网站名称</a></li> </ul> </div> <input name="query" type="text" class="sipt" id="query" onFocus="this.value='';" /><input type="submit" class="sbtn" value="搜 索" /> </form> </div> </div> <div id="navbox"> <ul class="navbar"> <li><a href="?mod=index">首页</a></li><li class="navline"></li> <?php $_smarty_tpl->tpl_vars['cate'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['cate']->_loop = false; $_from = get_categories(); if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['cate']->key => $_smarty_tpl->tpl_vars['cate']->value){ $_smarty_tpl->tpl_vars['cate']->_loop = true; ?> <li><a href="<?php echo $_smarty_tpl->tpl_vars['cate']->value['cate_link'];?> " title="<?php echo $_smarty_tpl->tpl_vars['cate']->value['cate_name'];?> "><?php echo $_smarty_tpl->tpl_vars['cate']->value['cate_name'];?> </a></li><li class="navline"></li> <?php } ?> <li><a href="http://bbs.lxsn.net/" rel="nofollow">站长论坛</a></li><li class="navline"></li> </ul> </div> <div id="txtbox"> <div class="count"><?php echo $_smarty_tpl->tpl_vars['cfg']->value['site_notice'];?> </div> <div class="link">快捷方式:<a href="<?php echo $_smarty_tpl->tpl_vars['site_root']->value;?> member/?mod=website&act=add">站点提交</a> - <a href="<?php echo $_smarty_tpl->tpl_vars['site_root']->value;?> member/?mod=article&act=add">软文投稿</a></div> </div> </div> <div class="sitepath"><?php echo $_smarty_tpl->tpl_vars['site_path']->value;?> </div><?php }} ?>
zhanxizhu/lxsndir
data/compile/default/36a2c2cd7233b83ae477006fde1bfc60f4006267.file.header.html.php
PHP
apache-2.0
3,400
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.application.options.colors; import com.intellij.application.options.EditorFontsConstants; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.FontPreferences; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.*; import com.intellij.ui.components.JBCheckBox; import com.intellij.util.EventDispatcher; import com.intellij.util.ui.JBUI; import net.miginfocom.swing.MigLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; public class FontOptions extends JPanel implements OptionsPanel{ private static final FontInfoRenderer RENDERER = new FontInfoRenderer() { @Override protected boolean isEditorFont() { return true; } }; private final EventDispatcher<ColorAndFontSettingsListener> myDispatcher = EventDispatcher.create(ColorAndFontSettingsListener.class); @NotNull private final ColorAndFontOptions myOptions; @NotNull private final JTextField myEditorFontSizeField = new JTextField(4); @NotNull private final JTextField myLineSpacingField = new JTextField(4); private final FontComboBox myPrimaryCombo = new FontComboBox(); private final JCheckBox myUseSecondaryFontCheckbox = new JCheckBox(ApplicationBundle.message("secondary.font")); private final JCheckBox myEnableLigaturesCheckbox = new JCheckBox(ApplicationBundle.message("use.ligatures")); private final FontComboBox mySecondaryCombo = new FontComboBox(false, false); @NotNull private final JBCheckBox myOnlyMonospacedCheckBox = new JBCheckBox(ApplicationBundle.message("checkbox.show.only.monospaced.fonts")); private boolean myIsInSchemeChange; public FontOptions(@NotNull ColorAndFontOptions options) { setLayout(new MigLayout("ins 0, gap 5, flowx")); myOptions = options; add(myOnlyMonospacedCheckBox, "newline 10, sgx b, sx 2"); add(new JLabel(ApplicationBundle.message("primary.font")), "newline, ax right"); add(myPrimaryCombo, "sgx b"); add(new JLabel(ApplicationBundle.message("editbox.font.size")), "gapleft 20"); add(myEditorFontSizeField); add(new JLabel(ApplicationBundle.message("editbox.line.spacing")), "gapleft 20"); add(myLineSpacingField); add(new JLabel(ApplicationBundle.message("label.fallback.fonts.list.description"), MessageType.INFO.getDefaultIcon(), SwingConstants.LEFT), "newline, sx 5"); add(myUseSecondaryFontCheckbox, "newline, ax right"); add(mySecondaryCombo, "sgx b"); JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); myEnableLigaturesCheckbox.setBorder(null); panel.add(myEnableLigaturesCheckbox); JLabel warningIcon = new JLabel(AllIcons.General.BalloonWarning); IdeTooltipManager.getInstance().setCustomTooltip( warningIcon, new TooltipWithClickableLinks.ForBrowser(warningIcon, ApplicationBundle.message("ligatures.jre.warning", ApplicationNamesInfo.getInstance().getFullProductName()))); warningIcon.setBorder(JBUI.Borders.emptyLeft(5)); updateWarningIconVisibility(warningIcon); panel.add(warningIcon); add(panel, "newline, sx 2"); myOnlyMonospacedCheckBox.setBorder(null); myUseSecondaryFontCheckbox.setBorder(null); mySecondaryCombo.setEnabled(false); myOnlyMonospacedCheckBox.setSelected(EditorColorsManager.getInstance().isUseOnlyMonospacedFonts()); myOnlyMonospacedCheckBox.addActionListener(e -> { EditorColorsManager.getInstance().setUseOnlyMonospacedFonts(myOnlyMonospacedCheckBox.isSelected()); myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected()); mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected()); }); myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected()); myPrimaryCombo.setRenderer(RENDERER); mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected()); mySecondaryCombo.setRenderer(RENDERER); myUseSecondaryFontCheckbox.addActionListener(e -> { mySecondaryCombo.setEnabled(myUseSecondaryFontCheckbox.isSelected()); syncFontFamilies(); }); ItemListener itemListener = this::syncFontFamilies; myPrimaryCombo.addItemListener(itemListener); mySecondaryCombo.addItemListener(itemListener); ActionListener actionListener = this::syncFontFamilies; myPrimaryCombo.addActionListener(actionListener); mySecondaryCombo.addActionListener(actionListener); myEditorFontSizeField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { if (myIsInSchemeChange || !SwingUtilities.isEventDispatchThread()) return; String selectedFont = myPrimaryCombo.getFontName(); if (selectedFont != null) { setFontSize(getFontSizeFromField()); } updateDescription(true); } }); myEditorFontSizeField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return; boolean up = e.getKeyCode() == KeyEvent.VK_UP; try { int value = Integer.parseInt(myEditorFontSizeField.getText()); value += (up ? 1 : -1); value = Math.min(EditorFontsConstants.getMaxEditorFontSize(), Math.max(EditorFontsConstants.getMinEditorFontSize(), value)); myEditorFontSizeField.setText(String.valueOf(value)); } catch (NumberFormatException ignored) { } } }); myLineSpacingField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { if (myIsInSchemeChange) return; float lineSpacing = getLineSpacingFromField(); if (getLineSpacing() != lineSpacing) { setCurrentLineSpacing(lineSpacing); } updateDescription(true); } }); myLineSpacingField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return; boolean up = e.getKeyCode() == KeyEvent.VK_UP; try { float value = Float.parseFloat(myLineSpacingField.getText()); value += (up ? 1 : -1) * .1F; value = Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), value)); myLineSpacingField.setText(String.format(Locale.ENGLISH, "%.1f", value)); } catch (NumberFormatException ignored) { } } }); myEnableLigaturesCheckbox.addActionListener(e -> { getFontPreferences().setUseLigatures(myEnableLigaturesCheckbox.isSelected()); updateWarningIconVisibility(warningIcon); updateDescription(true); }); } private void updateWarningIconVisibility(JLabel warningIcon) { warningIcon.setVisible(!SystemInfo.isJetbrainsJvm && getFontPreferences().useLigatures()); } private int getFontSizeFromField() { try { return Math.min(EditorFontsConstants.getMaxEditorFontSize(), Math.max(EditorFontsConstants.getMinEditorFontSize(), Integer.parseInt(myEditorFontSizeField.getText()))); } catch (NumberFormatException e) { return EditorFontsConstants.getDefaultEditorFontSize(); } } private float getLineSpacingFromField() { try { return Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), Float.parseFloat(myLineSpacingField.getText()))); } catch (NumberFormatException e){ return EditorFontsConstants.getDefaultEditorLineSpacing(); } } /** * Processes an event from {@code FontComboBox} * if it is enabled and its item is selected. * * @param event the event to process */ private void syncFontFamilies(AWTEvent event) { Object source = event.getSource(); if (source instanceof FontComboBox) { FontComboBox combo = (FontComboBox)source; if (combo.isEnabled() && combo.isShowing() && combo.getSelectedItem() != null) { syncFontFamilies(); } } } private void syncFontFamilies() { if (myIsInSchemeChange) { return; } FontPreferences fontPreferences = getFontPreferences(); fontPreferences.clearFonts(); String primaryFontFamily = myPrimaryCombo.getFontName(); String secondaryFontFamily = mySecondaryCombo.isEnabled() ? mySecondaryCombo.getFontName() : null; int fontSize = getFontSizeFromField(); if (primaryFontFamily != null ) { if (!FontPreferences.DEFAULT_FONT_NAME.equals(primaryFontFamily)) { fontPreferences.addFontFamily(primaryFontFamily); } fontPreferences.register(primaryFontFamily, fontSize); } if (secondaryFontFamily != null) { if (!FontPreferences.DEFAULT_FONT_NAME.equals(secondaryFontFamily)){ fontPreferences.addFontFamily(secondaryFontFamily); } fontPreferences.register(secondaryFontFamily, fontSize); } updateDescription(true); } @Override public void updateOptionsList() { myIsInSchemeChange = true; myLineSpacingField.setText(Float.toString(getLineSpacing())); FontPreferences fontPreferences = getFontPreferences(); List<String> fontFamilies = fontPreferences.getEffectiveFontFamilies(); myPrimaryCombo.setFontName(fontPreferences.getFontFamily()); boolean isThereSecondaryFont = fontFamilies.size() > 1; myUseSecondaryFontCheckbox.setSelected(isThereSecondaryFont); mySecondaryCombo.setFontName(isThereSecondaryFont ? fontFamilies.get(1) : null); myEditorFontSizeField.setText(String.valueOf(fontPreferences.getSize(fontPreferences.getFontFamily()))); boolean readOnly = ColorAndFontOptions.isReadOnly(myOptions.getSelectedScheme()); myPrimaryCombo.setEnabled(!readOnly); mySecondaryCombo.setEnabled(isThereSecondaryFont && !readOnly); myOnlyMonospacedCheckBox.setEnabled(!readOnly); myLineSpacingField.setEnabled(!readOnly); myEditorFontSizeField.setEnabled(!readOnly); myUseSecondaryFontCheckbox.setEnabled(!readOnly); myEnableLigaturesCheckbox.setEnabled(!readOnly); myEnableLigaturesCheckbox.setSelected(fontPreferences.useLigatures()); myIsInSchemeChange = false; } @NotNull protected FontPreferences getFontPreferences() { return getCurrentScheme().getFontPreferences(); } protected void setFontSize(int fontSize) { getCurrentScheme().setEditorFontSize(fontSize); } protected float getLineSpacing() { return getCurrentScheme().getLineSpacing(); } protected void setCurrentLineSpacing(float lineSpacing) { getCurrentScheme().setLineSpacing(lineSpacing); } @Override @Nullable public Runnable showOption(final String option) { return null; } @Override public void applyChangesToScheme() { } @Override public void selectOption(final String typeToSelect) { } protected EditorColorsScheme getCurrentScheme() { return myOptions.getSelectedScheme(); } public boolean updateDescription(boolean modified) { EditorColorsScheme scheme = myOptions.getSelectedScheme(); if (modified && ColorAndFontOptions.isReadOnly(scheme)) { return false; } myDispatcher.getMulticaster().fontChanged(); return true; } @Override public void addListener(ColorAndFontSettingsListener listener) { myDispatcher.addListener(listener); } @Override public JPanel getPanel() { return this; } @Override public Set<String> processListOptions() { return new HashSet<>(); } }
youdonghai/intellij-community
platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java
Java
apache-2.0
13,068
package com.example.dagger2_hello_world; import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Named; import dagger.Binds; import dagger.Module; import dagger.Provides; @Module public abstract class ApplicationModule { @Provides @NonNull static Application myApplication() { return Application.getInstance(); } @Binds @NonNull @Named(ApplicationScope.TAG) abstract Context context(Application application); @Binds @NonNull abstract android.app.Application application(Application application); }
ron-k/Dagged2-Hello-World
app/src/main/java/com/example/dagger2_hello_world/ApplicationModule.java
Java
apache-2.0
596
<?php return [ 'interfaces' => [ 'google.ads.googleads.v10.services.AdGroupFeedService' => [ 'MutateAdGroupFeeds' => [ 'method' => 'post', 'uriTemplate' => '/v10/customers/{customer_id=*}/adGroupFeeds:mutate', 'body' => '*', 'placeholders' => [ 'customer_id' => [ 'getters' => [ 'getCustomerId', ], ], ], ], ], 'google.longrunning.Operations' => [ 'CancelOperation' => [ 'method' => 'post', 'uriTemplate' => '/v10/{name=customers/*/operations/*}:cancel', 'body' => '*', 'placeholders' => [ 'name' => [ 'getters' => [ 'getName', ], ], ], ], 'DeleteOperation' => [ 'method' => 'delete', 'uriTemplate' => '/v10/{name=customers/*/operations/*}', 'placeholders' => [ 'name' => [ 'getters' => [ 'getName', ], ], ], ], 'GetOperation' => [ 'method' => 'get', 'uriTemplate' => '/v10/{name=customers/*/operations/*}', 'placeholders' => [ 'name' => [ 'getters' => [ 'getName', ], ], ], ], 'ListOperations' => [ 'method' => 'get', 'uriTemplate' => '/v10/{name=customers/*/operations}', 'placeholders' => [ 'name' => [ 'getters' => [ 'getName', ], ], ], ], 'WaitOperation' => [ 'method' => 'post', 'uriTemplate' => '/v10/{name=customers/*/operations/*}:wait', 'body' => '*', 'placeholders' => [ 'name' => [ 'getters' => [ 'getName', ], ], ], ], ], ], ];
googleads/google-ads-php
src/Google/Ads/GoogleAds/V10/Services/resources/ad_group_feed_service_rest_client_config.php
PHP
apache-2.0
2,554
import React, { Component } from 'react'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames'; class Content extends Component { render() { return ( <KeyboardAwareScrollView automaticallyAdjustContentInsets={false} resetScrollToCoords={(this.props.disableKBDismissScroll) ? null : { x: 0, y: 0 }} ref={(c) => { this._scrollview = c; this._root = c; }} {...this.props} > {this.props.children} </KeyboardAwareScrollView> ); } } Content.propTypes = { ...KeyboardAwareScrollView.propTypes, style: React.PropTypes.object, padder: React.PropTypes.bool, disableKBDismissScroll: React.PropTypes.bool, enableResetScrollToCoords: React.PropTypes.bool }; const StyledContent = connectStyle('NativeBase.Content', {}, mapPropsToStyleNames)(Content); export { StyledContent as Content, };
sampsasaarela/NativeBase
src/basic/Content.js
JavaScript
apache-2.0
1,015
/** * Copyright 2014 Groupon.com * * 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.groupon.vertx.memcache.client.response; /** * Represents a memcache store response. * * @author Stuart Siegrist (fsiegrist at groupon dot com) * @since 3.1.0 */ public final class StoreCommandResponse extends MemcacheCommandResponse { private final String data; private StoreCommandResponse(Builder builder) { super(builder); data = builder.data; } public String getData() { return data; } /** * Builder for the StoreCommandResponse */ public static class Builder extends AbstractBuilder<Builder, StoreCommandResponse> { private String data; @Override protected Builder self() { return this; } public Builder setData(String value) { data = value; return self(); } @Override public StoreCommandResponse build() { return new StoreCommandResponse(this); } } }
groupon/vertx-memcache
src/main/java/com/groupon/vertx/memcache/client/response/StoreCommandResponse.java
Java
apache-2.0
1,563
/* * Copyright 2013, Edmodo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or 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.yuqiaotech.erp.editimage.cropper.util; import android.graphics.RectF; import android.support.annotation.NonNull; /** * Utility class for handling calculations involving a fixed aspect ratio. */ public class AspectRatioUtil { /** * Calculates the aspect ratio given a rectangle. */ public static float calculateAspectRatio(float left, float top, float right, float bottom) { final float width = right - left; final float height = bottom - top; return width / height; } /** * Calculates the aspect ratio given a rectangle. */ public static float calculateAspectRatio(@NonNull RectF rect) { return rect.width() / rect.height(); } /** * Calculates the x-coordinate of the left edge given the other sides of the rectangle and an * aspect ratio. */ public static float calculateLeft(float top, float right, float bottom, float targetAspectRatio) { final float height = bottom - top; // targetAspectRatio = width / height // width = targetAspectRatio * height // right - left = targetAspectRatio * height return right - (targetAspectRatio * height); } /** * Calculates the y-coordinate of the top edge given the other sides of the rectangle and an * aspect ratio. */ public static float calculateTop(float left, float right, float bottom, float targetAspectRatio) { final float width = right - left; // targetAspectRatio = width / height // width = targetAspectRatio * height // height = width / targetAspectRatio // bottom - top = width / targetAspectRatio return bottom - (width / targetAspectRatio); } /** * Calculates the x-coordinate of the right edge given the other sides of the rectangle and an * aspect ratio. */ public static float calculateRight(float left, float top, float bottom, float targetAspectRatio) { final float height = bottom - top; // targetAspectRatio = width / height // width = targetAspectRatio * height // right - left = targetAspectRatio * height return (targetAspectRatio * height) + left; } /** * Calculates the y-coordinate of the bottom edge given the other sides of the rectangle and an * aspect ratio. */ public static float calculateBottom(float left, float top, float right, float targetAspectRatio) { final float width = right - left; // targetAspectRatio = width / height // width = targetAspectRatio * height // height = width / targetAspectRatio // bottom - top = width / targetAspectRatio return (width / targetAspectRatio) + top; } /** * Calculates the width of a rectangle given the top and bottom edges and an aspect ratio. */ public static float calculateWidth(float height, float targetAspectRatio) { return targetAspectRatio * height; } /** * Calculates the height of a rectangle given the left and right edges and an aspect ratio. */ public static float calculateHeight(float width, float targetAspectRatio) { return width / targetAspectRatio; } }
wicloud/crop-image
CropperSample/src/com/yuqiaotech/erp/editimage/cropper/util/AspectRatioUtil.java
Java
apache-2.0
3,853
/** * Malay translation for bootstrap-datetimepicker * Ateman Faiz <noorulfaiz@gmail.com> */ ;(function ($) { $.fn.datetimepicker.dates['ms'] = { days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"], daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"], daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"], months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"], today: "Hari Ini", suffix: [], meridiem: [] }; }(jQuery));
txterm/txsprider
public/static/js/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.ms.js
JavaScript
apache-2.0
715
from fruits import validate_fruit fruits = ["banana", "lemon", "apple", "orange", "batman"] print fruits def list_fruits(fruits, byName=True): if byName: # WARNING: this won't make a copy of the list and return it. It will change the list FOREVER fruits.sort() for index, fruit in enumerate(fruits): if validate_fruit(fruit): print "Fruit nr %d is %s" % (index, fruit) else: print "This %s is no fruit!" % (fruit) list_fruits(fruits) print fruits
Painatalman/python101
sources/101_test.py
Python
apache-2.0
519
package stroom.config.global.impl; import stroom.ui.config.shared.UserPreferences; import java.util.Optional; public interface UserPreferencesDao { Optional<UserPreferences> fetch(String userId); int update(String userId, UserPreferences userPreferences); int delete(String userId); }
gchq/stroom
stroom-config/stroom-config-global-impl/src/main/java/stroom/config/global/impl/UserPreferencesDao.java
Java
apache-2.0
303
package com.cocos2dj.module.btree; import java.util.HashMap; import com.badlogic.gdx.ai.btree.BehaviorTree; import com.badlogic.gdx.ai.btree.Task; import com.badlogic.gdx.ai.btree.branch.Parallel; import com.badlogic.gdx.ai.btree.branch.Parallel.Policy; import com.badlogic.gdx.ai.btree.branch.Selector; import com.badlogic.gdx.ai.btree.branch.Sequence; import com.cocos2dj.macros.CCLog; import com.cocos2dj.module.btree.BhTreeModel.StructBHTNode; import com.cocos2dj.module.btree.BhLeafTask.DebugTask; /** * RcBHT.java * * 不用管类型 * * @author xujun * */ public class BhTree<T> extends BehaviorTree<T> { static final String TAG = "RcBHT"; //fields>> HashMap<String, BhLeafTask<T>> tasksMap = new HashMap<>(); private boolean pauseFlag; //fields<< public void pause() { pauseFlag = true; } public void resume() { pauseFlag = false; } //func>> @SuppressWarnings("unchecked") Task<T> createTask(String type, String name, String args) { switch(type) { case "leaf": BhLeafTask<T> leaf;// = new RcLeafTask<T>(); //相同的name会缓存 if(name != null) { leaf = tasksMap.get(name); if(leaf != null) { CCLog.debug(TAG, "find same leaf task : " + name); return leaf; } if("debug".equals(args)) { leaf = new DebugTask(name); } else { leaf = new BhLeafTask<T>(); } tasksMap.put(name, leaf); return leaf; } else { if("debug".equals(args)) { leaf = new DebugTask(name); } else { leaf = new BhLeafTask<T>(); } } return leaf; case "parallel": if(args == null) { return new Parallel<T>(); } else { switch(args) { case "selector": return new Parallel<T>(Policy.Selector); case "sequence": return new Parallel<T>(Policy.Sequence); } CCLog.error(TAG, "pattern fail args = " + args + " need selector or sequence"); return null; } case "selector": return new Selector<T>(); case "sequence": return new Sequence<T>(); } CCLog.error(TAG, "not found type : " + type); return null; } final Task<T> createTask(StructBHTNode node) { Task<T> ret = createTask(node.type, node.key, node.args); if(ret == null) { CCLog.error(TAG, "createTask fail "); } if(node.children != null) { int len = node.children.length; for(int i = 0; i < len; ++i) { Task<T> child = createTask(node.children[i]); ret.addChild(child); } } return ret; } //func<< //methods>> public void setup(BhTreeModel model) { Task<T> root = createTask(model.root); addChild(root); } public void step() { if(!pauseFlag) { super.step(); } } public BhLeafTask<T> getLeaf(String key) { BhLeafTask<T> ret = tasksMap.get(key); // System.out.println("map = " + tasksMap.toString()); if(ret == null) { CCLog.error(TAG, "task not found : " + key); } return ret; } //methods<< }
mingwuyun/cocos2d-java
external/com/cocos2dj/module/btree/BhTree.java
Java
apache-2.0
2,892
package com.s24.search.solr.response; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.util.ResourceLoader; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.core.SolrResourceLoader; import org.junit.Test; import org.thymeleaf.TemplateEngine; import org.thymeleaf.templateresolver.ITemplateResolver; public class LuceneTemplateResolverIT extends SolrTestCaseJ4 { @Test public void testTemplateResolverConfiguration04() throws Exception { initCore(); ResourceLoader resourceLoader = new SolrResourceLoader(testSolrHome); TemplateEngine templateEngine = new TemplateEngine(); LuceneTemplateResolver templateResolver = new LuceneTemplateResolver(); templateResolver.setResourceLoader(resourceLoader); templateEngine.setTemplateResolver(templateResolver); templateEngine.getConfiguration(); List<ITemplateResolver> templateResolvers = new ArrayList<>(templateEngine.getTemplateResolvers()); assertEquals(1, templateResolvers.size()); assertEquals("com.s24.search.solr.response.LuceneTemplateResolver", templateResolvers.get(0).getName()); } }
shopping24/solr-thymeleaf
src/test/java/com/s24/search/solr/response/LuceneTemplateResolverIT.java
Java
apache-2.0
1,192
/** * Copyright (C) 2016-2018 Harald Kuhn * * 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 rocks.bottery.connector.ms.model; import java.io.Serializable; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /* { "issuer":"https://api.botframework.com", "authorization_endpoint":"https://invalid.botframework.com/", "jwks_uri":"https://login.botframework.com/v1/keys", "id_token_signing_alg_values_supported":["RSA256"], "token_endpoint_auth_methods_supported":["private_key_jwt"] } */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class OpenIdConfig implements Serializable { private static final long serialVersionUID = 1L; @XmlElement(name = "issuer") private String issuer; @XmlElement(name = "authorization_endpoint") private String authorizationEndpoint; @XmlElement(name = "jwks_uri") private String jwksUri; @XmlElement(name = "id_token_signing_alg_values_supported") private List<String> idTokenSigningAlgValuesSupported = null; @XmlElement(name = "token_endpoint_auth_methods_supported") private List<String> tokenEndpointAuthMethodsSupported = null; /** * * @return The issuer */ public String getIssuer() { return issuer; } /** * * @param issuer * The issuer */ public void setIssuer(String issuer) { this.issuer = issuer; } /** * * @return The authorizationEndpoint */ public String getAuthorizationEndpoint() { return authorizationEndpoint; } /** * * @param authorizationEndpoint * The authorization_endpoint */ public void setAuthorizationEndpoint(String authorizationEndpoint) { this.authorizationEndpoint = authorizationEndpoint; } /** * * @return The jwksUri */ public String getJwksUri() { return jwksUri; } /** * * @param jwksUri * The jwks_uri */ public void setJwksUri(String jwksUri) { this.jwksUri = jwksUri; } /** * * @return The idTokenSigningAlgValuesSupported */ public List<String> getIdTokenSigningAlgValuesSupported() { return idTokenSigningAlgValuesSupported; } /** * * @param idTokenSigningAlgValuesSupported * The id_token_signing_alg_values_supported */ public void setIdTokenSigningAlgValuesSupported(List<String> idTokenSigningAlgValuesSupported) { this.idTokenSigningAlgValuesSupported = idTokenSigningAlgValuesSupported; } /** * * @return The tokenEndpointAuthMethodsSupported */ public List<String> getTokenEndpointAuthMethodsSupported() { return tokenEndpointAuthMethodsSupported; } /** * * @param tokenEndpointAuthMethodsSupported * The token_endpoint_auth_methods_supported */ public void setTokenEndpointAuthMethodsSupported(List<String> tokenEndpointAuthMethodsSupported) { this.tokenEndpointAuthMethodsSupported = tokenEndpointAuthMethodsSupported; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OpenIdConfig {\n"); sb.append(" issuer: ").append(toIndentedString(issuer)).append("\n"); sb.append(" authorization_endpoint: ").append(toIndentedString(authorizationEndpoint)).append("\n"); sb.append(" jwksUri: ").append(toIndentedString(jwksUri)).append("\n"); sb.append(" tokenEndpointAuthMethodsSupported: ") .append(toIndentedString(this.tokenEndpointAuthMethodsSupported)).append("\n"); sb.append(" id_token_signing_alg_values_supported: ") .append(toIndentedString(this.idTokenSigningAlgValuesSupported)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
hkuhn42/bottery
bottery.connector.ms/src/main/java/rocks/bottery/connector/ms/model/OpenIdConfig.java
Java
apache-2.0
4,633
package org.rabix.bindings.cwl.bean; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.rabix.bindings.cwl.json.CWLStepsDeserializer; import org.rabix.bindings.model.ValidationReport; import org.rabix.common.json.BeanPropertyView; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(as = CWLWorkflow.class) public class CWLWorkflow extends CWLJobApp { @JsonProperty("steps") @JsonDeserialize(using = CWLStepsDeserializer.class) private List<CWLStep> steps; @JsonProperty("dataLinks") @JsonView(BeanPropertyView.Full.class) private List<CWLDataLink> dataLinks; public CWLWorkflow() { this.steps = new ArrayList<>(); this.dataLinks = new ArrayList<>(); } public CWLWorkflow(List<CWLStep> steps, List<CWLDataLink> dataLinks) { this.steps = steps; this.dataLinks = dataLinks; } @JsonIgnore public void addDataLink(CWLDataLink dataLink) { this.dataLinks.add(dataLink); } @JsonIgnore public void addDataLinks(List<CWLDataLink> dataLinks) { this.dataLinks.addAll(dataLinks); } public List<CWLStep> getSteps() { return steps; } public List<CWLDataLink> getDataLinks() { return dataLinks; } @Override public String toString() { return "Workflow [steps=" + steps + ", dataLinks=" + dataLinks + ", id=" + getId() + ", context=" + getContext() + ", description=" + getDescription() + ", inputs=" + getInputs() + ", outputs=" + getOutputs() + ", requirements=" + requirements + "]"; } @Override @JsonIgnore public CWLJobAppType getType() { return CWLJobAppType.WORKFLOW; } private Set<String> checkStepDuplicates() { Set<String> duplicates = new HashSet<>(); Set<String> ids = new HashSet<>(); for (CWLStep step : steps) { if (!ids.add(step.getId())) { duplicates.add(step.getId()); } } return duplicates; } // private Set<String> unconnectedOutputs() { // // } // // private Set<String> unconnectedSteps() { // // } // // private Set<String> unconnectedInputs() { // // } @Override public ValidationReport validate() { List<ValidationReport.Item> messages = new ArrayList<>(); messages.addAll(ValidationReport.messagesToItems(validatePortUniqueness(), ValidationReport.Severity.ERROR)); for (String duplicate : checkStepDuplicates()) { messages.add(ValidationReport.error("Duplicate step id: " + duplicate)); } if (steps == null || steps.isEmpty()) { messages.add(ValidationReport.error("Workflow has no steps")); } for (CWLStep step : steps) { for (ValidationReport.Item item : step.getApp().validate().getItems()) { messages.add( ValidationReport.item( item.getSeverity() + " from app in step '" + step.getId() + "': " + item.getMessage(), item.getSeverity()) ); } } return new ValidationReport(messages); } }
rabix/bunny
rabix-bindings-cwl/src/main/java/org/rabix/bindings/cwl/bean/CWLWorkflow.java
Java
apache-2.0
3,152
package org.jokar.permissiondispatcher.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Register some methods which permissions are needed. * Created by JokAr on 16/8/22. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) public @interface NeedsPermission { String[] value(); }
a1018875550/PermissionDispatcher
library/src/main/java/org/jokar/permissiondispatcher/annotation/NeedsPermission.java
Java
apache-2.0
431
/* jquery±íµ¥ÑéÖ¤²å¼þ¡£last edit by rongrong 2011.03.29 */ var __check_form_last_error_info = []; var check_form = function (formname, opt) { var formobj; //Ö¸¶¨µ±Ç°±íµ¥ var e_error = ""; var focus_obj = ""; //µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏñ var error = []; var _temp_ajax = new Array; //ajaxУÑéÇëÇóµÄ»º´æ var opt = opt || {}; //Ñ¡Ïî opt = $.extend({ type: 'form', //УÑé¶ÔÏó form ,elem trim: true, //×Ô¶¯trim errtype: 0, //·µ»Ø´íÎóÐÅÏ¢£º0 È«²¿ 1 ×îºóÒ»Ìõ 2 µÚÒ»Ìõ showtype: 0 //´íÎóÏÔʾ·½Ê½ 0 µ¯³ö 1 ²»µ¯³ö }, opt); if (opt['type'] == 'elem') { formobj = $(formname); formname = $('body'); } else { formobj = $('input,textarea,select,button', formname); } formobj.each(function (i) { var formobj_i = $(this); var jscheckflag = formobj_i.attr("jscheckflag"); var obj_tag = formobj_i.attr("tagName"); jscheckflag = jscheckflag == undefined ? 1 : jscheckflag; if (jscheckflag == 0) return true; var jscheckrule = formobj_i.attr("jscheckrule") || ''; var jscheckerror = formobj_i.attr("jscheckerror"); var jschecktitle = formobj_i.attr("jschecktitle") || '±íµ¥'; var jsmaxlen = formobj_i.attr("maxLength"); //Ö´ÐÐ×Ô¶¯trim if (jscheckrule.indexOf('trim=0') == -1 && opt['trim']) { cf_trim(formobj_i, 1); } //³õʼ»¯jscheckrule //УÑéHTML if (jscheckrule.indexOf('html=') == -1) { jscheckrule += ';html=0'; } var jsvalue = formobj_i.val(); var errflag = 0;//´íÎó±ê¼Ç if (obj_tag == 'TEXTAREA' && (jsmaxlen > 0 ? (jsvalue.length > jsmaxlen ? 1 : 0) : 0)) { jscheckerror = (jschecktitle ? jschecktitle : formobj_i.attr('name')) + " ²»µÃ³¬¹ý " + jsmaxlen + " ×Ö"; errflag = 1; } else if (jscheckrule) { errflag = docheck(formobj_i, jscheckrule) ? errflag : 1; } if (errflag) { e_error = jscheckerror ? jscheckerror : jschecktitle + ' ' + formobj_i.data('jscheckerror'); error.push(e_error); if (focus_obj == "") focus_obj = formobj_i; //¾Û½¹µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏó if (this.oldback == undefined) this.oldback = this.style.backgroundColor; //¼Ç¼ԭµ×É« this.style.backgroundColor = '#FFFF00'; //¸ßÁÁ´íÎó±íµ¥¶ÔÏó } else { if (this.oldback != undefined) this.style.backgroundColor = this.oldback; //»¹Ô­µ×É« } }); //´¦ÀíajaxУÑé if (!error) { for (var i in _temp_ajax) { var obj = _temp_ajax[i].obj; var str = _temp_ajax[i].str; var jscheckerror = obj.attr('jscheckerror'); var jschecktitle = obj.attr('jschecktitle'); if (_cf_ajax.call(obj.get(0), obj, str) != true) { e_error = jscheckerror ? jscheckerror : jschecktitle + ' ' + obj.data('jscheckerror'); error.push(e_error); if (focus_obj == "") focus_obj = obj; //¾Û½¹µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏó if (obj.get(0).oldback == undefined) obj.get(0).oldback = obj.get(0).style.backgroundColor; //¼Ç¼ԭµ×É« obj.get(0).style.backgroundColor = '#FFFF00'; //¸ßÁÁ´íÎó±íµ¥¶ÔÏó break; } } } if (error.length > 0) { __check_form_last_error_info = error; if (opt.showtype == 0) alert("±íµ¥´æÔÚÒÔÏ´íÎó:\n" + error.join("\n")); try { focus_obj.focus() } catch (e) { } ; return false; } return true; //УÑéÖ÷º¯Êý function docheck(el, jscheckrule) { var jscheckrule = jscheckrule || el.attr("jscheckrule"); var e_rules = jscheckrule.split(";"); var e_rule, e_rules_len = e_rules.length; for (var k = 0; k < e_rules_len; k++) { var rule_index = e_rules[k].indexOf("="); if (rule_index > -1) { e_rule = [e_rules[k].substr(0, rule_index), e_rules[k].substr(rule_index + 1)]; if (e_rule.length == 2) { //e_rule_para = e_rule_para.replace(new RegExp("\'","gm"),"\\'"); var cf_func = "cf_" + e_rule[0] + "(el,e_rule[1])"; try { if (!eval(cf_func)) return false; } catch (e) { return false; } } } } return true; } //¼ì²âÖÐÓ¢ÎÄ»ìºÏ³¤¶È function strLen(s) { var i, str1, str2, str3, nLen; str1 = s; nLen = 0; for (i = 1; i <= str1.length; i++) { str2 = str1.substring(i - 1, i) str3 = escape(str2); if (str3.length > 3) { nLen = nLen + 2; } else { nLen = nLen + 1; } } return nLen; } //////////////////////////////////////////**** ¼ì²â¹¦Äܺ¯Êý×é****/////////////////////////////////// //×Ô¶¯trimµô¿Õ¸ñ£¬Ò»°ã¼ÓÔÚ¹æÔò×îÇ°Ãætrim=1 function cf_trim(obj, flag) { if (flag == 1) { var str = obj.val(); str = $.trim(str); try { obj.val(str); } catch (e) { } ;//fileʱ»á³ö´í } return true; } //ÅжÏÊÇ·ñΪ¿Õ function cf_null(obj, cannull) { if (cannull == 1) return true; var obj_type = obj.attr('type'), str; if (obj_type == 'checkbox' || obj_type == 'radio') { var objname = obj.attr('name'); str = formobj.filter(':' + obj_type + '[name=' + objname + '][checked]').map(function () { return this.value; }).get().join(','); } else { str = obj.val(); } str = str && typeof(str) == 'object' ? str.join(',') : str; if (cannull == 0) { str = $.trim(str); } if (cannull == 1 || str != "") return true; obj.data('jscheckerror', '²»ÄÜΪ¿Õ'); return false; } //×î´ó³¤¶È function cf_maxlen(obj, num) { var str = obj.val(); if (str == "" || strLen(str) <= num) return true; obj.data('jscheckerror', '³¤¶È²»ÄÜ´óÓÚ ' + num + ' ×Ö½Ú'); return false; } //×îС³¤¶È function cf_minlen(obj, num) { var str = obj.val(); if (str == "" || strLen(str) >= num) return true; obj.data('jscheckerror', '³¤¶È²»ÄÜСÓÚ ' + num + ' ×Ö½Ú'); return false; } //×î´óÖµ function cf_maxnum(obj, num) { var str = obj.val(); if (str * 1 <= num * 1) return true; obj.data('jscheckerror', '²»ÄÜ´óÓÚ ' + num); return false; } //×î´ó×ÖÊý function cf_maxlencn(obj, num) { var str = obj.val(); if (str == "" || str.length <= num) return true; obj.data('jscheckerror', '×ÖÊý²»ÄÜ´óÓÚ ' + num + ' ×Ö'); return false; } //×îС×ÖÊý function cf_minlencn(obj, num) { var str = obj.val(); if (str == "" || str.length >= num) return true; obj.data('jscheckerror', '×ÖÊý²»ÄÜСÓÚ ' + num + ' ×Ö'); return false; } //Ö¸¶¨×ÖÊý function cf_lencn(obj, num) { var str = obj.val(); if (str == "" || str.length == num) return true; obj.data('jscheckerror', '×ÖÊý±ØÐëµÈÓÚ ' + num + ' ×Ö'); } //×îСֵ function cf_minnum(obj, num) { var str = obj.val(); if (str == "" || str * 1 >= num * 1) return true; obj.data('jscheckerror', '²»ÄÜСÓÚ ' + num); return false; } //Ö¸¶¨³¤¶È function cf_len(obj, num) { var str = obj.val(); if (str == "" || strLen(str) == num) return true; obj.data('jscheckerror', '³¤¶È±ØÐëµÈÓÚ ' + num + ' ×Ö½Ú'); } //ÊÇ·ñÓʼþµØÖ· function cf_email(obj, mustcheck) { var str = obj.val(); if (str == "" || !mustcheck) return true; rx = "^([\\w\\_\\.])+@([\\w]+\\.)+([\\w])+$"; if (cf_regexp(obj, rx)) return true; obj.data('jscheckerror', '±ØÐëΪ EMAIL ¸ñʽ'); return false; } //ÓëÁíÒ»¶ÔÏóµÄÖµÒ»Ö function cf_sameto(obj, el) { var str = obj.val(); if (str == "" || str == formobj.filter("#" + el).val()) return true; el = formobj.filter("#" + el).attr('jschecktitle') || el; obj.data('jscheckerror', '±ØÐëµÈÓÚ ' + el + ' µÄÖµ'); return false; } //ÓëÁíÒ»¶ÔÏóµÄÖµ²»Ò»Ö function cf_differentto(obj, el) { var str = obj.val(); if (str == "" || str == formobj.filter("#" + e1).val()) return true; obj.data('jscheckerror', '±ØÐë²»µÈÓÚ ' + el + ' µÄÖµ'); return false; } //²»ÄÜΪijЩֵ function cf_nosame(obj, para) { var str = obj.val(); if (str == "") return true; var p_arr = para.split(","); var p_arrlen = p_arr.length; for (var l = 0; l < p_arrlen; l++) { if (p_arr[l] == str) { obj.data('jscheckerror', '²»ÄܵÈÓÚ ' + para.join(' »ò ')); return false; break; } } return true; } //ÔÊÐí×Ö·û·¶Î§ function cf_charset(obj, para) { var str = obj.val(); if (str == "") return true; var c_rule = ''; var p_arr = para.split(","); var p_arrlen = p_arr.length; var para_arr = []; for (var l = 0; l < p_arrlen; l++) { if (p_arr[l] == 'en') { c_rule += "a-zA-Z"; para_arr[l] = '×Öĸ'; } else if (p_arr[l] == 'num') { c_rule += "0-9"; para_arr[l] = 'Êý×Ö'; } else if (p_arr[l] == 'fl') { c_rule += "0-9\\.0-9"; para_arr[l] = 'СÊý'; } else if (p_arr[l] == 'cn') { c_rule += "\\u4E00-\\u9FA5"; para_arr[l] = 'ÖÐÎÄ'; } else if (p_arr[l] == 'ul') { c_rule += "_"; para_arr[l] = 'Ï»®Ïß'; } } if (c_rule == "") return true; else { var t_rule = "^[" + c_rule + "]*$"; if (cf_regexp(obj, t_rule)) return true; obj.data('jscheckerror', '±ØÐëΪ[' + para_arr.join(',') + ']'); return false; } } //×Ô¶¨ÒåÕýÔòÆ¥Åä function cf_regexp(obj, rx) { var str = obj.val(); if (str == "") return true; if (rx == "")return true; var r_exp = new RegExp(rx, "ig"); if (r_exp.test(str)) return true; obj.data('jscheckerror', 'º¬ÓзǷ¨×Ö·û'); return false; } //УÑéHTML±êÇ©<HTML> function cf_html(obj, flag) { var str = obj.val(); if (str == "" || str == null) return true; if (flag == 1) return true; if (str.indexOf('<') == -1 && str.indexOf('>') == -1) return true; obj.data('jscheckerror', 'º¬ÓÐhtml×Ö·û'); return false; } //ajaxУÑé function cf_ajax(obj, str) { _temp_ajax = _temp_ajax.concat({obj: obj, str: str}); return true; //return _cf_ajax.call(obj.get(0),obj,str); } function _cf_ajax(obj, str) { var str_obj = eval('(' + str + ')'); var resp = $.ajax({ url: str_obj.url, async: false, data: str_obj.data }).responseText; if (resp === 'true') return true; obj.data('jscheckerror', resp); return false; } function get_param(str) { return eval('(' + str + ')'); } //µ÷º¯Êý call = {func:[this.value,1,2,3]} function cf_call(obj, str) { var str_obj = get_param.call(obj.get(0), str); for (var func in str_obj) { var resp = window[func].apply(undefined, str_obj[func]); if (resp !== true) { obj.data('jscheckerror', resp); return false; } } return true; } } check_form.get_error = function () { return __check_form_last_error_info; };
DullSky/his
WebRoot/Js/ckform.js
JavaScript
apache-2.0
12,288
<?php /* This php script extract all the file contained in $dir_txt and $dir_html to index them in the table pages of our database. To have an accurate research later, we attribute differents weigths to texts depending of the importance of their part. */ /* This function extract the text in the paragraph named by $part_name in the string $html containing the entire man page under html form */ function extract_texte($html, $part_name) { $pattern_start = '<h2 class="nroffsh">'.$part_name.'</h2>'; $pattern_end="<h2"; $retour = ""; $pos= strpos($html, $pattern_start); if (!($pos===false)) { $retour = substr($html, $pos + strlen($pattern_start)) ; $pos = strpos($retour, $pattern_end); if (!($pos===false)) { $retour = substr($retour, 0, $pos); } } return strip_tags($retour); } include('bdd.php'); $dir_txt = "man_txt/man1"; $dir_html = "man_html/man1"; $extension = ".1.txt"; $extension_html = ".1.html"; $files = scandir($dir_txt); echo "</br>"; foreach ($files as $file){ $page_name = substr($file , 0 , -(strlen($extension))); if (!is_dir($dir_txt."/".$file)){ echo $page_name . "</br>"; $file_content = ""; $file_content = file_get_contents($dir_txt."/".$file); $file_content_html = ""; $file_content_html = file_get_contents($dir_html."/".$page_name.$extension_html); try{ $query = "INSERT INTO pages VALUES ('$page_name','". str_replace ("'","''",$file_content)."','". str_replace ("'","''",$file_content_html)."',". "( ". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"NAME"))."'), 'A') ||". //"setweight(to_tsvector('".$page_name."'), 'A') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"DESCRIPTION"))."'), 'B') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"SYNOPSIS"))."'), 'C') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"OPTION"))."'), 'C') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"ERRORS"))."'), 'C') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"NOTES"))."'), 'C') ||". "setweight(to_tsvector('".str_replace ("'","''",extract_texte($file_content_html,"EXAMPLE"))."'), 'C') ||". "to_tsvector('".str_replace ("'","''",$file_content)."') ) ) "; $bdd->exec($query); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } } } echo "It's works</br>"; ?>
loic-carbonne/Man-fulltext-search
Step2-Indexing/export_to_db.php
PHP
apache-2.0
2,736
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.asterix.installer.driver; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import edu.uci.ics.asterix.common.configuration.AsterixConfiguration; import edu.uci.ics.asterix.event.schema.cluster.Cluster; import edu.uci.ics.asterix.event.schema.cluster.Node; public class InstallerUtil { private static final String DEFAULT_ASTERIX_CONFIGURATION_PATH = "conf" + File.separator + "asterix-configuration.xml"; public static final String TXN_LOG_DIR = "txnLogs"; public static final String TXN_LOG_DIR_KEY_SUFFIX = "txnLogDir"; public static final String ASTERIX_CONFIGURATION_FILE = "asterix-configuration.xml"; public static final String TXN_LOG_CONFIGURATION_FILE = "log.properties"; public static final int CLUSTER_NET_PORT_DEFAULT = 1098; public static final int CLIENT_NET_PORT_DEFAULT = 1099; public static final int HTTP_PORT_DEFAULT = 8888; public static final int WEB_INTERFACE_PORT_DEFAULT = 19001; public static String getNodeDirectories(String asterixInstanceName, Node node, Cluster cluster) { String storeDataSubDir = asterixInstanceName + File.separator + "data" + File.separator; String[] storeDirs = null; StringBuffer nodeDataStore = new StringBuffer(); String storeDirValue = node.getStore(); if (storeDirValue == null) { storeDirValue = cluster.getStore(); if (storeDirValue == null) { throw new IllegalStateException(" Store not defined for node " + node.getId()); } storeDataSubDir = node.getId() + File.separator + storeDataSubDir; } storeDirs = storeDirValue.split(","); for (String ns : storeDirs) { nodeDataStore.append(ns + File.separator + storeDataSubDir.trim()); nodeDataStore.append(","); } nodeDataStore.deleteCharAt(nodeDataStore.length() - 1); return nodeDataStore.toString(); } public static AsterixConfiguration getAsterixConfiguration(String asterixConf) throws FileNotFoundException, IOException, JAXBException { if (asterixConf == null) { asterixConf = InstallerDriver.getManagixHome() + File.separator + DEFAULT_ASTERIX_CONFIGURATION_PATH; } File file = new File(asterixConf); JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class); Unmarshaller unmarshaller = ctx.createUnmarshaller(); AsterixConfiguration asterixConfiguration = (AsterixConfiguration) unmarshaller.unmarshal(file); return asterixConfiguration; } }
parshimers/incubator-asterixdb
asterix-installer/src/main/java/edu/uci/ics/asterix/installer/driver/InstallerUtil.java
Java
apache-2.0
3,396
/** * Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.geoar.newdata; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.n52.geoar.newdata.Annotations; import org.n52.geoar.newdata.DataSource; import org.n52.geoar.newdata.Filter; import org.n52.geoar.GeoARApplication; import org.n52.geoar.newdata.CheckList.CheckManager; import org.n52.geoar.newdata.PluginLoader.PluginInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Parcel; import dalvik.system.DexClassLoader; import dalvik.system.DexFile; public class InstalledPluginHolder extends PluginHolder { private List<DataSourceHolder> mDataSources = new ArrayList<DataSourceHolder>(); private File pluginFile; private Long version; private String identifier; private boolean loaded = false; private String description; private String name; private Context mPluginContext; private Bitmap pluginIcon; private String publisher; @CheckManager private CheckList<InstalledPluginHolder>.Checker mChecker; private DexClassLoader mPluginDexClassLoader; private boolean iconLoaded; private static final Logger LOG = LoggerFactory .getLogger(InstalledPluginHolder.class); public InstalledPluginHolder(PluginInfo pluginInfo) { this.version = pluginInfo.version; this.identifier = pluginInfo.identifier; this.description = pluginInfo.description; this.name = pluginInfo.name; this.pluginFile = pluginInfo.pluginFile; this.publisher = pluginInfo.publisher; } @Override public String getIdentifier() { return identifier; } @Override public String getName() { return name; } @Override public String getPublisher() { return publisher; } @Override public Long getVersion() { return version; } public String getDescription() { return description; }; /** * Changes to the returned list do not affect loaded data sources * * @return */ public List<DataSourceHolder> getDataSources() { if (!loaded) { try { loadPlugin(); } catch (IOException e) { e.printStackTrace(); } } return mDataSources; } public File getPluginFile() { return pluginFile; } public void setChecked(boolean state) { mChecker.setChecked(state); } public boolean isChecked() { return mChecker.isChecked(); } @SuppressLint("NewApi") private void loadPlugin() throws IOException { mDataSources.clear(); String pluginBaseFileName = getPluginFile().getName().substring(0, getPluginFile().getName().lastIndexOf(".")); // Check if the Plugin exists if (!getPluginFile().exists()) throw new FileNotFoundException("Not found: " + getPluginFile()); File tmpDir = GeoARApplication.applicationContext.getDir( pluginBaseFileName, 0); Enumeration<String> entries = DexFile .loadDex( getPluginFile().getAbsolutePath(), tmpDir.getAbsolutePath() + "/" + pluginBaseFileName + ".dex", 0).entries(); // Path for optimized dex equals path which will be used by // dexClassLoader // create separate ClassLoader for each plugin mPluginDexClassLoader = new DexClassLoader(getPluginFile() .getAbsolutePath(), tmpDir.getAbsolutePath(), null, GeoARApplication.applicationContext.getClassLoader()); try { while (entries.hasMoreElements()) { // Check each classname for annotations String entry = entries.nextElement(); Class<?> entryClass = mPluginDexClassLoader.loadClass(entry); if (entryClass .isAnnotationPresent(Annotations.DataSource.class)) { // Class is a annotated as datasource if (org.n52.geoar.newdata.DataSource.class .isAssignableFrom(entryClass)) { // Class is a datasource @SuppressWarnings("unchecked") DataSourceHolder dataSourceHolder = new DataSourceHolder( (Class<? extends DataSource<? super Filter>>) entryClass, this); mDataSources.add(dataSourceHolder); } else { LOG.error("Datasource " + entryClass.getSimpleName() + " is not implementing DataSource interface"); // TODO handle error, somehow propagate back to user } } } } catch (ClassNotFoundException e) { throw new RuntimeException("Dex changed"); } catch (LinkageError e) { LOG.error("Data source " + getName() + " uses invalid class, " + e.getMessage()); } loaded = true; } /** * Returns a {@link Context} wrapping the * {@link GeoARApplication#applicationContext}, but returning the value of * {@link InstalledPluginHolder#getPluginResources()} as * {@link Context#getResources()} return value. * * @return */ public Context getPluginContext() { if (mPluginContext == null) { mPluginContext = new PluginContext( GeoARApplication.applicationContext, this); } return mPluginContext; } public ClassLoader getPluginClassLoader() { return mPluginDexClassLoader; } @Override public Bitmap getPluginIcon() { if (!iconLoaded) { try { iconLoaded = true; ZipFile zipFile = new ZipFile(pluginFile); ZipEntry pluginIconEntry = zipFile.getEntry("icon.png"); if (pluginIconEntry != null) { pluginIcon = BitmapFactory.decodeStream(zipFile .getInputStream(pluginIconEntry)); } else { LOG.info("Plugin " + getName() + " has no icon"); } } catch (IOException e) { LOG.error("Plugin " + getName() + " has an invalid icon"); } } return pluginIcon; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getClass().getName()); super.writeToParcel(dest, flags); } public void saveState(ObjectOutputStream objectOutputStream) throws IOException { objectOutputStream.writeBoolean(isChecked()); for (DataSourceHolder dataSource : mDataSources) { dataSource.saveState(objectOutputStream); } } public void restoreState(PluginStateInputStream objectInputStream) throws IOException { setChecked(objectInputStream.readBoolean()); for (DataSourceHolder dataSource : mDataSources) { dataSource.restoreState(objectInputStream); } } /** * Should be called after all state initialization took place, e.g. after * {@link InstalledPluginHolder#restoreState(PluginStateInputStream)} */ public void postConstruct() { for (DataSourceHolder dataSource : mDataSources) { dataSource.postConstruct(); } } }
52North/geoar-app
src/main/java/org/n52/geoar/newdata/InstalledPluginHolder.java
Java
apache-2.0
7,501
/* * * Copyright (c) 2015-2017 Stanislav Zhukov * * 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 YAPE_OPTEST_HPP #define YAPE_OPTEST_HPP #include "OpAND.hpp" class OpTEST : public OpAND { public: void Execute() override; int GetOpcode() const override; }; #endif //YAPE_OPTEST_HPP
Koncord/YAPE
apps/Core/Instructions/OpTEST.hpp
C++
apache-2.0
830
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from airflow import AirflowException from airflow.contrib.hooks.gcp_compute_hook import GceHook from airflow.contrib.utils.gcp_field_validator import GcpBodyFieldValidator from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class GceBaseOperator(BaseOperator): """ Abstract base operator for Google Compute Engine operators to inherit from. """ @apply_defaults def __init__(self, project_id, zone, resource_id, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): self.project_id = project_id self.zone = zone self.full_location = 'projects/{}/zones/{}'.format(self.project_id, self.zone) self.resource_id = resource_id self.gcp_conn_id = gcp_conn_id self.api_version = api_version self._validate_inputs() self._hook = GceHook(gcp_conn_id=self.gcp_conn_id, api_version=self.api_version) super(GceBaseOperator, self).__init__(*args, **kwargs) def _validate_inputs(self): if not self.project_id: raise AirflowException("The required parameter 'project_id' is missing") if not self.zone: raise AirflowException("The required parameter 'zone' is missing") if not self.resource_id: raise AirflowException("The required parameter 'resource_id' is missing") def execute(self, context): pass class GceInstanceStartOperator(GceBaseOperator): """ Start an instance in Google Compute Engine. :param project_id: Google Cloud Platform project where the Compute Engine instance exists. :type project_id: str :param zone: Google Cloud Platform zone where the instance exists. :type zone: str :param resource_id: Name of the Compute Engine instance resource. :type resource_id: str :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: str :param api_version: API version used (e.g. v1). :type api_version: str """ template_fields = ('project_id', 'zone', 'resource_id', 'gcp_conn_id', 'api_version') @apply_defaults def __init__(self, project_id, zone, resource_id, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): super(GceInstanceStartOperator, self).__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, *args, **kwargs) def execute(self, context): return self._hook.start_instance(self.project_id, self.zone, self.resource_id) class GceInstanceStopOperator(GceBaseOperator): """ Stop an instance in Google Compute Engine. :param project_id: Google Cloud Platform project where the Compute Engine instance exists. :type project_id: str :param zone: Google Cloud Platform zone where the instance exists. :type zone: str :param resource_id: Name of the Compute Engine instance resource. :type resource_id: str :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: str :param api_version: API version used (e.g. v1). :type api_version: str """ template_fields = ('project_id', 'zone', 'resource_id', 'gcp_conn_id', 'api_version') @apply_defaults def __init__(self, project_id, zone, resource_id, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): super(GceInstanceStopOperator, self).__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, *args, **kwargs) def execute(self, context): return self._hook.stop_instance(self.project_id, self.zone, self.resource_id) SET_MACHINE_TYPE_VALIDATION_SPECIFICATION = [ dict(name="machineType", regexp="^.+$"), ] class GceSetMachineTypeOperator(GceBaseOperator): """ Changes the machine type for a stopped instance to the machine type specified in the request. :param project_id: Google Cloud Platform project where the Compute Engine instance exists. :type project_id: str :param zone: Google Cloud Platform zone where the instance exists. :type zone: str :param resource_id: Name of the Compute Engine instance resource. :type resource_id: str :param body: Body required by the Compute Engine setMachineType API, as described in https://cloud.google.com/compute/docs/reference/rest/v1/instances/setMachineType#request-body :type body: dict :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. :type gcp_conn_id: str :param api_version: API version used (e.g. v1). :type api_version: str """ template_fields = ('project_id', 'zone', 'resource_id', 'gcp_conn_id', 'api_version') @apply_defaults def __init__(self, project_id, zone, resource_id, body, gcp_conn_id='google_cloud_default', api_version='v1', validate_body=True, *args, **kwargs): self.body = body self._field_validator = None if validate_body: self._field_validator = GcpBodyFieldValidator( SET_MACHINE_TYPE_VALIDATION_SPECIFICATION, api_version=api_version) super(GceSetMachineTypeOperator, self).__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, *args, **kwargs) def _validate_all_body_fields(self): if self._field_validator: self._field_validator.validate(self.body) def execute(self, context): self._validate_all_body_fields() return self._hook.set_machine_type(self.project_id, self.zone, self.resource_id, self.body)
sid88in/incubator-airflow
airflow/contrib/operators/gcp_compute_operator.py
Python
apache-2.0
7,129
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * 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.gbif.metrics.es; import java.util.Objects; /** Query parameter. */ public class Parameter { private final String name; private final String value; /** * @param name parameter name/key * @param value parameter value */ public Parameter(String name, String value) { this.name = name; this.value = value; } /** @return parameter name/key */ public String getName() { return name; } /** @return parameter value */ public String getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Parameter parameter = (Parameter) o; return name.equals(parameter.name) && value.equals(parameter.value); } @Override public int hashCode() { return Objects.hash(name, value); } }
gbif/metrics
metrics-es/src/main/java/org/gbif/metrics/es/Parameter.java
Java
apache-2.0
1,522
/* * Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.abst.filter.convolve; import boofcv.alg.filter.convolve.ConvolveImageNoBorder; import boofcv.alg.filter.convolve.ConvolveUnsafe_U8; import boofcv.alg.filter.convolve.ConvolveWithBorder; import boofcv.alg.filter.convolve.noborder.*; import boofcv.alg.misc.ImageMiscOps; import boofcv.core.image.border.BorderIndex1D_Extend; import boofcv.core.image.border.ImageBorder1D_S32; import boofcv.factory.filter.kernel.FactoryKernelGaussian; import boofcv.struct.convolve.Kernel1D_F32; import boofcv.struct.convolve.Kernel1D_I32; import boofcv.struct.convolve.Kernel2D_F32; import boofcv.struct.convolve.Kernel2D_I32; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageSInt16; import boofcv.struct.image.ImageSInt32; import boofcv.struct.image.ImageUInt8; import java.util.Random; /** * Benchmark for different convolution operations. * @author Peter Abeles */ @SuppressWarnings({"UnusedDeclaration"}) public class BenchmarkConvolve { static int width = 640; static int height = 480; Random rand = new Random(234); static Kernel2D_F32 kernel2D_F32; static Kernel1D_F32 kernelF32; static Kernel1D_I32 kernelI32; static Kernel2D_I32 kernel2D_I32; static ImageFloat32 input_F32 = new ImageFloat32(width,height); static ImageFloat32 out_F32 = new ImageFloat32(width,height); static ImageUInt8 input_U8 = new ImageUInt8(width,height); static ImageSInt16 input_S16 = new ImageSInt16(width,height); static ImageUInt8 out_U8 = new ImageUInt8(width,height); static ImageSInt16 out_S16 = new ImageSInt16(width,height); static ImageSInt32 out_S32 = new ImageSInt32(width,height); // iterate through different sized kernel radius // @Param({"1", "2"}) private int radius; public BenchmarkConvolve() { ImageMiscOps.fillUniform(input_U8,rand,0,20); ImageMiscOps.fillUniform(input_S16,rand,0,20); ImageMiscOps.fillUniform(input_F32,rand,0,20); } protected void setUp() throws Exception { kernelF32 = FactoryKernelGaussian.gaussian(Kernel1D_F32.class, -1, radius); kernelI32 = FactoryKernelGaussian.gaussian(Kernel1D_I32.class,-1,radius); kernel2D_F32 = FactoryKernelGaussian.gaussian(Kernel2D_F32.class,-1,radius); kernel2D_I32 = FactoryKernelGaussian.gaussian(Kernel2D_I32.class, -1, radius); } public int timeHorizontal_F32(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.horizontal(kernelF32, input_F32,out_F32); return 0; } public int timeHorizontal_I8_I8_div2(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.horizontal(kernelI32, input_U8, out_U8, 10); return 0; } public int timeHorizontalUnroll_I8_I8_div(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_U8_I8_Div.horizontal(kernelI32, input_U8, out_U8,10) ) throw new RuntimeException(); return 0; } public int timeHorizontal_I8_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.horizontal(kernelI32, input_U8, out_S16); return 0; } public int timeHorizontal_I16_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.horizontal(kernelI32, input_S16, out_S16); return 0; } public int timeVertical_F32(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.vertical(kernelF32, input_F32, out_F32); return 0; } public int timeVertical_I8_I8_div(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.vertical(kernelI32, input_U8, out_U8,10); return 0; } public int timeVerticalUnrolled_U8_I8_div(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_U8_I8_Div.vertical(kernelI32, input_U8, out_U8,10) ) throw new RuntimeException(); return 0; } public int timeVertical_I8_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.vertical(kernelI32, input_U8, out_S16); return 0; } public int timeVertical_I16_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.vertical(kernelI32, input_S16, out_S16); return 0; } public int timeConvolve2D_F32(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageNoBorder.convolve(kernel2D_F32, input_F32, out_F32); return 0; } public int timeConvolve2D_Std_F32(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.convolve(kernel2D_F32, input_F32,out_F32); return 0; } public int timeConvolve2D_Unrolled_F32(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_F32_F32.convolve(kernel2D_F32, input_F32,out_F32) ) throw new RuntimeException(); return 0; } public int timeConvolve2D_I8_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_S16); return 0; } public int timeConvolve2D_Extend_I8_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveWithBorder.convolve(kernel2D_I32, input_U8, out_S16, new ImageBorder1D_S32(BorderIndex1D_Extend.class)); return 0; } public int timeConvolve2D_Std_I8_I8_DIV(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageStandard.convolve(kernel2D_I32, input_U8, out_U8,10); return 0; } public int timeConvolve2D_I8_I8_DIV(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_U8,10); return 0; } public int timeConvolveUnsafe2D_I8_I8_DIV(int reps) { for( int i = 0; i < reps; i++ ) ConvolveUnsafe_U8.convolve(kernel2D_I32, input_U8, out_U8, 10); return 0; } public int timeConvolve2D_Std_I8_I16(int reps) { for( int i = 0; i < reps; i++ ) ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_U8,10); return 0; } public int timeHorizontalUnrolled_F32(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_F32_F32.horizontal(kernelF32, input_F32,out_F32) ) throw new RuntimeException(); return 0; } public int timeVerticalUnrolled_F32(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_F32_F32.vertical(kernelF32, input_F32, out_F32) ) throw new RuntimeException(); return 0; } public int timeHorizontalUnrolled_U8(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_U8_I16.horizontal(kernelI32, input_U8, out_S16) ) throw new RuntimeException(); return 0; } public int timeVerticalUnrolled_U8(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_U8_I16.vertical(kernelI32, input_U8, out_S16) ) throw new RuntimeException(); return 0; } public int timeHorizontalUnrolled_I16(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_S16_I16.horizontal(kernelI32, input_S16, out_S16) ) throw new RuntimeException(); return 0; } public int timeVerticalUnrolled_I16(int reps) { for( int i = 0; i < reps; i++ ) if( !ConvolveImageUnrolled_S16_I16.vertical(kernelI32, input_S16, out_S16) ) throw new RuntimeException(); return 0; } public int timeBox_U8_S32_Vertical6(int reps) { for( int i = 0; i < reps; i++ ) ImplConvolveBox.vertical(input_U8, out_S32,radius); return 0; } // public static void main( String args[] ) { // System.out.println("========= Profile Image Size "+ width +" x "+ height +" =========="); // // Runner.main(BenchmarkConvolve.class, args); // } }
pacozaa/BoofCV
main/ip/benchmark/boofcv/abst/filter/convolve/BenchmarkConvolve.java
Java
apache-2.0
7,931
// Copyright 2015 The Hugo Authors. 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. package helpers import ( "fmt" "io/ioutil" "os" "path/filepath" "reflect" "runtime" "strconv" "strings" "testing" "time" "github.com/gohugoio/hugo/langs" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugofs" "github.com/spf13/afero" ) func TestMakePath(t *testing.T) { c := qt.New(t) tests := []struct { input string expected string removeAccents bool }{ {"dot.slash/backslash\\underscore_pound#plus+hyphen-", "dot.slash/backslash\\underscore_pound#plus+hyphen-", true}, {"abcXYZ0123456789", "abcXYZ0123456789", true}, {"%20 %2", "%20-2", true}, {"foo- bar", "foo-bar", true}, {" Foo bar ", "Foo-bar", true}, {"Foo.Bar/foo_Bar-Foo", "Foo.Bar/foo_Bar-Foo", true}, {"fOO,bar:foobAR", "fOObarfoobAR", true}, {"FOo/BaR.html", "FOo/BaR.html", true}, {"трям/трям", "трям/трям", true}, {"은행", "은행", true}, {"Банковский кассир", "Банковскии-кассир", true}, // Issue #1488 {"संस्कृत", "संस्कृत", false}, {"a%C3%B1ame", "a%C3%B1ame", false}, // Issue #1292 {"this+is+a+test", "this+is+a+test", false}, // Issue #1290 {"~foo", "~foo", false}, // Issue #2177 {"foo--bar", "foo--bar", true}, // Issue #7288 } for _, test := range tests { v := newTestCfg() v.Set("removePathAccents", test.removeAccents) l := langs.NewDefaultLanguage(v) p, err := NewPathSpec(hugofs.NewMem(v), l, nil) c.Assert(err, qt.IsNil) output := p.MakePath(test.input) if output != test.expected { t.Errorf("Expected %#v, got %#v\n", test.expected, output) } } } func TestMakePathSanitized(t *testing.T) { v := newTestCfg() p, _ := NewPathSpec(hugofs.NewMem(v), v, nil) tests := []struct { input string expected string }{ {" FOO bar ", "foo-bar"}, {"Foo.Bar/fOO_bAr-Foo", "foo.bar/foo_bar-foo"}, {"FOO,bar:FooBar", "foobarfoobar"}, {"foo/BAR.HTML", "foo/bar.html"}, {"трям/трям", "трям/трям"}, {"은행", "은행"}, } for _, test := range tests { output := p.MakePathSanitized(test.input) if output != test.expected { t.Errorf("Expected %#v, got %#v\n", test.expected, output) } } } func TestMakePathSanitizedDisablePathToLower(t *testing.T) { v := newTestCfg() v.Set("disablePathToLower", true) l := langs.NewDefaultLanguage(v) p, _ := NewPathSpec(hugofs.NewMem(v), l, nil) tests := []struct { input string expected string }{ {" FOO bar ", "FOO-bar"}, {"Foo.Bar/fOO_bAr-Foo", "Foo.Bar/fOO_bAr-Foo"}, {"FOO,bar:FooBar", "FOObarFooBar"}, {"foo/BAR.HTML", "foo/BAR.HTML"}, {"трям/трям", "трям/трям"}, {"은행", "은행"}, } for _, test := range tests { output := p.MakePathSanitized(test.input) if output != test.expected { t.Errorf("Expected %#v, got %#v\n", test.expected, output) } } } func TestMakePathRelative(t *testing.T) { type test struct { inPath, path1, path2, output string } data := []test{ {"/abc/bcd/ab.css", "/abc/bcd", "/bbc/bcd", "/ab.css"}, {"/abc/bcd/ab.css", "/abcd/bcd", "/abc/bcd", "/ab.css"}, } for i, d := range data { output, _ := makePathRelative(d.inPath, d.path1, d.path2) if d.output != output { t.Errorf("Test #%d failed. Expected %q got %q", i, d.output, output) } } _, error := makePathRelative("a/b/c.ss", "/a/c", "/d/c", "/e/f") if error == nil { t.Errorf("Test failed, expected error") } } func TestGetDottedRelativePath(t *testing.T) { // on Windows this will receive both kinds, both country and western ... for _, f := range []func(string) string{filepath.FromSlash, func(s string) string { return s }} { doTestGetDottedRelativePath(f, t) } } func doTestGetDottedRelativePath(urlFixer func(string) string, t *testing.T) { type test struct { input, expected string } data := []test{ {"", "./"}, {urlFixer("/"), "./"}, {urlFixer("post"), "../"}, {urlFixer("/post"), "../"}, {urlFixer("post/"), "../"}, {urlFixer("tags/foo.html"), "../"}, {urlFixer("/tags/foo.html"), "../"}, {urlFixer("/post/"), "../"}, {urlFixer("////post/////"), "../"}, {urlFixer("/foo/bar/index.html"), "../../"}, {urlFixer("/foo/bar/foo/"), "../../../"}, {urlFixer("/foo/bar/foo"), "../../../"}, {urlFixer("foo/bar/foo/"), "../../../"}, {urlFixer("foo/bar/foo/bar"), "../../../../"}, {"404.html", "./"}, {"404.xml", "./"}, {"/404.html", "./"}, } for i, d := range data { output := GetDottedRelativePath(d.input) if d.expected != output { t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output) } } } func TestMakeTitle(t *testing.T) { type test struct { input, expected string } data := []test{ {"Make-Title", "Make Title"}, {"MakeTitle", "MakeTitle"}, {"make_title", "make_title"}, } for i, d := range data { output := MakeTitle(d.input) if d.expected != output { t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, output) } } } func TestDirExists(t *testing.T) { type test struct { input string expected bool } data := []test{ {".", true}, {"./", true}, {"..", true}, {"../", true}, {"./..", true}, {"./../", true}, {os.TempDir(), true}, {os.TempDir() + FilePathSeparator, true}, {"/", true}, {"/some-really-random-directory-name", false}, {"/some/really/random/directory/name", false}, {"./some-really-random-local-directory-name", false}, {"./some/really/random/local/directory/name", false}, } for i, d := range data { exists, _ := DirExists(filepath.FromSlash(d.input), new(afero.OsFs)) if d.expected != exists { t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists) } } } func TestIsDir(t *testing.T) { type test struct { input string expected bool } data := []test{ {"./", true}, {"/", true}, {"./this-directory-does-not-existi", false}, {"/this-absolute-directory/does-not-exist", false}, } for i, d := range data { exists, _ := IsDir(d.input, new(afero.OsFs)) if d.expected != exists { t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists) } } } func TestIsEmpty(t *testing.T) { zeroSizedFile, _ := createZeroSizedFileInTempDir() defer deleteFileInTempDir(zeroSizedFile) nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir() defer deleteFileInTempDir(nonZeroSizedFile) emptyDirectory, _ := createEmptyTempDir() defer deleteTempDir(emptyDirectory) nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles() defer deleteTempDir(nonEmptyZeroLengthFilesDirectory) nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles() defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory) nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt" nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/" fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile) dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir) type test struct { input string expectedResult bool expectedErr error } data := []test{ {zeroSizedFile.Name(), true, nil}, {nonZeroSizedFile.Name(), false, nil}, {emptyDirectory, true, nil}, {nonEmptyZeroLengthFilesDirectory, false, nil}, {nonEmptyNonZeroLengthFilesDirectory, false, nil}, {nonExistentFile, false, fileDoesNotExist}, {nonExistentDir, false, dirDoesNotExist}, } for i, d := range data { exists, err := IsEmpty(d.input, new(afero.OsFs)) if d.expectedResult != exists { t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists) } if d.expectedErr != nil { if d.expectedErr.Error() != err.Error() { t.Errorf("Test %d failed. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err) } } else { if d.expectedErr != err { t.Errorf("Test %d failed. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err) } } } } func createZeroSizedFileInTempDir() (*os.File, error) { filePrefix := "_path_test_" f, e := ioutil.TempFile("", filePrefix) // dir is os.TempDir() if e != nil { // if there was an error no file was created. // => no requirement to delete the file return nil, e } return f, nil } func createNonZeroSizedFileInTempDir() (*os.File, error) { f, err := createZeroSizedFileInTempDir() if err != nil { // no file ?? return nil, err } byteString := []byte("byteString") err = ioutil.WriteFile(f.Name(), byteString, 0644) if err != nil { // delete the file deleteFileInTempDir(f) return nil, err } return f, nil } func deleteFileInTempDir(f *os.File) { _ = os.Remove(f.Name()) } func createEmptyTempDir() (string, error) { dirPrefix := "_dir_prefix_" d, e := ioutil.TempDir("", dirPrefix) // will be in os.TempDir() if e != nil { // no directory to delete - it was never created return "", e } return d, nil } func createTempDirWithZeroLengthFiles() (string, error) { d, dirErr := createEmptyTempDir() if dirErr != nil { return "", dirErr } filePrefix := "_path_test_" _, fileErr := ioutil.TempFile(d, filePrefix) // dir is os.TempDir() if fileErr != nil { // if there was an error no file was created. // but we need to remove the directory to clean-up deleteTempDir(d) return "", fileErr } // the dir now has one, zero length file in it return d, nil } func createTempDirWithNonZeroLengthFiles() (string, error) { d, dirErr := createEmptyTempDir() if dirErr != nil { return "", dirErr } filePrefix := "_path_test_" f, fileErr := ioutil.TempFile(d, filePrefix) // dir is os.TempDir() if fileErr != nil { // if there was an error no file was created. // but we need to remove the directory to clean-up deleteTempDir(d) return "", fileErr } byteString := []byte("byteString") fileErr = ioutil.WriteFile(f.Name(), byteString, 0644) if fileErr != nil { // delete the file deleteFileInTempDir(f) // also delete the directory deleteTempDir(d) return "", fileErr } // the dir now has one, zero length file in it return d, nil } func deleteTempDir(d string) { _ = os.RemoveAll(d) } func TestExists(t *testing.T) { zeroSizedFile, _ := createZeroSizedFileInTempDir() defer deleteFileInTempDir(zeroSizedFile) nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir() defer deleteFileInTempDir(nonZeroSizedFile) emptyDirectory, _ := createEmptyTempDir() defer deleteTempDir(emptyDirectory) nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt" nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/" type test struct { input string expectedResult bool expectedErr error } data := []test{ {zeroSizedFile.Name(), true, nil}, {nonZeroSizedFile.Name(), true, nil}, {emptyDirectory, true, nil}, {nonExistentFile, false, nil}, {nonExistentDir, false, nil}, } for i, d := range data { exists, err := Exists(d.input, new(afero.OsFs)) if d.expectedResult != exists { t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists) } if d.expectedErr != err { t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err) } } } func TestAbsPathify(t *testing.T) { type test struct { inPath, workingDir, expected string } data := []test{ {os.TempDir(), filepath.FromSlash("/work"), filepath.Clean(os.TempDir())}, // TempDir has trailing slash {"dir", filepath.FromSlash("/work"), filepath.FromSlash("/work/dir")}, } windowsData := []test{ {"c:\\banana\\..\\dir", "c:\\foo", "c:\\dir"}, {"\\dir", "c:\\foo", "c:\\foo\\dir"}, {"c:\\", "c:\\foo", "c:\\"}, } unixData := []test{ {"/banana/../dir/", "/work", "/dir"}, } for i, d := range data { // todo see comment in AbsPathify ps := newTestDefaultPathSpec("workingDir", d.workingDir) expected := ps.AbsPathify(d.inPath) if d.expected != expected { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected) } } t.Logf("Running platform specific path tests for %s", runtime.GOOS) if runtime.GOOS == "windows" { for i, d := range windowsData { ps := newTestDefaultPathSpec("workingDir", d.workingDir) expected := ps.AbsPathify(d.inPath) if d.expected != expected { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected) } } } else { for i, d := range unixData { ps := newTestDefaultPathSpec("workingDir", d.workingDir) expected := ps.AbsPathify(d.inPath) if d.expected != expected { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expected, expected) } } } } func TestExtractAndGroupRootPaths(t *testing.T) { in := []string{ filepath.FromSlash("/a/b/c/d"), filepath.FromSlash("/a/b/c/e"), filepath.FromSlash("/a/b/e/f"), filepath.FromSlash("/a/b"), filepath.FromSlash("/a/b/c/b/g"), filepath.FromSlash("/c/d/e"), } inCopy := make([]string, len(in)) copy(inCopy, in) result := ExtractAndGroupRootPaths(in) c := qt.New(t) c.Assert(fmt.Sprint(result), qt.Equals, filepath.FromSlash("[/a/b/{c,e} /c/d/e]")) // Make sure the original is preserved c.Assert(in, qt.DeepEquals, inCopy) } func TestExtractRootPaths(t *testing.T) { tests := []struct { input []string expected []string }{{ []string{ filepath.FromSlash("a/b"), filepath.FromSlash("a/b/c/"), "b", filepath.FromSlash("/c/d"), filepath.FromSlash("d/"), filepath.FromSlash("//e//"), }, []string{"a", "a", "b", "c", "d", "e"}, }} for _, test := range tests { output := ExtractRootPaths(test.input) if !reflect.DeepEqual(output, test.expected) { t.Errorf("Expected %#v, got %#v\n", test.expected, output) } } } func TestFindCWD(t *testing.T) { type test struct { expectedDir string expectedErr error } // cwd, _ := os.Getwd() data := []test{ //{cwd, nil}, // Commenting this out. It doesn't work properly. // There's a good reason why we don't use os.Getwd(), it doesn't actually work the way we want it to. // I really don't know a better way to test this function. - SPF 2014.11.04 } for i, d := range data { dir, err := FindCWD() if d.expectedDir != dir { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedDir, dir) } if d.expectedErr != err { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, err) } } } func TestSafeWriteToDisk(t *testing.T) { emptyFile, _ := createZeroSizedFileInTempDir() defer deleteFileInTempDir(emptyFile) tmpDir, _ := createEmptyTempDir() defer deleteTempDir(tmpDir) randomString := "This is a random string!" reader := strings.NewReader(randomString) fileExists := fmt.Errorf("%v already exists", emptyFile.Name()) type test struct { filename string expectedErr error } now := time.Now().Unix() nowStr := strconv.FormatInt(now, 10) data := []test{ {emptyFile.Name(), fileExists}, {tmpDir + "/" + nowStr, nil}, } for i, d := range data { e := SafeWriteToDisk(d.filename, reader, new(afero.OsFs)) if d.expectedErr != nil { if d.expectedErr.Error() != e.Error() { t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error()) } } else { if d.expectedErr != e { t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e) } contents, _ := ioutil.ReadFile(d.filename) if randomString != string(contents) { t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents)) } } reader.Seek(0, 0) } } func TestWriteToDisk(t *testing.T) { emptyFile, _ := createZeroSizedFileInTempDir() defer deleteFileInTempDir(emptyFile) tmpDir, _ := createEmptyTempDir() defer deleteTempDir(tmpDir) randomString := "This is a random string!" reader := strings.NewReader(randomString) type test struct { filename string expectedErr error } now := time.Now().Unix() nowStr := strconv.FormatInt(now, 10) data := []test{ {emptyFile.Name(), nil}, {tmpDir + "/" + nowStr, nil}, } for i, d := range data { e := WriteToDisk(d.filename, reader, new(afero.OsFs)) if d.expectedErr != e { t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e) } contents, e := ioutil.ReadFile(d.filename) if e != nil { t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e) } if randomString != string(contents) { t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents)) } reader.Seek(0, 0) } } func TestGetTempDir(t *testing.T) { dir := os.TempDir() if FilePathSeparator != dir[len(dir)-1:] { dir = dir + FilePathSeparator } testDir := "hugoTestFolder" + FilePathSeparator tests := []struct { input string expected string }{ {"", dir}, {testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator}, {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator}, {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator}, {testDir + "fOO,bar:foobAR", dir + testDir + "fOObarfoobAR" + FilePathSeparator}, {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator}, {testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator}, {testDir + "은행", dir + testDir + "은행" + FilePathSeparator}, {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator}, } for _, test := range tests { output := GetTempDir(test.input, new(afero.MemMapFs)) if output != test.expected { t.Errorf("Expected %#v, got %#v\n", test.expected, output) } } }
gohugoio/hugo
helpers/path_test.go
GO
apache-2.0
18,249
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.tcp; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import javax.net.ssl.SSLException; import org.apache.logging.log4j.Logger; import org.apache.geode.CancelCriterion; import org.apache.geode.CancelException; import org.apache.geode.SystemFailure; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.DistributedSystemDisconnectedException; import org.apache.geode.distributed.internal.DMStats; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.DistributionMessage; import org.apache.geode.distributed.internal.LonerDistributionManager; import org.apache.geode.distributed.internal.direct.DirectChannel; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.distributed.internal.membership.MembershipManager; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.LoggingExecutors; import org.apache.geode.internal.logging.LoggingThread; import org.apache.geode.internal.logging.log4j.AlertAppender; import org.apache.geode.internal.logging.log4j.LogMarker; import org.apache.geode.internal.net.SocketCreator; import org.apache.geode.internal.net.SocketCreatorFactory; import org.apache.geode.internal.security.SecurableCommunicationChannel; /** * <p> * TCPConduit manages a server socket and a collection of connections to other systems. Connections * are identified by DistributedMember IDs. These types of messages are currently supported: * </p> * * <pre> * <p> * DistributionMessage - message is delivered to the server's * ServerDelegate * <p> * </pre> * <p> * In the current implementation, ServerDelegate is the DirectChannel used by the GemFire * DistributionManager to send and receive messages. * <p> * If the ServerDelegate is null, DistributionMessages are ignored by the TCPConduit. * </p> * * @since GemFire 2.0 */ public class TCPConduit implements Runnable { private static final Logger logger = LogService.getLogger(); /** * max amount of time (ms) to wait for listener threads to stop */ private static int LISTENER_CLOSE_TIMEOUT; /** * backlog is the "accept" backlog configuration parameter all conduits server socket */ private static int BACKLOG; /** * use javax.net.ssl.SSLServerSocketFactory? */ static boolean useSSL; /** * Force use of Sockets rather than SocketChannels (NIO). Note from Bruce: due to a bug in the * java VM, NIO cannot be used with IPv6 addresses on Windows. When that condition holds, the * useNIO flag must be disregarded. */ private static boolean USE_NIO; /** * use direct ByteBuffers instead of heap ByteBuffers for NIO operations */ static boolean useDirectBuffers; /** * The socket producer used by the cluster */ private final SocketCreator socketCreator; private MembershipManager membershipManager; /** * true if NIO can be used for the server socket */ private boolean useNIO; static { init(); } public MembershipManager getMembershipManager() { return membershipManager; } public static int getBackLog() { return BACKLOG; } public static void init() { useSSL = Boolean.getBoolean("p2p.useSSL"); // only use nio if not SSL USE_NIO = !useSSL && !Boolean.getBoolean("p2p.oldIO"); // only use direct buffers if we are using nio useDirectBuffers = USE_NIO && !Boolean.getBoolean("p2p.nodirectBuffers"); LISTENER_CLOSE_TIMEOUT = Integer.getInteger("p2p.listenerCloseTimeout", 60000).intValue(); // fix for bug 37730 BACKLOG = Integer.getInteger("p2p.backlog", HANDSHAKE_POOL_SIZE + 1).intValue(); } ///////////////// permanent conduit state /** * the size of OS TCP/IP buffers, not set by default */ public int tcpBufferSize = DistributionConfig.DEFAULT_SOCKET_BUFFER_SIZE; public int idleConnectionTimeout = DistributionConfig.DEFAULT_SOCKET_LEASE_TIME; /** * port is the tcp/ip port that this conduit binds to. If it is zero, a port from * membership-port-range is selected to bind to. The actual port number this conduit is listening * on will be in the "id" instance variable */ private int port; private int[] tcpPortRange = new int[] {DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[0], DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1]}; /** * The java groups address that this conduit is associated with */ private InternalDistributedMember localAddr; /** * address is the InetAddress that this conduit uses for identity */ private final InetAddress address; /** * isBindAddress is true if we should bind to the address */ private final boolean isBindAddress; /** * the object that receives DistributionMessage messages received by this conduit. */ private final DirectChannel directChannel; private DMStats stats; /** * Config from the delegate * * @since GemFire 4.2.1 */ DistributionConfig config; ////////////////// runtime state that is re-initialized on a restart /** * server socket address */ private InetSocketAddress id; protected volatile boolean stopped; /** * the listener thread */ private Thread thread; /** * if using NIO, this is the object used for accepting connections */ private ServerSocketChannel channel; /** * the server socket */ private ServerSocket socket; /** * a table of Connections from this conduit to others */ private ConnectionTable conTable; /** * <p> * creates a new TCPConduit bound to the given InetAddress and port. The given ServerDelegate will * receive any DistributionMessages passed to the conduit. * </p> * <p> * This constructor forces the conduit to ignore the following system properties and look for them * only in the <i>props</i> argument: * </p> * * <pre> * p2p.tcpBufferSize * p2p.idleConnectionTimeout * </pre> */ public TCPConduit(MembershipManager mgr, int port, InetAddress address, boolean isBindAddress, DirectChannel receiver, Properties props) throws ConnectionException { parseProperties(props); this.address = address; this.isBindAddress = isBindAddress; this.port = port; this.directChannel = receiver; this.stats = null; this.config = null; this.membershipManager = mgr; if (directChannel != null) { this.stats = directChannel.getDMStats(); this.config = directChannel.getDMConfig(); } if (this.getStats() == null) { this.stats = new LonerDistributionManager.DummyDMStats(); } try { this.conTable = ConnectionTable.create(this); } catch (IOException io) { throw new ConnectionException( "Unable to initialize connection table", io); } this.socketCreator = SocketCreatorFactory.getSocketCreatorForComponent(SecurableCommunicationChannel.CLUSTER); this.useNIO = USE_NIO; if (this.useNIO) { InetAddress addr = address; if (addr == null) { try { addr = SocketCreator.getLocalHost(); } catch (java.net.UnknownHostException e) { throw new ConnectionException("Unable to resolve localHost address", e); } } // JDK bug 6230761 - NIO can't be used with IPv6 on Windows if (addr instanceof Inet6Address) { String os = System.getProperty("os.name"); if (os != null) { if (os.indexOf("Windows") != -1) { this.useNIO = false; } } } } startAcceptor(); } /** * parse instance-level properties from the given object */ private void parseProperties(Properties p) { if (p != null) { String s; s = p.getProperty("p2p.tcpBufferSize", "" + tcpBufferSize); try { tcpBufferSize = Integer.parseInt(s); } catch (Exception e) { logger.warn("exception parsing p2p.tcpBufferSize", e); } if (tcpBufferSize < Connection.SMALL_BUFFER_SIZE) { // enforce minimum tcpBufferSize = Connection.SMALL_BUFFER_SIZE; } s = p.getProperty("p2p.idleConnectionTimeout", "" + idleConnectionTimeout); try { idleConnectionTimeout = Integer.parseInt(s); } catch (Exception e) { logger.warn("exception parsing p2p.idleConnectionTimeout", e); } s = p.getProperty("membership_port_range_start"); try { tcpPortRange[0] = Integer.parseInt(s); } catch (Exception e) { logger.warn("Exception parsing membership-port-range start port.", e); } s = p.getProperty("membership_port_range_end"); try { tcpPortRange[1] = Integer.parseInt(s); } catch (Exception e) { logger.warn("Exception parsing membership-port-range end port.", e); } } } private ExecutorService hsPool; /** * the reason for a shutdown, if abnormal */ private volatile Exception shutdownCause; private static final int HANDSHAKE_POOL_SIZE = Integer.getInteger("p2p.HANDSHAKE_POOL_SIZE", 10).intValue(); private static final long HANDSHAKE_POOL_KEEP_ALIVE_TIME = Long.getLong("p2p.HANDSHAKE_POOL_KEEP_ALIVE_TIME", 60).longValue(); /** * added to fix bug 40436 */ public void setMaximumHandshakePoolSize(int maxSize) { if (this.hsPool != null) { ThreadPoolExecutor handshakePool = (ThreadPoolExecutor) this.hsPool; if (maxSize > handshakePool.getMaximumPoolSize()) { handshakePool.setMaximumPoolSize(maxSize); } } } /** * binds the server socket and gets threads going */ private void startAcceptor() throws ConnectionException { int localPort; int p = this.port; InetAddress ba = this.address; { ExecutorService tmp_hsPool = null; String threadName = "P2P-Handshaker " + ba + ":" + p + " Thread "; try { tmp_hsPool = LoggingExecutors.newThreadPoolWithSynchronousFeedThatHandlesRejection(threadName, null, null, 1, HANDSHAKE_POOL_SIZE, HANDSHAKE_POOL_KEEP_ALIVE_TIME); } catch (IllegalArgumentException poolInitException) { throw new ConnectionException( "while creating handshake pool", poolInitException); } this.hsPool = tmp_hsPool; } createServerSocket(); try { localPort = socket.getLocalPort(); id = new InetSocketAddress(socket.getInetAddress(), localPort); stopped = false; thread = new LoggingThread("P2P Listener Thread " + id, this); try { thread.setPriority(Thread.MAX_PRIORITY); } catch (Exception e) { logger.info("unable to set listener priority: {}", e.getMessage()); } if (!Boolean.getBoolean("p2p.test.inhibitAcceptor")) { thread.start(); } else { logger.fatal( "p2p.test.inhibitAcceptor was found to be set, inhibiting incoming tcp/ip connections"); socket.close(); this.hsPool.shutdownNow(); } } catch (IOException io) { String s = "While creating ServerSocket on port " + p; throw new ConnectionException(s, io); } this.port = localPort; } /** * creates the server sockets. This can be used to recreate the socket using this.port and * this.bindAddress, which must be set before invoking this method. */ private void createServerSocket() { int p = this.port; int b = BACKLOG; InetAddress bindAddress = this.address; try { if (this.useNIO) { if (p <= 0) { socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress, this.useNIO, 0, tcpPortRange); } else { ServerSocketChannel channel = ServerSocketChannel.open(); socket = channel.socket(); InetSocketAddress inetSocketAddress = new InetSocketAddress(isBindAddress ? bindAddress : null, p); socket.bind(inetSocketAddress, b); } if (useNIO) { try { // set these buffers early so that large buffers will be allocated // on accepted sockets (see java.net.ServerSocket.setReceiverBufferSize javadocs) socket.setReceiveBufferSize(tcpBufferSize); int newSize = socket.getReceiveBufferSize(); if (newSize != tcpBufferSize) { logger.info("{} is {} instead of the requested {}", "Listener receiverBufferSize", Integer.valueOf(newSize), Integer.valueOf(tcpBufferSize)); } } catch (SocketException ex) { logger.warn("Failed to set listener receiverBufferSize to {}", tcpBufferSize); } } channel = socket.getChannel(); } else { try { if (p <= 0) { socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress, this.useNIO, this.tcpBufferSize, tcpPortRange); } else { socket = socketCreator.createServerSocket(p, b, isBindAddress ? bindAddress : null, this.tcpBufferSize); } int newSize = socket.getReceiveBufferSize(); if (newSize != this.tcpBufferSize) { logger.info("Listener receiverBufferSize is {} instead of the requested {}", Integer.valueOf(newSize), Integer.valueOf(this.tcpBufferSize)); } } catch (SocketException ex) { logger.warn("Failed to set listener receiverBufferSize to {}", this.tcpBufferSize); } } port = socket.getLocalPort(); } catch (IOException io) { throw new ConnectionException( String.format("While creating ServerSocket on port %s with address %s", new Object[] {Integer.valueOf(p), bindAddress}), io); } } /** * Ensure that the ConnectionTable class gets loaded. * * @see SystemFailure#loadEmergencyClasses() */ public static void loadEmergencyClasses() { ConnectionTable.loadEmergencyClasses(); } /** * Close the ServerSocketChannel, ServerSocket, and the ConnectionTable. * * @see SystemFailure#emergencyClose() */ public void emergencyClose() { // stop(); // Causes grief if (stopped) { return; } stopped = true; try { if (channel != null) { channel.close(); // NOTE: do not try to interrupt the listener thread at this point. // Doing so interferes with the channel's socket logic. } else { if (socket != null) { socket.close(); } } } catch (IOException e) { // ignore, please! } // this.hsPool.shutdownNow(); // I don't trust this not to allocate objects or to synchronize // this.conTable.close(); not safe against deadlocks ConnectionTable.emergencyClose(); socket = null; thread = null; conTable = null; } /* stops the conduit, closing all tcp/ip connections */ public void stop(Exception cause) { if (!stopped) { stopped = true; shutdownCause = cause; if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "Shutting down conduit"); } try { // set timeout endpoint here since interrupt() has been known // to hang long timeout = System.currentTimeMillis() + LISTENER_CLOSE_TIMEOUT; Thread t = this.thread;; if (channel != null) { channel.close(); // NOTE: do not try to interrupt the listener thread at this point. // Doing so interferes with the channel's socket logic. } else { ServerSocket s = this.socket; if (s != null) { s.close(); } if (t != null) { t.interrupt(); } } do { t = this.thread; if (t == null || !t.isAlive()) { break; } t.join(200); } while (timeout > System.currentTimeMillis()); if (t != null && t.isAlive()) { logger.warn( "Unable to shut down listener within {}ms. Unable to interrupt socket.accept() due to JDK bug. Giving up.", Integer.valueOf(LISTENER_CLOSE_TIMEOUT)); } } catch (IOException | InterruptedException e) { // we're already trying to shutdown, ignore } finally { this.hsPool.shutdownNow(); } // close connections after shutting down acceptor to fix bug 30695 this.conTable.close(); socket = null; thread = null; conTable = null; } } /** * Returns whether or not this conduit is stopped * * @since GemFire 3.0 */ public boolean isStopped() { return this.stopped; } /** * starts the conduit again after it's been stopped. This will clear the server map if the * conduit's port is zero (wildcard bind) */ public void restart() throws ConnectionException { if (!stopped) { return; } this.stats = null; if (directChannel != null) { this.stats = directChannel.getDMStats(); } if (this.getStats() == null) { this.stats = new LonerDistributionManager.DummyDMStats(); } try { this.conTable = ConnectionTable.create(this); } catch (IOException io) { throw new ConnectionException( "Unable to initialize connection table", io); } startAcceptor(); } /** * this is the server socket listener thread's run loop */ public void run() { ConnectionTable.threadWantsSharedResources(); if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "Starting P2P Listener on {}", id); } for (;;) { SystemFailure.checkFailure(); if (stopper.isCancelInProgress()) { break; } if (stopped) { break; } if (Thread.currentThread().isInterrupted()) { break; } if (stopper.isCancelInProgress()) { break; // part of bug 37271 } Socket othersock = null; try { if (this.useNIO) { SocketChannel otherChannel = channel.accept(); othersock = otherChannel.socket(); } else { try { othersock = socket.accept(); } catch (SSLException ex) { // SW: This is the case when there is a problem in P2P // SSL configuration, so need to exit otherwise goes into an // infinite loop just filling the logs logger.warn("Stopping P2P listener due to SSL configuration problem.", ex); break; } othersock.setSoTimeout(0); socketCreator.handshakeIfSocketIsSSL(othersock, idleConnectionTimeout); } if (stopped) { try { if (othersock != null) { othersock.close(); } } catch (Exception e) { } continue; } acceptConnection(othersock); } catch (ClosedByInterruptException cbie) { // safe to ignore } catch (ClosedChannelException | CancelException e) { break; } catch (IOException e) { this.getStats().incFailedAccept(); try { if (othersock != null) { othersock.close(); } } catch (IOException ignore) { } if (!stopped) { if (e instanceof SocketException && "Socket closed".equalsIgnoreCase(e.getMessage())) { // safe to ignore; see bug 31156 if (!socket.isClosed()) { logger.warn("ServerSocket threw 'socket closed' exception but says it is not closed", e); try { socket.close(); createServerSocket(); } catch (IOException ioe) { logger.fatal("Unable to close and recreate server socket", ioe); // post 5.1.0x, this should force shutdown try { Thread.sleep(5000); } catch (InterruptedException ie) { // Don't reset; we're just exiting the thread logger.info("Interrupted and exiting while trying to recreate listener sockets"); return; } } } } else if ("Too many open files".equals(e.getMessage())) { getConTable().fileDescriptorsExhausted(); } else { logger.warn(e.getMessage(), e); } } } catch (Exception e) { logger.warn(e.getMessage(), e); } if (!stopped && socket.isClosed()) { // NOTE: do not check for distributed system closing here. Messaging // may need to occur during the closing of the DS or cache logger.warn("ServerSocket closed - reopening"); try { createServerSocket(); } catch (ConnectionException ex) { logger.warn(ex.getMessage(), ex); } } } // for if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace("Stopped P2P Listener on {}", id); } } private void acceptConnection(final Socket othersock) { try { this.hsPool.execute(new Runnable() { public void run() { basicAcceptConnection(othersock); } }); } catch (RejectedExecutionException rejected) { try { othersock.close(); } catch (IOException ignore) { } } } private ConnectionTable getConTable() { ConnectionTable result = this.conTable; if (result == null) { stopper.checkCancelInProgress(null); throw new DistributedSystemDisconnectedException( "tcp layer has been shutdown"); } return result; } protected void basicAcceptConnection(Socket othersock) { try { getConTable().acceptConnection(othersock, new PeerConnectionFactory()); } catch (IOException io) { // exception is logged by the Connection if (!stopped) { this.getStats().incFailedAccept(); } } catch (ConnectionException ex) { // exception is logged by the Connection if (!stopped) { this.getStats().incFailedAccept(); } } catch (CancelException e) { } catch (Exception e) { if (!stopped) { this.getStats().incFailedAccept(); logger.warn("Failed to accept connection from {} because {}", othersock.getInetAddress(), e); } } } /** * return true if "new IO" classes are being used for the server socket */ protected boolean useNIO() { return this.useNIO; } /** * records the current outgoing message count on all thread-owned ordered connections * * @since GemFire 5.1 */ public void getThreadOwnedOrderedConnectionState(DistributedMember member, Map result) { getConTable().getThreadOwnedOrderedConnectionState(member, result); } /** * wait for the incoming connections identified by the keys in the argument to receive and * dispatch the number of messages associated with the key * * @since GemFire 5.1 */ public void waitForThreadOwnedOrderedConnectionState(DistributedMember member, Map channelState) throws InterruptedException { getConTable().waitForThreadOwnedOrderedConnectionState(member, channelState); } /** * connections send messageReceived when a message object has been read. * * @param bytesRead number of bytes read off of network to get this message */ protected void messageReceived(Connection receiver, DistributionMessage message, int bytesRead) { if (logger.isTraceEnabled()) { logger.trace("{} received {} from {}", id, message, receiver); } if (directChannel != null) { DistributionMessage msg = message; msg.setBytesRead(bytesRead); msg.setSender(receiver.getRemoteAddress()); msg.setSharedReceiver(receiver.isSharedResource()); directChannel.receive(msg, bytesRead); } } /** * gets the address of this conduit's ServerSocket endpoint */ public InetSocketAddress getSocketId() { return id; } /** * gets the actual port to which this conduit's ServerSocket is bound */ public int getPort() { return id.getPort(); } /** * Gets the local member ID that identifies this conduit */ public InternalDistributedMember getMemberId() { return this.localAddr; } public void setMemberId(InternalDistributedMember addr) { localAddr = addr; } /** * Return a connection to the given member. This method must continue to attempt to create a * connection to the given member as long as that member is in the membership view and the system * is not shutting down. * * @param memberAddress the IDS associated with the remoteId * @param preserveOrder whether this is an ordered or unordered connection * @param retry false if this is the first attempt * @param startTime the time this operation started * @param ackTimeout the ack-wait-threshold * 1000 for the operation to be transmitted (or zero) * @param ackSATimeout the ack-severe-alert-threshold * 1000 for the operation to be transmitted * (or zero) * * @return the connection */ public Connection getConnection(InternalDistributedMember memberAddress, final boolean preserveOrder, boolean retry, long startTime, long ackTimeout, long ackSATimeout) throws java.io.IOException, DistributedSystemDisconnectedException { if (stopped) { throw new DistributedSystemDisconnectedException( "The conduit is stopped"); } Connection conn = null; InternalDistributedMember memberInTrouble = null; boolean breakLoop = false; for (;;) { stopper.checkCancelInProgress(null); boolean interrupted = Thread.interrupted(); try { // If this is the second time through this loop, we had // problems. Tear down the connection so that it gets // rebuilt. if (retry || conn != null) { // not first time in loop if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress) || membershipManager.shutdownInProgress()) { throw new IOException( "TCP/IP connection lost and member is not in view"); } // bug35953: Member is still in view; we MUST NOT give up! // Pause just a tiny bit... try { Thread.sleep(100); } catch (InterruptedException e) { interrupted = true; stopper.checkCancelInProgress(e); } // try again after sleep if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress)) { // OK, the member left. Just register an error. throw new IOException( "TCP/IP connection lost and member is not in view"); } // Print a warning (once) if (memberInTrouble == null) { memberInTrouble = memberAddress; logger.warn("Attempting TCP/IP reconnect to {}", memberInTrouble); } else { if (logger.isDebugEnabled()) { logger.debug("Attempting TCP/IP reconnect to {}", memberInTrouble); } } // Close the connection (it will get rebuilt later). this.getStats().incReconnectAttempts(); if (conn != null) { try { if (logger.isDebugEnabled()) { logger.debug("Closing old connection. conn={} before retrying. memberInTrouble={}", conn, memberInTrouble); } conn.closeForReconnect("closing before retrying"); } catch (CancelException ex) { throw ex; } catch (Exception ex) { } } } // not first time in loop Exception problem = null; try { // Get (or regenerate) the connection // bug36202: this could generate a ConnectionException, so it // must be caught and retried boolean retryForOldConnection; boolean debugRetry = false; do { retryForOldConnection = false; conn = getConTable().get(memberAddress, preserveOrder, startTime, ackTimeout, ackSATimeout); if (conn == null) { // conduit may be closed - otherwise an ioexception would be thrown problem = new IOException( String.format("Unable to reconnect to server; possible shutdown: %s", memberAddress)); } else if (conn.isClosing() || !conn.getRemoteAddress().equals(memberAddress)) { if (logger.isDebugEnabled()) { logger.debug("Got an old connection for {}: {}@{}", memberAddress, conn, conn.hashCode()); } conn.closeOldConnection("closing old connection"); conn = null; retryForOldConnection = true; debugRetry = true; } } while (retryForOldConnection); if (debugRetry && logger.isDebugEnabled()) { logger.debug("Done removing old connections"); } // we have a connection; fall through and return it } catch (ConnectionException e) { // Race condition between acquiring the connection and attempting // to use it: another thread closed it. problem = e; // [sumedh] No need to retry since Connection.createSender has already // done retries and now member is really unreachable for some reason // even though it may be in the view breakLoop = true; } catch (IOException e) { problem = e; // bug #43962 don't keep trying to connect to an alert listener if (AlertAppender.isThreadAlerting()) { if (logger.isDebugEnabled()) { logger.debug("Giving up connecting to alert listener {}", memberAddress); } breakLoop = true; } } if (problem != null) { // Some problems are not recoverable; check and error out early. if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress)) { // left the view // Bracket our original warning if (memberInTrouble != null) { // make this msg info to bracket warning logger.info("Ending reconnect attempt because {} has disappeared.", memberInTrouble); } throw new IOException(String.format("Peer has disappeared from view: %s", memberAddress)); } // left the view if (membershipManager.shutdownInProgress()) { // shutdown in progress // Bracket our original warning if (memberInTrouble != null) { // make this msg info to bracket warning logger.info("Ending reconnect attempt to {} because shutdown has started.", memberInTrouble); } stopper.checkCancelInProgress(null); throw new DistributedSystemDisconnectedException( "Abandoned because shutdown is in progress"); } // shutdown in progress // Log the warning. We wait until now, because we want // to have m defined for a nice message... if (memberInTrouble == null) { logger.warn("Error sending message to {} (will reattempt): {}", memberAddress, problem); memberInTrouble = memberAddress; } else { if (logger.isDebugEnabled()) { logger.debug("Error sending message to {}", memberAddress, problem); } } if (breakLoop) { if (!problem.getMessage().startsWith("Cannot form connection to alert listener")) { logger.warn("Throwing IOException after finding breakLoop=true", problem); } if (problem instanceof IOException) { throw (IOException) problem; } else { IOException ioe = new IOException(String.format("Problem connecting to %s", memberAddress)); ioe.initCause(problem); throw ioe; } } // Retry the operation (indefinitely) continue; } // problem != null // Success! // Make sure our logging is bracketed if there was a problem if (memberInTrouble != null) { logger.info("Successfully reconnected to member {}", memberInTrouble); if (logger.isTraceEnabled()) { logger.trace("new connection is {} memberAddress={}", conn, memberAddress); } } return conn; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // for(;;) } @Override public String toString() { return "" + id; } /** * Returns the distribution manager of the direct channel */ public DistributionManager getDM() { return directChannel.getDM(); } public void removeEndpoint(DistributedMember mbr, String reason, boolean notifyDisconnect) { ConnectionTable ct = this.conTable; if (ct == null) { return; } ct.removeEndpoint(mbr, reason, notifyDisconnect); } /** * check to see if there are still any receiver threads for the given end-point */ public boolean hasReceiversFor(DistributedMember endPoint) { ConnectionTable ct = this.conTable; return (ct != null) && ct.hasReceiversFor(endPoint); } /** * Stats from the delegate */ public DMStats getStats() { return stats; } protected class Stopper extends CancelCriterion { @Override public String cancelInProgress() { DistributionManager dm = getDM(); if (dm == null) { return "no distribution manager"; } if (TCPConduit.this.stopped) { return "Conduit has been stopped"; } return null; } @Override public RuntimeException generateCancelledException(Throwable e) { String reason = cancelInProgress(); if (reason == null) { return null; } DistributionManager dm = getDM(); if (dm == null) { return new DistributedSystemDisconnectedException("no distribution manager"); } RuntimeException result = dm.getCancelCriterion().generateCancelledException(e); if (result != null) { return result; } // We know we've been stopped; generate the exception result = new DistributedSystemDisconnectedException("Conduit has been stopped"); result.initCause(e); return result; } } private final Stopper stopper = new Stopper(); public CancelCriterion getCancelCriterion() { return stopper; } /** * if the conduit is disconnected due to an abnormal condition, this will describe the reason * * @return exception that caused disconnect */ public Exception getShutdownCause() { return this.shutdownCause; } /** * returns the SocketCreator that should be used to produce sockets for TCPConduit connections. */ protected SocketCreator getSocketCreator() { return socketCreator; } /** * ARB: Called by Connection before handshake reply is sent. Returns true if member is part of * view, false if membership is not confirmed before timeout. */ public boolean waitForMembershipCheck(InternalDistributedMember remoteId) { return membershipManager.waitForNewMember(remoteId); } }
pdxrunner/geode
geode-core/src/main/java/org/apache/geode/internal/tcp/TCPConduit.java
Java
apache-2.0
37,478
package view; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.border.Border; import model.Manufacturer; import model.Model; public class FormPanel extends JPanel { private JLabel nameLabel; private JLabel phoneLabel; private JLabel creationDateLabel; private JLabel carInfoLabel; private JTextField nameField; private JTextField phoneField; private JFormattedTextField creationDateField; private static final String CMAN_NOT_SELECTABLE_OPTION = "-Válassz autógyártót-"; private JComboBox<String> carManComboBox; private static final String CMOD_NOT_SELECTABLE_OPTION = "-Válassz autótípust-"; private JComboBox<String> carModelComboBox; private JTextField licensePlateNoField; private JTextField yearField; private JTextField colorField; private JTextField odometerField; private JLabel licensePlateNoLabel; private JLabel yearLabel; private JLabel colorLabel; private JLabel odometerLabel; private JButton okBtn; private FormListener formListener; private CarManChooserListener carManChooserListener; public FormPanel(List<Manufacturer> manufacturers) { Dimension dim = getPreferredSize(); dim.width = 250; setPreferredSize(dim); nameLabel = new JLabel("*Név: "); phoneLabel = new JLabel("Telefonszám: "); creationDateLabel = new JLabel("Mai dátum: "); carInfoLabel = new JLabel("Gépjármű információk: "); nameField = new JTextField(10); phoneField = new JTextField(10); carManComboBox = new JComboBox<String>(); carModelComboBox = new JComboBox<String>(); licensePlateNoField = new JTextField(10); yearField = new JTextField(10); colorField = new JTextField(10); odometerField = new JTextField(10); licensePlateNoLabel = new JLabel("Rendszám: "); yearLabel = new JLabel("Gyártási év: "); colorLabel = new JLabel("Szín: "); odometerLabel = new JLabel("Km-óra állás: "); licensePlateNoField.setText("*Rendszám"); licensePlateNoField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { if(licensePlateNoField.getText().trim().equals("")) licensePlateNoField.setText("*Rendszám"); } public void focusGained(FocusEvent e) { if(licensePlateNoField.getText().trim().equals("*Rendszám")) licensePlateNoField.setText(""); } }); yearField.setText("Gyártási év"); yearField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { if(yearField.getText().trim().equals("")) yearField.setText("Gyártási év"); } public void focusGained(FocusEvent e) { if(yearField.getText().trim().equals("Gyártási év")) yearField.setText(""); } }); colorField.setText("Gépjármű színe"); colorField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { if(colorField.getText().trim().equals("")) colorField.setText("Gépjármű színe"); } public void focusGained(FocusEvent e) { if(colorField.getText().trim().equals("Gépjármű színe")) colorField.setText(""); } }); odometerField.setText("Kilóméteróra állás"); odometerField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { if(odometerField.getText().trim().equals("")) odometerField.setText("Kilóméteróra állás"); } public void focusGained(FocusEvent e) { if(odometerField.getText().trim().equals("Kilóméteróra állás")) odometerField.setText(""); } }); carModelComboBox.setVisible(false); carManComboBox.setModel(new DefaultComboBoxModel<String>() { boolean selectionAllowed = true; public void setSelectedItem(Object anObject) { if (!CMAN_NOT_SELECTABLE_OPTION.equals(anObject)) { super.setSelectedItem(anObject); } else if (selectionAllowed) { // Allow this just once selectionAllowed = false; super.setSelectedItem(anObject); } } }); carModelComboBox.setModel(new DefaultComboBoxModel<String>() { boolean selectionAllowed = true; public void setSelectedItem(Object anObject) { if (!CMOD_NOT_SELECTABLE_OPTION.equals(anObject)) { super.setSelectedItem(anObject); } else if (selectionAllowed) { // Allow this just once selectionAllowed = false; super.setSelectedItem(anObject); } } }); carManComboBox.addItem(CMAN_NOT_SELECTABLE_OPTION); for (Manufacturer man : manufacturers) { carManComboBox.addItem(man.getManufacturerName()); } Date todaysDate = new Date(); SimpleDateFormat dateformat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); creationDateField = new JFormattedTextField( dateformat.format(todaysDate)); creationDateField.setEditable(false); okBtn = new JButton("OK"); okBtn.setMnemonic(KeyEvent.VK_O); nameLabel.setDisplayedMnemonic(KeyEvent.VK_N); nameLabel.setLabelFor(nameField); phoneLabel.setDisplayedMnemonic(KeyEvent.VK_T); phoneLabel.setLabelFor(phoneField); carManComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String carMan = (String) carManComboBox.getSelectedItem(); CarManChooserEvent eCM = new CarManChooserEvent(this, carMan); if (carManChooserListener != null) { carManChooserListener.carManChooserEventOccured(eCM); } } }); okBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = nameField.getText(); String phoneNum = phoneField.getText(); Date creationDate = new Date(); String carMan = (String) carManComboBox.getSelectedItem(); String carModel = (String) carModelComboBox.getSelectedItem(); String licensePlateNo = licensePlateNoField.getText(); String year = yearField.getText(); String color = colorField.getText(); String odometer = odometerField.getText(); if( year.equals("Gyártási év") ){ year = ""; } if( color.equals("Gépjármű színe") ){ color = ""; } if (name.equals("")) { JOptionPane.showMessageDialog(FormPanel.this, "A 'Név' mező nem maradhat üresen!", "Adatbázis hiba", JOptionPane.ERROR_MESSAGE); } else if(carMan.equals(CMAN_NOT_SELECTABLE_OPTION)){ JOptionPane.showMessageDialog(FormPanel.this, "Autógyártó választása kötelező!", "Adatbázis hiba", JOptionPane.ERROR_MESSAGE); } else if(carModel.equals(CMOD_NOT_SELECTABLE_OPTION)){ JOptionPane.showMessageDialog(FormPanel.this, "Autótípus választása kötelező!", "Adatbázis hiba", JOptionPane.ERROR_MESSAGE); } else if(licensePlateNo.equals("*Rendszám")){ JOptionPane.showMessageDialog(FormPanel.this, "Rendszám megadása kötelező!", "Adatbázis hiba", JOptionPane.ERROR_MESSAGE); } else if(!odometer.equals("Kilóméteróra állás") && !isInteger(odometer) ){ JOptionPane.showMessageDialog(FormPanel.this, "A kilóméteróra állás szám kell hogy legyen!", "Adatbázis hiba", JOptionPane.ERROR_MESSAGE); } else { Integer odoMeter; if( odometer.equals("Kilóméteróra állás") ){ odoMeter = 0; } else{ odoMeter = Integer.parseInt(odometer); } nameField.setText(""); phoneField.setText(""); licensePlateNoField.setText("*Rendszám"); yearField.setText("Gyártási év"); colorField.setText("Gépjármű színe"); odometerField.setText("Kilóméteróra állás"); FormEvent ev = new FormEvent(this, name, phoneNum, creationDate, carMan, carModel, licensePlateNo, year, color, odoMeter); if (formListener != null) { formListener.formEventOccured(ev); } } } }); Border innerBorder = BorderFactory.createTitledBorder("Új ügyfél"); Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5); setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder)); layoutComponents(); } public void layoutComponents() { setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); // Name label and name field gc.gridy = 0; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.LINE_END; gc.insets = new Insets(0, 0, 0, 5); add(nameLabel, gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(nameField, gc); // Phone label and name field gc.gridy++; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_END; gc.insets = new Insets(0, 0, 0, 5); add(phoneLabel, gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(phoneField, gc); // Date gc.gridy++; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_END; gc.insets = new Insets(0, 0, 0, 5); add(creationDateLabel, gc); gc.gridx++; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(creationDateField, gc); ////////////// Separator ////////////// gc.gridy++; gc.gridx = 0; gc.weightx = 1.0; gc.weighty = 0.3; gc.fill = GridBagConstraints.HORIZONTAL; gc.gridwidth = GridBagConstraints.REMAINDER; add(new JSeparator(JSeparator.HORIZONTAL), gc); // Car info label gc.gridy++; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_START; gc.fill = GridBagConstraints.NONE; gc.insets = new Insets(0, 0, 0, 0); add(carInfoLabel, gc); // Car manufacturer chooser gc.gridy++; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_END; gc.fill = GridBagConstraints.NONE; gc.insets = new Insets(5, 0, 0, 0); add(carManComboBox, gc); // Car model chooser gc.gridy++; gc.gridx = 0; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_END; gc.fill = GridBagConstraints.NONE; gc.insets = new Insets(5, 0, 0, 0); add(carModelComboBox, gc); // Car license plate no. gc.gridy++; gc.gridx = 1; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(licensePlateNoField, gc); // Car year gc.gridy++; gc.gridx = 1; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(yearField, gc); // Car color gc.gridy++; gc.gridx = 1; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(colorField, gc); // Car odometer gc.gridy++; gc.gridx = 1; gc.weightx = 1; gc.weighty = 0.1; gc.anchor = GridBagConstraints.LINE_START; gc.insets = new Insets(0, 0, 0, 0); add(odometerField, gc); // OK Button gc.gridy++; gc.gridx = 1; gc.weightx = 1; gc.weighty = 1.5; gc.anchor = GridBagConstraints.FIRST_LINE_START; gc.fill = GridBagConstraints.NONE; gc.insets = new Insets(0, 0, 0, 5); add(okBtn, gc); } public void setFormListener(FormListener listener) { this.formListener = listener; } public void setCarManChooserListener(CarManChooserListener listener) { this.carManChooserListener = listener; } public void setCarModelComboBox(List<Model> models) { this.carModelComboBox.removeAllItems(); carModelComboBox.addItem(CMOD_NOT_SELECTABLE_OPTION); for (Model model : models) { this.carModelComboBox.addItem(model.getModelName()); } carModelComboBox.setVisible(true); } public static boolean isInteger(String str) { int length = str.length(); int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c <= '/' || c >= ':') { return false; } } return true; } }
TibiSecurity/progkorny
src/main/java/view/FormPanel.java
Java
apache-2.0
12,691
<?php function error($code, $msg, $file, $line) { //为了安全起见,不暴露出真实物理路径,下面两行过滤实际路径 $file = str_replace(getcwd(), "", $file); $msg = str_replace(getcwd(), "", $msg); switch ($code) { case E_USER_ERROR : $msg = "自定义ERROR——".$msg; break; case E_USER_WARNING : $msg = "自定义WARNING——".$msg; break; case E_USER_NOTICE : $msg = "自定义NOTICE——".$msg; break; case E_ERROR : $msg = "致命错误——".$msg; break; case E_WARNING : $msg = "WARNING——".$msg; break; case E_NOTICE : $msg = "NOTICE——".$msg; break; default : $msg = "未知错误类型——".$msg; break; } echo '<div style="width:80%;border:1px solid red; margin:auto auto 15px auto; background:#FFFFFF;">'; echo '<div style="background:orange;font-size:9.5pt;padding:0px 5px;border-bottom:1px dashed red;"><b>错误信息:</b>' . $msg . "</div>"; echo '<div style="font-size:9.5pt;padding:0px 5px;border-bottom:1px dashed red;"><b>错误代码:</b>' . $code . "</div>"; echo '<div style="font-size:9.5pt;padding:0px 5px;border-bottom:1px dashed red;"><b>报错文件:</b>' . $file . "</div>"; echo '<div style="font-size:9.5pt;padding:0px 5px;"><b>报错行号:</b>' . $line . "</div></div>"; /* Don't execute PHP internal error handler */ return true; }
mfy/EasyVote
app/common/error.php
PHP
apache-2.0
1,376
package com.example.android.sunshine.app; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.ShareActionProvider; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.overman.weather.app.R; public class DetailActivity extends ActionBarActivity { //private ShareActionProvider mShareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new DetailFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { final String LOG_TAG = "onCreateOptionsMenu"; // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { //Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view */ public class DetailFragment extends Fragment { private String LOG_TAG = this.getClass().getSimpleName(); private static final String SHARE_HASHTAG = " #WeatherApp"; private String forecastStr; public DetailFragment() { setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_detail, container, false); Intent intent = getActivity().getIntent(); if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) { forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT); ((TextView) rootView.findViewById(R.id.detail_text)) .setText(forecastStr); } return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.detailfragment, menu); // Retrieve the share menu item MenuItem menuItem = menu.findItem(R.id.menu_item_share); // Get the provider and hold onto it to set/change the share intent ShareActionProvider myShareActionProvider = new ShareActionProvider(getActivity()); MenuItemCompat.setActionProvider(menuItem, myShareActionProvider); // ShareActionProvider myShareActionProvider = // (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); // Attach an intent to this provider. // if (myShareActionProvider != null) { // myShareActionProvider.setShareIntent(createShareForecastIntent()); // } else { // Log.d(LOG_TAG, "share actionprovider is null ?!?"); // } Intent myShareIntent = createShareForecastIntent(); myShareActionProvider.setShareIntent(myShareIntent); } private Intent createShareForecastIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, forecastStr + SHARE_HASHTAG); return shareIntent; } } }
michaeloverman/Weather
app/src/main/java/com/example/android/sunshine/app/DetailActivity.java
Java
apache-2.0
4,561
package com.youcan.core; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.youcan.core.l; public class l { protected l() { //do nothing System.out.println("l started."); } private static Logger log; public static final boolean init(String logName) { if ((log = LogManager.exists(logName)) != null) { return true; } return false; } public static final void print(Object message) { System.out.print(message); } public static final void println(Object message) { System.out.println(message); } public static final void warn(Object message) { log.warn(message); } public static final void info(Object message) { log.info(message); } public static final void debug(Object message) { log.debug(message); } public static final void error(Object message) { log.error(message); } public static final void error(Object message, Throwable t) { log.error(message, t); } public static final void fatal(Object message) { log.fatal(message); } public static final void fatal(Object message, Throwable t) { log.fatal(message, t); } public static final Logger getLog() { return log; } public static final void setLog(Logger log) { l.log = log; } }
jiaozhujun/c3f
src-core/com/youcan/core/l.java
Java
apache-2.0
1,306
/* ** 2013 October 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package common.zeroquest.entity.helper; import java.util.Random; import common.zeroquest.entity.EntityJakanPrime; import net.minecraft.entity.DataWatcher; import net.minecraft.nbt.NBTTagCompound; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class CustomJakanHelper { protected final EntityJakanPrime dragon; protected final DataWatcher dataWatcher; protected final Random rand; public CustomJakanHelper(EntityJakanPrime dragon) { this.dragon = dragon; this.dataWatcher = dragon.getDataWatcher(); this.rand = dragon.getRNG(); } public void writeToNBT(NBTTagCompound nbt) {} public void readFromNBT(NBTTagCompound nbt) {} public void applyEntityAttributes() {} public void onLivingUpdate() {} public void onDeathUpdate() {} public void onDeath() {} }
NovaViper/ZeroQuest
1.6.4-src/common/zeroquest/entity/helper/CustomJakanHelper.java
Java
apache-2.0
1,197
/* * Copyright 2013 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. */ //-------------------------------------------------------------------------------- // TeapotRenderer.cpp // Render a teapot //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Include files //-------------------------------------------------------------------------------- #include "TeapotRenderer.h" //-------------------------------------------------------------------------------- // Teapot model data //-------------------------------------------------------------------------------- #include "teapot.inl" MATERIAL_PARAMETERS TeapotRenderer::materials_[] = { { "Gold", { {0.f, 0.f, 0.f}, {1.f, 0.765557f, 0.336057f, 0.f }, { 0,0,0 } } }, { "Copper", { {0.f, 0.f, 0.f}, {0.955008f, 0.637427f, 0.538163, 0.f }, { 0,0,0 } } }, { "Plastic", { {0.9f, 0.f, 0.f}, {0.2f, 0.2f, 0.2f, 0.f }, { 0,0,0 } } }, }; const int32_t TeapotRenderer::NUM_MATERIALS = sizeof(TeapotRenderer::materials_)/sizeof(TeapotRenderer::materials_[0]); //-------------------------------------------------------------------------------- // Ctor //-------------------------------------------------------------------------------- TeapotRenderer::TeapotRenderer() : roughness_(0.f), current_material(0) {} //-------------------------------------------------------------------------------- // Dtor //-------------------------------------------------------------------------------- TeapotRenderer::~TeapotRenderer() { Unload(); } void TeapotRenderer::Init() { // Settings glFrontFace(GL_CCW); // // // // SRGB test // Enable Linear space #if 0 glEnable(GL_FRAMEBUFFER_SRGB_EXT); if( glIsEnabled(GL_EXT_sRGB_write_control)) { LOGI("Enabled!!!"); } glEnable(GL_EXT_sRGB_write_control); if( glIsEnabled(GL_EXT_sRGB_write_control)) { LOGI("Enabled!!!"); } #endif // FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING // // // // Load shader LoadShaders(&shader_param_, "Shaders/VS_ShaderPlain.vsh", "Shaders/ShaderPlain.fsh"); // Create Index buffer num_indices_ = sizeof(teapotIndices) / sizeof(teapotIndices[0]); glGenBuffers(1, &ibo_); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(teapotIndices), teapotIndices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Create VBO num_vertices_ = sizeof(teapotPositions) / sizeof(teapotPositions[0]) / 3; int32_t iStride = sizeof(TEAPOT_VERTEX); int32_t iIndex = 0; TEAPOT_VERTEX* p = new TEAPOT_VERTEX[num_vertices_]; for (int32_t i = 0; i < num_vertices_; ++i) { p[i].pos[0] = teapotPositions[iIndex]; p[i].pos[1] = teapotPositions[iIndex + 1]; p[i].pos[2] = teapotPositions[iIndex + 2]; p[i].normal[0] = teapotNormals[iIndex]; p[i].normal[1] = teapotNormals[iIndex + 1]; p[i].normal[2] = teapotNormals[iIndex + 2]; iIndex += 3; } glGenBuffers(1, &vbo_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, iStride * num_vertices_, p, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //Create cubemap //CreateCubemap(); delete[] p; UpdateViewport(); mat_model_ = ndk_helper::Mat4::Translation(0, 0, -15.f); ndk_helper::Mat4 mat = ndk_helper::Mat4::RotationX(M_PI / 3); mat_model_ = mat * mat_model_; } void TeapotRenderer::SwitchStage(const char* file_name) { LOGI("Loading Cubemap Textures"); if (tex_cubemap_) { glDeleteTextures(1, &tex_cubemap_); tex_cubemap_ = 0; } // Create Cubemap glGenTextures(1, &tex_cubemap_); glBindTexture(GL_TEXTURE_CUBE_MAP, tex_cubemap_); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); //128x128 - 1x1 cubemaps // Create Cubemap glGenTextures(1, &tex_cubemap_); glBindTexture(GL_TEXTURE_CUBE_MAP, tex_cubemap_); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, MIPLEVELS - 1); //128x128 - 1x1 cubemaps for( int32_t i = 0; i < MIPLEVELS; ++i ) { const int32_t BUFFER_SIZE = 256; char file_name_buffer[BUFFER_SIZE]; //#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 //#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 //#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A for(int32_t face = 0; face < 6; ++face) { snprintf(file_name_buffer, BUFFER_SIZE, file_name, i, face); ndk_helper::JNIHelper::GetInstance()->LoadCubemapTexture(file_name_buffer, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, i, false); } } glGenerateMipmap(GL_TEXTURE_CUBE_MAP); } void TeapotRenderer::UpdateViewport() { // Init Projection matrices int32_t viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); float fAspect; const float CAM_NEAR = 5.f; const float CAM_FAR = 10000.f; // Set aspect ratio as wider axis becomes -1-1 to show sprite in same physical size on screen if (viewport[2] < viewport[3]) { fAspect = (float) viewport[2] / (float) viewport[3]; mat_projection_ = ndk_helper::Mat4::Perspective(fAspect, 1.f, CAM_NEAR, CAM_FAR); } else { // Landscape orientation fAspect = (float) viewport[3] / (float) viewport[2]; mat_projection_ = ndk_helper::Mat4::Perspective(1.f, fAspect, CAM_NEAR, CAM_FAR); } } void TeapotRenderer::Unload() { if (vbo_) { glDeleteBuffers(1, &vbo_); vbo_ = 0; } if (ibo_) { glDeleteBuffers(1, &ibo_); ibo_ = 0; } if (tex_cubemap_) { glDeleteTextures(1, &tex_cubemap_); tex_cubemap_ = 0; } if (shader_param_.program_) { glDeleteProgram(shader_param_.program_); shader_param_.program_ = 0; } } const float CAM_X = 0.f; const float CAM_Y = 0.f; const float CAM_Z = 700.f; void TeapotRenderer::Update(const double time) { mat_view_ = ndk_helper::Mat4::LookAt(ndk_helper::Vec3(CAM_X, CAM_Y, CAM_Z), ndk_helper::Vec3(0.f, 0.f, 0.f), ndk_helper::Vec3(0.f, 1.f, 0.f)); if (camera_) { camera_->Update(time); mat_view_ = camera_->GetTransformMatrix() * mat_view_ * camera_->GetRotationMatrix() * mat_model_; } else { mat_view_ = mat_view_ * mat_model_; } } void TeapotRenderer::Render() { // Feed Projection and Model View matrices to the shaders ndk_helper::Mat4 mat_vp = mat_projection_ * mat_view_; // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, vbo_); int32_t iStride = sizeof(TEAPOT_VERTEX); // Pass the vertex data glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, iStride, BUFFER_OFFSET(0)); glEnableVertexAttribArray(ATTRIB_VERTEX); glVertexAttribPointer(ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, iStride, BUFFER_OFFSET(3 * sizeof(GLfloat))); glEnableVertexAttribArray(ATTRIB_NORMAL); // Bind the IB glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_); glUseProgram(shader_param_.program_); /* R G B Silver 0.971519 0.959915 0.915324 Aluminium 0.913183 0.921494 0.924524 Gold 1 0.765557 0.336057 Copper 0.955008 0.637427 0.538163 Chromium 0.549585 0.556114 0.554256 Nickel 0.659777 0.608679 0.525649 Titanium 0.541931 0.496791 0.449419 Cobalt 0.662124 0.654864 0.633732 Platinum 0.672411 0.637331 0.585456 * */ TEAPOT_MATERIALS material = { { 1.0f, 0.5f, 0.5f }, { 1.0f, 0.765557, 0.538163, 10.f }, //Gold specular { 0.1f, 0.1f, 0.1f }, }; //Update uniforms TEAPOT_MATERIALS& mat = materials_[current_material].material; glUniform3f(shader_param_.material_diffuse_, mat.diffuse_color[0], mat.diffuse_color[1], mat.diffuse_color[2]); glUniform4f(shader_param_.material_specular_, mat.specular_color[0], mat.specular_color[1], mat.specular_color[2], mat.specular_color[3]); // //using glUniform3fv here was troublesome // glUniform3f(shader_param_.material_ambient_, mat.ambient_color[0], mat.ambient_color[1], mat.ambient_color[2]); glUniformMatrix4fv(shader_param_.matrix_projection_, 1, GL_FALSE, mat_vp.Ptr()); glUniformMatrix4fv(shader_param_.matrix_view_, 1, GL_FALSE, mat_view_.Ptr()); //Dynamic light glUniform3f(shader_param_.light0_, 200.f, -200.f, -200.f); glUniform3f(shader_param_.camera_pos_, CAM_X, CAM_Y, CAM_Z); // Set cubemap glEnable(GL_TEXTURE_CUBE_MAP); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, tex_cubemap_); glUniform1i(shader_param_.sampler0_, 0); glUniform2f(shader_param_.roughness_, roughness_, MIPLEVELS-1); glDrawElements(GL_TRIANGLES, num_indices_, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0)); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } bool TeapotRenderer::LoadShaders(SHADER_PARAMS* params, const char* strVsh, const char* strFsh) { GLuint program; GLuint vert_shader, frag_shader; char* vert_shader_pathname, *frag_shader_pathname; // Create shader program program = glCreateProgram(); LOGI("Created Shader %d", program); // Create and compile vertex shader if (!ndk_helper::shader::CompileShader(&vert_shader, GL_VERTEX_SHADER, strVsh)) { LOGI("Failed to compile vertex shader"); glDeleteProgram(program); return false; } // Create and compile fragment shader if (!ndk_helper::shader::CompileShader(&frag_shader, GL_FRAGMENT_SHADER, strFsh)) { LOGI("Failed to compile fragment shader"); glDeleteProgram(program); return false; } // Attach vertex shader to program glAttachShader(program, vert_shader); // Attach fragment shader to program glAttachShader(program, frag_shader); // Bind attribute locations // this needs to be done prior to linking glBindAttribLocation(program, ATTRIB_VERTEX, "myVertex"); glBindAttribLocation(program, ATTRIB_NORMAL, "myNormal"); glBindAttribLocation(program, ATTRIB_UV, "myUV"); // Link program if (!ndk_helper::shader::LinkProgram(program)) { LOGI("Failed to link program: %d", program); if (vert_shader) { glDeleteShader(vert_shader); vert_shader = 0; } if (frag_shader) { glDeleteShader(frag_shader); frag_shader = 0; } if (program) { glDeleteProgram(program); } return false; } // Get uniform locations params->matrix_projection_ = glGetUniformLocation(program, "uPMatrix"); params->matrix_view_ = glGetUniformLocation(program, "uMVMatrix"); params->light0_ = glGetUniformLocation(program, "vLight0"); params->camera_pos_ = glGetUniformLocation(program, "vCamera"); params->material_diffuse_ = glGetUniformLocation(program, "vMaterialDiffuse"); params->material_ambient_ = glGetUniformLocation(program, "vMaterialAmbient"); params->material_specular_ = glGetUniformLocation(program, "vMaterialSpecular"); params->sampler0_ = glGetUniformLocation( program, "sCubemapTexture" ); params->roughness_ = glGetUniformLocation(program, "vRoughness"); // Release vertex and fragment shaders if (vert_shader) glDeleteShader(vert_shader); if (frag_shader) glDeleteShader(frag_shader); params->program_ = program; return true; } bool TeapotRenderer::Bind(ndk_helper::TapCamera* camera) { camera_ = camera; return true; } // //Material control // void TeapotRenderer::SwitchMaterial() { current_material = (current_material + 1) % NUM_MATERIALS; } const char* TeapotRenderer::GetMaterialName() { return materials_[current_material].material_name; }
hak/AndroidPhysicallyBasedRendering
jni/TeapotRenderer.cpp
C++
apache-2.0
13,459
""" Copyright 2016 Andrea McIntosh 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. """ from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views import generic from .models import Question, Choice class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except: return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
akmcinto/TodoApp
ToDoApp/polls/views.py
Python
apache-2.0
1,788
/* * Copyright 2020 Verizon Media * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import Header from '../components/header/Header'; import UserDomains from '../components/domain/UserDomains'; import API from '../api.js'; import styled from '@emotion/styled'; import Head from 'next/head'; import Search from '../components/search/Search'; import RequestUtils from '../components/utils/RequestUtils'; import Error from './_error'; import createCache from '@emotion/cache'; import { CacheProvider } from '@emotion/react'; const HomeContainerDiv = styled.div` flex: 1 1; `; const HomeContentDiv = styled.div` align-items: center; height: 100%; justify-content: flex-start; width: 100%; display: flex; flex-direction: column; `; const Logo = ({ className }) => ( <img src='/static/athenz-logo.png' className={className} /> ); const LogoStyled = styled(Logo)` height: 100px; width: 100px; `; const MainLogoDiv = styled.div` padding-top: 20px; `; const DetailsDiv = styled.div` align-items: flex-start; line-height: 1.3; padding: 20px 0; text-align: center; width: 650px; `; const SearchContainerDiv = styled.div` padding: 20px 0 0 0; width: 600px; `; const AppContainerDiv = styled.div` align-items: stretch; flex-flow: row nowrap; height: 100%; display: flex; justify-content: flex-start; `; const MainContentDiv = styled.div` flex: 1 1 calc(100vh - 60px); overflow: hidden; font: 300 14px HelveticaNeue-Reg, Helvetica, Arial, sans-serif; `; const StyledAnchor = styled.a` color: #3570f4; text-decoration: none; cursor: pointer; `; export default class PageHome extends React.Component { static async getInitialProps({ req }) { let api = API(req); let reload = false; let error = null; const domains = await Promise.all([ api.listUserDomains(), api.getHeaderDetails(), api.getPendingDomainMembersList(), ]).catch((err) => { let response = RequestUtils.errorCheckHelper(err); reload = response.reload; error = response.error; return [{}, {}, {}]; }); return { api, reload, error, domains: domains[0], headerDetails: domains[1], pending: domains[2], nonce: req.headers.rid, }; } constructor(props) { super(props); this.api = props.api || API(); this.cache = createCache({ key: 'athenz', nonce: this.props.nonce, }); } render() { if (this.props.reload) { window.location.reload(); return <div />; } if (this.props.error) { return <Error err={this.props.error} />; } return ( <CacheProvider value={this.cache}> <div data-testid='home'> <Head> <title>Athenz</title> </Head> <Header showSearch={false} headerDetails={this.props.headerDetails} pending={this.props.pending} /> <MainContentDiv> <AppContainerDiv> <HomeContainerDiv> <HomeContentDiv> <MainLogoDiv> <LogoStyled /> </MainLogoDiv> <DetailsDiv> <span> Athenz is an open source platform which provides secure identity in the form of X.509 certificate to every workload for service authentication (mutual TLS authentication) and provides fine-grained Role Based Access Control (RBAC) for authorization. </span> <StyledAnchor rel='noopener' target='_blank' href='https://git.ouroath.com/pages/athens/athenz-guide/' > Learn more </StyledAnchor> </DetailsDiv> <SearchContainerDiv> <Search /> </SearchContainerDiv> </HomeContentDiv> </HomeContainerDiv> <UserDomains domains={this.props.domains} api={this.api} /> </AppContainerDiv> </MainContentDiv> </div> </CacheProvider> ); } }
yahoo/athenz
ui/src/pages/home.js
JavaScript
apache-2.0
5,975
package com.churches.by.ui; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import com.churches.by.R; public class AboutDialog extends DialogFragment { public AboutDialog() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); return inflater.inflate(R.layout.about_dialog, container, false); } }
vmatelsky/churches
Churches/com.churches.by/src/main/java/com/churches/by/ui/AboutDialog.java
Java
apache-2.0
684
/* * Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved. */ package com.arjuna.databroker.control.comms; import java.io.Serializable; import java.util.Map; public class PropertiesDTO implements Serializable { private static final long serialVersionUID = -4823706453142980142L; public PropertiesDTO() { } public PropertiesDTO(Map<String, String> properties) { _properties = properties; } public Map<String, String> getProperties() { return _properties; } public void setProperties(Map<String, String> properties) { _properties = properties; } private Map<String, String> _properties; }
mtaylor/DataBroker
control-common/src/main/java/com/arjuna/databroker/control/comms/PropertiesDTO.java
Java
apache-2.0
727
/* * Copyright 2017 Crown Copyright * * 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 stroom.security.impl; import stroom.security.shared.SessionListResponse; public interface SessionListService { /** * List all sessions on the specified node */ SessionListResponse listSessions(final String nodeName); /** * List all sessions on all nodes */ SessionListResponse listSessions(); }
gchq/stroom
stroom-security/stroom-security-impl/src/main/java/stroom/security/impl/SessionListService.java
Java
apache-2.0
946
package org.lnu.is.converter.person.paper; import org.lnu.is.annotations.Converter; import org.lnu.is.converter.AbstractConverter; import org.lnu.is.domain.honors.type.HonorType; import org.lnu.is.domain.paper.type.PaperType; import org.lnu.is.domain.person.Person; import org.lnu.is.domain.person.paper.PersonPaper; import org.lnu.is.resource.person.paper.PersonPaperResource; /** * Person Paper Resource Converter. * @author ivanursul * */ @Converter("personPaperResourceConverter") public class PersonPaperResourceConverter extends AbstractConverter<PersonPaperResource, PersonPaper> { @Override public PersonPaper convert(final PersonPaperResource source, final PersonPaper target) { if (source.getPersonId() != null) { Person person = new Person(); person.setId(source.getPersonId()); target.setPerson(person); } if (source.getPaperTypeId() != null) { PaperType paperType = new PaperType(); paperType.setId(source.getPaperTypeId()); target.setPaperType(paperType); } if (source.getHonorsTypeId() != null) { HonorType honorsType = new HonorType(); honorsType.setId(source.getHonorsTypeId()); target.setHonorsType(honorsType); } target.setDocSeries(source.getDocSeries()); target.setDocNum(source.getDocNum()); target.setDocDate(source.getDocDate()); target.setDocIssued(source.getDocIssued()); target.setDocPin(source.getDocPin()); target.setMark(source.getMark()); target.setIsChecked(source.getIsChecked()); target.setIsForeign(source.getIsForeign()); return target; } @Override public PersonPaper convert(final PersonPaperResource source) { return convert(source, new PersonPaper()); } }
ifnul/ums-backend
is-lnu-converter/src/main/java/org/lnu/is/converter/person/paper/PersonPaperResourceConverter.java
Java
apache-2.0
1,692
package voldemort.server.protocol.vold; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.common.VoldemortOpCode; import voldemort.common.nio.ByteBufferBackedInputStream; import voldemort.common.nio.ByteBufferContainer; import voldemort.server.RequestRoutingType; import voldemort.server.StoreRepository; import voldemort.server.protocol.AbstractRequestHandler; import voldemort.server.protocol.RequestHandler; import voldemort.server.protocol.StreamRequestHandler; import voldemort.store.ErrorCodeMapper; import voldemort.store.Store; import voldemort.utils.ByteArray; import voldemort.versioning.ObsoleteVersionException; /** * Server-side request handler for voldemort native client protocol * * */ public class VoldemortNativeRequestHandler extends AbstractRequestHandler implements RequestHandler { private static final Logger logger = Logger.getLogger(VoldemortNativeRequestHandler.class); private final int protocolVersion; public VoldemortNativeRequestHandler(ErrorCodeMapper errorMapper, StoreRepository repository, int protocolVersion) { super(errorMapper, repository); if(protocolVersion < 0 || protocolVersion > 3) throw new IllegalArgumentException("Unknown protocol version: " + protocolVersion); this.protocolVersion = protocolVersion; } private ClientRequestHandler getClientRequestHanlder(byte opCode, Store<ByteArray, byte[], byte[]> store) throws IOException { switch(opCode) { case VoldemortOpCode.GET_OP_CODE: return new GetRequestHandler(store, protocolVersion); case VoldemortOpCode.GET_ALL_OP_CODE: return new GetAllRequestHandler(store, protocolVersion); case VoldemortOpCode.PUT_OP_CODE: return new PutRequestHandler(store, protocolVersion); case VoldemortOpCode.DELETE_OP_CODE: return new DeleteRequestHandler(store, protocolVersion); case VoldemortOpCode.GET_VERSION_OP_CODE: return new GetVersionRequestHandler(store, protocolVersion); default: throw new IOException("Unknown op code: " + opCode); } } @Override public StreamRequestHandler handleRequest(final DataInputStream inputStream, final DataOutputStream outputStream) throws IOException { return handleRequest(inputStream, outputStream, null); } private void clearBuffer(ByteBufferContainer outputContainer) { if(outputContainer != null) { outputContainer.getBuffer().clear(); } } @Override public StreamRequestHandler handleRequest(final DataInputStream inputStream, final DataOutputStream outputStream, final ByteBufferContainer outputContainer) throws IOException { long startTimeMs = -1; long startTimeNs = -1; if(logger.isDebugEnabled()) { startTimeMs = System.currentTimeMillis(); startTimeNs = System.nanoTime(); } byte opCode = inputStream.readByte(); String storeName = inputStream.readUTF(); RequestRoutingType routingType = getRoutingType(inputStream); Store<ByteArray, byte[], byte[]> store = getStore(storeName, routingType); if(store == null) { clearBuffer(outputContainer); writeException(outputStream, new VoldemortException("No store named '" + storeName + "'.")); return null; } ClientRequestHandler requestHandler = getClientRequestHanlder(opCode, store); try { requestHandler.parseRequest(inputStream); requestHandler.processRequest(); } catch ( VoldemortException e) { // Put generates lot of ObsoleteVersionExceptions, suppress them // they are harmless and indicates normal mode of operation. if(!(e instanceof ObsoleteVersionException)) { logger.error("Store" + storeName + ". Error: " + e.getMessage()); } clearBuffer(outputContainer); writeException(outputStream, e); return null; } // We are done with Input, clear the buffers clearBuffer(outputContainer); int size = requestHandler.getResponseSize(); if(outputContainer != null) { outputContainer.growBuffer(size); } requestHandler.writeResponse(outputStream); outputStream.flush(); if(logger.isDebugEnabled()) { String debugPrefix = "OpCode " + opCode + " started at: " + startTimeMs + " handlerRef: " + System.identityHashCode(inputStream) + " Elapsed : " + (System.nanoTime() - startTimeNs) + " ns, "; logger.debug(debugPrefix + requestHandler.getDebugMessage() ); } return null; } private RequestRoutingType getRoutingType(DataInputStream inputStream) throws IOException { RequestRoutingType routingType = RequestRoutingType.NORMAL; if(protocolVersion > 0) { boolean isRouted = inputStream.readBoolean(); routingType = RequestRoutingType.getRequestRoutingType(isRouted, false); } if(protocolVersion > 1) { int routingTypeCode = inputStream.readByte(); routingType = RequestRoutingType.getRequestRoutingType(routingTypeCode); } return routingType; } /** * This is pretty ugly. We end up mimicking the request logic here, so this * needs to stay in sync with handleRequest. */ @Override public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException { DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer)); try { byte opCode = inputStream.readByte(); // Store Name inputStream.readUTF(); // Store routing type getRoutingType(inputStream); switch(opCode) { case VoldemortOpCode.GET_VERSION_OP_CODE: if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer)) return false; break; case VoldemortOpCode.GET_OP_CODE: if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; case VoldemortOpCode.GET_ALL_OP_CODE: if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; case VoldemortOpCode.PUT_OP_CODE: { if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; } case VoldemortOpCode.DELETE_OP_CODE: { if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer)) return false; break; } default: throw new VoldemortException(" Unrecognized Voldemort OpCode " + opCode); } // This should not happen, if we reach here and if buffer has more // data, there is something wrong. if(buffer.hasRemaining()) { logger.info(" Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode " + opCode + " remaining bytes " + buffer.remaining()); } return true; } catch(IOException e) { // This could also occur if the various methods we call into // re-throw a corrupted value error as some other type of exception. // For example, updating the position on a buffer past its limit // throws an InvalidArgumentException. if(logger.isDebugEnabled()) logger.debug("Probable partial read occurred causing exception", e); return false; } } private void writeException(DataOutputStream stream, VoldemortException e) throws IOException { short code = getErrorMapper().getCode(e); stream.writeShort(code); stream.writeUTF(e.getMessage()); stream.flush(); } }
cshaxu/voldemort
src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java
Java
apache-2.0
8,979
package com.jasonsoft.softwarevideoplayer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory.Options; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore.Video; import android.provider.MediaStore.Video.Thumbnails; import android.view.View; import android.widget.ImageView; import com.jasonsoft.softwarevideoplayer.cache.CacheManager; import com.jasonsoft.softwarevideoplayer.data.AsyncDrawable; import com.jasonsoft.softwarevideoplayer.data.LoadThumbnailParams; import com.jasonsoft.softwarevideoplayer.data.LoadThumbnailResult; import java.lang.ref.WeakReference; public class LoadThumbnailTask extends AsyncTask<LoadThumbnailParams, Void, LoadThumbnailResult> { private Context mContext; private final WeakReference<ImageView> thumbnailViewReference; private long data = 0; public LoadThumbnailTask(Context context, ImageView thumbnailView) { this.mContext = context; this.thumbnailViewReference = new WeakReference<ImageView>(thumbnailView); } @Override protected LoadThumbnailResult doInBackground(LoadThumbnailParams... params) { data = params[0].origId; Bitmap bitmap = Thumbnails.getThumbnail(mContext.getContentResolver(), data, Thumbnails.MINI_KIND, new Options()); android.util.Log.d("jason", "doInBackground data:" + data); android.util.Log.d("jason", "doInBackground bitmap:" + bitmap); if (data > 0 && bitmap != null) { CacheManager.getInstance().addThumbnailToMemoryCache(String.valueOf(data), bitmap); } if (this.isCancelled()) { return null; } return new LoadThumbnailResult(bitmap); } @Override protected void onPostExecute(LoadThumbnailResult result) { if (isCancelled() || null == result) { return; } final ImageView thumbnailView = thumbnailViewReference.get(); final LoadThumbnailTask loadThumbnailTask = getLoadThumbnailTask(thumbnailView); if (this == loadThumbnailTask && thumbnailView != null) { setThumbnail(result.bitmap, thumbnailView); } } public long getData() { return data; } /** * @param imageView Any imageView * @return Retrieve the currently active work task (if any) associated with this imageView. * null if there is no such task. */ public static LoadThumbnailTask getLoadThumbnailTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getLoadThumbnailTask(); } } return null; } void setThumbnail(Bitmap bitmap, ImageView thumbnailView) { thumbnailView.setImageBitmap(bitmap); thumbnailView.setVisibility(View.VISIBLE); } }
jasonchuang/SoftwareVideoPlayer
src/com/jasonsoft/softwarevideoplayer/LoadThumbnailTask.java
Java
apache-2.0
3,200
package org.opendaylight.opflex.genie.content.format.meta.mdl; import java.util.TreeMap; import org.opendaylight.opflex.genie.content.model.mclass.MClass; import org.opendaylight.opflex.genie.content.model.mprop.MProp; import org.opendaylight.opflex.genie.engine.file.WriteStats; import org.opendaylight.opflex.genie.engine.format.*; import org.opendaylight.opflex.genie.engine.model.Ident; /** * Created by midvorki on 8/4/14. */ public class FContDef extends GenericFormatterTask { public FContDef( FormatterCtx aInFormatterCtx, FileNameRule aInFileNameRule, Indenter aInIndenter, BlockFormatDirective aInHeaderFormatDirective, BlockFormatDirective aInCommentFormatDirective, boolean aInIsUserFile, WriteStats aInStats) { super(aInFormatterCtx, aInFileNameRule, aInIndenter, aInHeaderFormatDirective, aInCommentFormatDirective, aInIsUserFile, aInStats); } public void generate() { out.println(); MClass lRoot = MClass.getContainmentRoot(); genClass(0, lRoot); } private void genClass(int aInIndent, MClass aInClass) { out.print(aInIndent, aInClass.getFullConcatenatedName()); genProps(aInIndent + 1, aInClass); genContained(aInIndent, aInClass); } private void genProps(int aInIndent, MClass aInClass) { TreeMap<String,MProp> lProps = new TreeMap<String, MProp>(); aInClass.findProp(lProps, false); if (!lProps.isEmpty()) { out.print('['); for (MProp lProp : lProps.values()) { genProp(aInIndent,lProp); } out.println(']'); } else { out.println(); } } private void genProp(int aInIndent, MProp aInProp) { out.println(); out.print(aInIndent, aInProp.getLID().getName() + "=<" + aInProp.getType(false).getFullConcatenatedName() + "/" + aInProp.getType(true).getFullConcatenatedName() + "|group:" + aInProp.getGroup() + ">;"); } private void genContained(int aInIndent, MClass aInParent) { TreeMap<Ident,MClass> lContained = new TreeMap<Ident,MClass>(); aInParent.getContainsClasses(lContained, true, true); if (!lContained.isEmpty()) { out.println(aInIndent, '{'); for (MClass lClass : lContained.values()) { genClass(aInIndent+1, lClass); } out.println(aInIndent, '}'); } } }
noironetworks/genie
src/main/java/org/opendaylight/opflex/genie/content/format/meta/mdl/FContDef.java
Java
apache-2.0
2,728
package com.transmem.doc; import java.io.IOException; import java.io.File; import java.io.PrintWriter; import java.io.FileReader; import java.io.BufferedReader; import java.util.ArrayList; import java.util.logging.Logger; import java.sql.SQLException; /** * Bitext loader loads a bilingual parallel text from two separate files. * The files should be in plain text format with proper punctuation marks * for each sentence. In other words, a sentence in the source language * text should have a corresponding sentence in the translation text. * The current implementation does not include automatic alignment, it is * the user's responsibility to guarantee that the sentences are aligned. * This class implements ITextSaver for TextParser to parse the text into * sentences. */ public class BitextLoader implements ITextSaver { public static final Logger log_ = Logger.getLogger(BitextLoader.class.getName()); class Record { public int index_; public int length_; public Record link_; //link to the other language sentence public Record(int index, int length) { this.index_ = index; this.length_ = length; this.link_ = null; } } private IUnitSaver saver_ = null; private String sencoding_, tencoding_; private File[] tempfiles_; //temporary filenames private PrintWriter[] tempwriters_; private ArrayList<Record>[] slens_; //length of sentences private int curfile_, index_; /** * Construct BitextLoader with two file names. */ public BitextLoader(String sfilename, String tfilename, String sencoding, String tencoding, IUnitSaver saver) throws IOException,SQLException { this.saver_ = saver; this.sencoding_ = sencoding; this.tencoding_ = tencoding; parseFiles(sfilename, tfilename); } /** * Parse the two files to get sentences. * @param sfilename - source text filename * @param tfilename - target text filename */ protected void parseFiles(String sfilename, String tfilename) throws IOException,SQLException { this.slens_ = new ArrayList[2];//{new ArrayList<Record>(),new ArrayList<Record>()}; this.slens_[0] = new ArrayList<Record>(); this.slens_[1] = new ArrayList<Record>(); //parse two files one by one, saving sentences into temporary text files this.tempfiles_ = new File[2]; this.tempfiles_[0] = File.createTempFile("tmbis",".tmp"); log_.info("Temporary file created 4 src: "+tempfiles_[0]); this.tempwriters_[0] = new PrintWriter(this.tempfiles_[0]); this.curfile_ = 0; this.index_ = 0; TextParser tps = new TextParser(); tps.parse(sfilename, this.sencoding_, this); this.tempwriters_[0].close(); this.tempfiles_[1] = File.createTempFile("tmbid",".tmp"); log_.info("Temporary file created 4 dst: "+tempfiles_[1]); this.tempwriters_[1] = new PrintWriter(this.tempfiles_[1]); this.curfile_ = 1; this.index_ = 0; TextParser tpd = new TextParser(); tpd.parse(tfilename, this.tencoding_, this); this.tempwriters_[1].close(); //merge and align the sentences boolean saved = false; if ((this.slens_[0].size() > 0) && (this.slens_[0].size() == this.slens_[1].size())) { mergeAndAlign(); saved = true; } //finally delete the temp files this.tempfiles_[0].delete(); this.tempfiles_[1].delete(); log_.info("Temporary files deleted"); File f = new File(sfilename); f.delete(); f = new File(tfilename); f.delete(); log_.info("Uploaded files deleted"); if (!saved) throw new IOException("Sentences do not match"); } /** * Align the sentences from the two files and merge if necessary. * A true aligner is an AI research topic, so we ignore that at the moment, * and leave the un-matched sentences empty. The user is then responsible * to edit the sentences and align manually. */ public void mergeAndAlign() throws SQLException,IOException { BufferedReader reader1 = new BufferedReader(new FileReader(this.tempfiles_[0])); BufferedReader reader2 = new BufferedReader(new FileReader(this.tempfiles_[1])); while (true) { String s1 = reader1.readLine(); String s2 = reader2.readLine(); if (s1 == null && s2 == null) break; this.saver_.saveUnit(s1, s2); } reader1.close(); reader2.close(); } // Interface method, not used here public void startParagraph(int startpos) throws java.sql.SQLException { } // Interface method, not used here public void endParagraph(int endpos) throws java.sql.SQLException { } /** * Called by a TextParser object when a sentence is ready to save. * @param sentence - String as a sentence * @param startpos - ignored * @param endpos - ignored */ public void saveSentence(String sentence, int startpos, int endpos) throws java.sql.SQLException { this.tempwriters_[this.curfile_].println(sentence); this.slens_[this.curfile_].add(new Record(this.index_, sentence.length())); this.index_ ++; } }
tedwen/transmem
src/com/transmem/doc/BitextLoader.java
Java
apache-2.0
4,846
package com.indeed.proctor.common; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.indeed.util.core.DataLoadingTimerTask; import com.indeed.util.varexport.Export; import com.indeed.proctor.common.model.Audit; import com.indeed.proctor.common.model.TestMatrixArtifact; import org.apache.log4j.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.el.FunctionMapper; import java.io.IOException; import java.util.Map; public abstract class AbstractProctorLoader extends DataLoadingTimerTask implements Supplier<Proctor> { private static final Logger LOGGER = Logger.getLogger(AbstractProctorLoader.class); @Nonnull protected final Map<String, TestSpecification> requiredTests; @Nullable private Proctor current = null; @Nullable private Audit lastAudit = null; @Nullable private String lastLoadErrorMessage= "load never attempted"; @Nonnull private final FunctionMapper functionMapper; public AbstractProctorLoader(@Nonnull final Class<?> cls, @Nonnull final ProctorSpecification specification, @Nonnull final FunctionMapper functionMapper) { super(cls.getSimpleName()); this.requiredTests = specification.getTests(); this.functionMapper = functionMapper; } @Nullable abstract TestMatrixArtifact loadTestMatrix() throws IOException, MissingTestMatrixException; @Nonnull abstract String getSource(); @Override public boolean load() { final Proctor newProctor; try { newProctor = doLoad(); } catch (@Nonnull final Throwable t) { lastLoadErrorMessage = t.getMessage(); throw new RuntimeException("Unable to reload proctor from " + getSource(), t); } lastLoadErrorMessage = null; if (newProctor == null) { // This should only happen if the versions of the matrix files are the same. return false; } this.current = newProctor; final Audit lastAudit = Preconditions.checkNotNull(this.lastAudit, "Missing last audit"); setDataVersion(lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy()); LOGGER.info("Successfully loaded new test matrix definition: " + lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy()); return true; } @Nullable public Proctor doLoad() throws IOException, MissingTestMatrixException { final TestMatrixArtifact testMatrix = loadTestMatrix(); if (testMatrix == null) { throw new MissingTestMatrixException("Failed to load Test Matrix from " + getSource()); } final ProctorLoadResult loadResult = ProctorUtils.verifyAndConsolidate(testMatrix, getSource(), requiredTests, functionMapper); final Audit newAudit = testMatrix.getAudit(); if (lastAudit != null) { final Audit audit = Preconditions.checkNotNull(newAudit, "Missing audit"); if(lastAudit.getVersion() == audit.getVersion()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Not reloading " + getSource() + " test matrix definition because audit is unchanged: " + lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy()); } return null; } } final Proctor proctor = Proctor.construct(testMatrix, loadResult, functionMapper); // kind of lame to modify lastAudit here but current in load(), but the interface is a little constraining this.lastAudit = newAudit; return proctor; } @Nullable public Proctor get() { return current; } @Nullable @Export(name = "last-audit") public Audit getLastAudit() { return lastAudit; } @Nullable @Export(name = "last-error", doc = "The last error message thrown by the loader. null indicates a successful load.") public String getLastLoadErrorMessage() { return lastLoadErrorMessage; } // this is used for healthchecks @SuppressWarnings({"UnusedDeclaration"}) public boolean isLoadedDataSuccessfullyRecently() { return dataLoadTimer.isLoadedDataSuccessfullyRecently(); } }
jdcheng/proctor-git
proctor-common/src/main/java/com/indeed/proctor/common/AbstractProctorLoader.java
Java
apache-2.0
4,349
package com.dev9.crash.bad; import com.dev9.crash.AbstractBadThing; import org.springframework.stereotype.Service; @Service public class FillHeapLocalMethodOnStack extends AbstractBadThing { public String getBadThingDescription() { return "Fills up the heap using an object with a local method. This method allocates an object on the stack which grows until OOM."; } public String getBadThingName() { return "Fill Up The Heap On The Stack"; } @Override public String getBadThingId() { return "fill-up-the-heap-object-local-method-stack-oom"; } public String doBadThing() throws Exception { MemoryMasher mm = new MemoryMasher(); mm.stackHeapMasher(); return null; } }
dev9com/crash-dummy
src/main/java/com/dev9/crash/bad/FillHeapLocalMethodOnStack.java
Java
apache-2.0
757
/* * Copyright 2004-2013 the Seasar Foundation and the Others. * * 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.docksidestage.mysql.dbflute.allcommon; import java.util.*; import org.dbflute.exception.ClassificationNotFoundException; import org.dbflute.jdbc.Classification; import org.dbflute.jdbc.ClassificationCodeType; import org.dbflute.jdbc.ClassificationMeta; import org.dbflute.jdbc.ClassificationUndefinedHandlingType; import org.dbflute.optional.OptionalThing; import static org.dbflute.util.DfTypeUtil.emptyStrings; /** * The definition of classification. * @author DBFlute(AutoGenerator) */ public interface CDef extends Classification { /** * 会員が受けられるサービスのランクを示す */ public enum ServiceRank implements CDef { /** PLATINUM: platinum rank */ Platinum("PLT", "PLATINUM", emptyStrings()) , /** GOLD: gold rank */ Gold("GLD", "GOLD", emptyStrings()) , /** SILVER: silver rank */ Silver("SIL", "SILVER", emptyStrings()) , /** BRONZE: bronze rank */ Bronze("BRZ", "BRONZE", emptyStrings()) , /** PLASTIC: plastic rank (deprecated: テーブル区分値の非推奨要素指定のテストのため) */ @Deprecated Plastic("PLS", "PLASTIC", emptyStrings()) ; private static final Map<String, ServiceRank> _codeClsMap = new HashMap<String, ServiceRank>(); private static final Map<String, ServiceRank> _nameClsMap = new HashMap<String, ServiceRank>(); static { for (ServiceRank value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private ServiceRank(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.ServiceRank; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<ServiceRank> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof ServiceRank) { return OptionalThing.of((ServiceRank)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<ServiceRank> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static ServiceRank codeOf(Object code) { if (code == null) { return null; } if (code instanceof ServiceRank) { return (ServiceRank)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static ServiceRank nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<ServiceRank> listAll() { return new ArrayList<ServiceRank>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<ServiceRank> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: ServiceRank." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<ServiceRank> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<ServiceRank> clsList = new ArrayList<ServiceRank>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<ServiceRank> groupOf(String groupName) { return new ArrayList<ServiceRank>(4); } @Override public String toString() { return code(); } } /** * mainly region of member address */ public enum Region implements CDef { /** アメリカ */ アメリカ("1", "アメリカ", emptyStrings()) , /** カナダ */ カナダ("2", "カナダ", emptyStrings()) , /** 中国 */ 中国("3", "中国", emptyStrings()) , /** 千葉 */ 千葉("4", "千葉", emptyStrings()) ; private static final Map<String, Region> _codeClsMap = new HashMap<String, Region>(); private static final Map<String, Region> _nameClsMap = new HashMap<String, Region>(); static { for (Region value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private Region(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.Region; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<Region> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof Region) { return OptionalThing.of((Region)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<Region> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static Region codeOf(Object code) { if (code == null) { return null; } if (code instanceof Region) { return (Region)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static Region nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<Region> listAll() { return new ArrayList<Region>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<Region> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: Region." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<Region> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<Region> clsList = new ArrayList<Region>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<Region> groupOf(String groupName) { return new ArrayList<Region>(4); } @Override public String toString() { return code(); } } /** * reason for member withdrawal */ public enum WithdrawalReason implements CDef { /** SIT: サイトが使いにくいから */ Sit("SIT", "SIT", emptyStrings()) , /** PRD: 商品に魅力がないから */ Prd("PRD", "PRD", emptyStrings()) , /** FRT: フリテンだから */ Frt("FRT", "FRT", emptyStrings()) , /** OTH: その他理由 */ Oth("OTH", "OTH", emptyStrings()) ; private static final Map<String, WithdrawalReason> _codeClsMap = new HashMap<String, WithdrawalReason>(); private static final Map<String, WithdrawalReason> _nameClsMap = new HashMap<String, WithdrawalReason>(); static { for (WithdrawalReason value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private WithdrawalReason(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.WithdrawalReason; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<WithdrawalReason> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof WithdrawalReason) { return OptionalThing.of((WithdrawalReason)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<WithdrawalReason> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static WithdrawalReason codeOf(Object code) { if (code == null) { return null; } if (code instanceof WithdrawalReason) { return (WithdrawalReason)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static WithdrawalReason nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<WithdrawalReason> listAll() { return new ArrayList<WithdrawalReason>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<WithdrawalReason> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: WithdrawalReason." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<WithdrawalReason> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<WithdrawalReason> clsList = new ArrayList<WithdrawalReason>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<WithdrawalReason> groupOf(String groupName) { return new ArrayList<WithdrawalReason>(4); } @Override public String toString() { return code(); } } /** * 支払方法 */ public enum PaymentMethod implements CDef { /** 手渡し: Face-to-Faceの手渡しで商品と交換 */ ByHand("HAN", "手渡し", emptyStrings()) , /** 銀行振込: 銀行振込で確認してから商品発送 */ BankTransfer("BAK", "銀行振込", emptyStrings()) , /** クレジットカード: クレジットカードの番号を教えてもらう */ CreditCard("CRC", "クレジットカード", emptyStrings()) ; private static final Map<String, PaymentMethod> _codeClsMap = new HashMap<String, PaymentMethod>(); private static final Map<String, PaymentMethod> _nameClsMap = new HashMap<String, PaymentMethod>(); static { for (PaymentMethod value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private PaymentMethod(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.PaymentMethod; } /** * Is the classification in the group? <br> * 最も推奨されている方法 <br> * The group elements:[ByHand] * @return The determination, true or false. */ public boolean isRecommended() { return ByHand.equals(this); } public boolean inGroup(String groupName) { if ("recommended".equals(groupName)) { return isRecommended(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<PaymentMethod> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof PaymentMethod) { return OptionalThing.of((PaymentMethod)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<PaymentMethod> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static PaymentMethod codeOf(Object code) { if (code == null) { return null; } if (code instanceof PaymentMethod) { return (PaymentMethod)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static PaymentMethod nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<PaymentMethod> listAll() { return new ArrayList<PaymentMethod>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<PaymentMethod> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("recommended".equalsIgnoreCase(groupName)) { return listOfRecommended(); } throw new ClassificationNotFoundException("Unknown classification group: PaymentMethod." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<PaymentMethod> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<PaymentMethod> clsList = new ArrayList<PaymentMethod>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * 最も推奨されている方法 <br> * The group elements:[ByHand] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<PaymentMethod> listOfRecommended() { return new ArrayList<PaymentMethod>(Arrays.asList(ByHand)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<PaymentMethod> groupOf(String groupName) { if ("recommended".equals(groupName)) { return listOfRecommended(); } return new ArrayList<PaymentMethod>(4); } @Override public String toString() { return code(); } } /** * the test of reference variable in grouping map */ public enum GroupingReference implements CDef { /** LAND_NAME */ LAND_NAME("LND", "LAND_NAME", emptyStrings()) , /** SEA_NAME */ SEA_NAME("SEA", "SEA_NAME", emptyStrings()) , /** IKSPIARY_NAME */ IKSPIARY_NAME("IKS", "IKSPIARY_NAME", emptyStrings()) , /** AMPHI_NAME */ AMPHI_NAME("AMP", "AMPHI_NAME", emptyStrings()) ; private static final Map<String, GroupingReference> _codeClsMap = new HashMap<String, GroupingReference>(); private static final Map<String, GroupingReference> _nameClsMap = new HashMap<String, GroupingReference>(); static { for (GroupingReference value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private GroupingReference(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.GroupingReference; } /** * Is the classification in the group? <br> * サービスが利用できる会員 <br> * The group elements:[LAND_NAME, SEA_NAME] * @return The determination, true or false. */ public boolean isServiceAvailable() { return LAND_NAME.equals(this) || SEA_NAME.equals(this); } /** * Is the classification in the group? <br> * The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The determination, true or false. */ public boolean isServicePlus() { return LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this); } /** * Is the classification in the group? <br> * The group elements:[AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The determination, true or false. */ public boolean isNestedPlus() { return AMPHI_NAME.equals(this) || LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this); } /** * Is the classification in the group? <br> * The group elements:[IKSPIARY_NAME] * @return The determination, true or false. */ public boolean isOneDef() { return IKSPIARY_NAME.equals(this); } /** * Is the classification in the group? <br> * The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The determination, true or false. */ public boolean isDupRef() { return LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this); } public boolean inGroup(String groupName) { if ("serviceAvailable".equals(groupName)) { return isServiceAvailable(); } if ("servicePlus".equals(groupName)) { return isServicePlus(); } if ("nestedPlus".equals(groupName)) { return isNestedPlus(); } if ("oneDef".equals(groupName)) { return isOneDef(); } if ("dupRef".equals(groupName)) { return isDupRef(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<GroupingReference> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof GroupingReference) { return OptionalThing.of((GroupingReference)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<GroupingReference> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static GroupingReference codeOf(Object code) { if (code == null) { return null; } if (code instanceof GroupingReference) { return (GroupingReference)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static GroupingReference nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<GroupingReference> listAll() { return new ArrayList<GroupingReference>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<GroupingReference> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("serviceAvailable".equalsIgnoreCase(groupName)) { return listOfServiceAvailable(); } if ("servicePlus".equalsIgnoreCase(groupName)) { return listOfServicePlus(); } if ("nestedPlus".equalsIgnoreCase(groupName)) { return listOfNestedPlus(); } if ("oneDef".equalsIgnoreCase(groupName)) { return listOfOneDef(); } if ("dupRef".equalsIgnoreCase(groupName)) { return listOfDupRef(); } throw new ClassificationNotFoundException("Unknown classification group: GroupingReference." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<GroupingReference> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<GroupingReference> clsList = new ArrayList<GroupingReference>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * サービスが利用できる会員 <br> * The group elements:[LAND_NAME, SEA_NAME] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<GroupingReference> listOfServiceAvailable() { return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME)); } /** * Get the list of group classification elements. (returns new copied list) <br> * The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<GroupingReference> listOfServicePlus() { return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME, IKSPIARY_NAME)); } /** * Get the list of group classification elements. (returns new copied list) <br> * The group elements:[AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<GroupingReference> listOfNestedPlus() { return new ArrayList<GroupingReference>(Arrays.asList(AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME)); } /** * Get the list of group classification elements. (returns new copied list) <br> * The group elements:[IKSPIARY_NAME] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<GroupingReference> listOfOneDef() { return new ArrayList<GroupingReference>(Arrays.asList(IKSPIARY_NAME)); } /** * Get the list of group classification elements. (returns new copied list) <br> * The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<GroupingReference> listOfDupRef() { return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME, IKSPIARY_NAME)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<GroupingReference> groupOf(String groupName) { if ("serviceAvailable".equals(groupName)) { return listOfServiceAvailable(); } if ("servicePlus".equals(groupName)) { return listOfServicePlus(); } if ("nestedPlus".equals(groupName)) { return listOfNestedPlus(); } if ("oneDef".equals(groupName)) { return listOfOneDef(); } if ("dupRef".equals(groupName)) { return listOfDupRef(); } return new ArrayList<GroupingReference>(4); } @Override public String toString() { return code(); } } /** * The test of relation reference */ public enum SelfReference implements CDef { /** foo801 */ Foo801("801", "foo801", emptyStrings()) , /** foo811 */ Foo811("811", "foo811", emptyStrings()) , /** bar802: 0 */ Bar802("802", "bar802", emptyStrings()) , /** baz803: 0 */ Baz803("803", "baz803", emptyStrings()) , /** bar812: 0 */ Bar812("812", "bar812", emptyStrings()) , /** baz813: 0 */ Baz813("813", "baz813", emptyStrings()) ; private static final Map<String, SelfReference> _codeClsMap = new HashMap<String, SelfReference>(); private static final Map<String, SelfReference> _nameClsMap = new HashMap<String, SelfReference>(); static { for (SelfReference value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private SelfReference(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.SelfReference; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SelfReference> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof SelfReference) { return OptionalThing.of((SelfReference)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SelfReference> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static SelfReference codeOf(Object code) { if (code == null) { return null; } if (code instanceof SelfReference) { return (SelfReference)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static SelfReference nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<SelfReference> listAll() { return new ArrayList<SelfReference>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<SelfReference> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: SelfReference." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<SelfReference> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<SelfReference> clsList = new ArrayList<SelfReference>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<SelfReference> groupOf(String groupName) { return new ArrayList<SelfReference>(4); } @Override public String toString() { return code(); } } /** * The test of top only */ public enum TopCommentOnly implements CDef { ; private static final Map<String, TopCommentOnly> _codeClsMap = new HashMap<String, TopCommentOnly>(); private static final Map<String, TopCommentOnly> _nameClsMap = new HashMap<String, TopCommentOnly>(); static { for (TopCommentOnly value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private TopCommentOnly(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.TopCommentOnly; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<TopCommentOnly> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof TopCommentOnly) { return OptionalThing.of((TopCommentOnly)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<TopCommentOnly> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static TopCommentOnly codeOf(Object code) { if (code == null) { return null; } if (code instanceof TopCommentOnly) { return (TopCommentOnly)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static TopCommentOnly nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<TopCommentOnly> listAll() { return new ArrayList<TopCommentOnly>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<TopCommentOnly> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: TopCommentOnly." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<TopCommentOnly> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<TopCommentOnly> clsList = new ArrayList<TopCommentOnly>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<TopCommentOnly> groupOf(String groupName) { return new ArrayList<TopCommentOnly>(4); } @Override public String toString() { return code(); } } /** * the test of sub-item map for implicit classification */ public enum SubItemImplicit implements CDef { /** Aaa: means foo */ Foo("FOO", "Aaa", emptyStrings()) , /** Bbb: means bar */ Bar("BAR", "Bbb", emptyStrings()) ; private static final Map<String, SubItemImplicit> _codeClsMap = new HashMap<String, SubItemImplicit>(); private static final Map<String, SubItemImplicit> _nameClsMap = new HashMap<String, SubItemImplicit>(); static { for (SubItemImplicit value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private static final Map<String, Map<String, Object>> _subItemMapMap = new HashMap<String, Map<String, Object>>(); static { { Map<String, Object> subItemMap = new HashMap<String, Object>(); subItemMap.put("regularStringItem", "value1<tag>"); subItemMap.put("regularNumberItem", "123"); subItemMap.put("regularVariousItem", "list:{\n ; reg\n ; var\n ; ite\n}"); subItemMap.put("listItem", "list:{\n ; aa\n ; bb\n ; cc\n}"); _subItemMapMap.put(Foo.code(), Collections.unmodifiableMap(subItemMap)); } { Map<String, Object> subItemMap = new HashMap<String, Object>(); subItemMap.put("regularStringItem", "value2<teg>"); subItemMap.put("regularNumberItem", "456"); subItemMap.put("regularVariousItem", "map:{\n ; reg = var\n ; ous = ite\n}"); subItemMap.put("mapItem", "map:{\n ; key11 = value11\n}"); subItemMap.put("containsLine", "va\nlue"); _subItemMapMap.put(Bar.code(), Collections.unmodifiableMap(subItemMap)); } } private String _code; private String _alias; private Set<String> _sisterSet; private SubItemImplicit(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return _subItemMapMap.get(code()); } public ClassificationMeta meta() { return CDef.DefMeta.SubItemImplicit; } public String regularStringItem() { return (String)subItemMap().get("regularStringItem"); } public String regularNumberItem() { return (String)subItemMap().get("regularNumberItem"); } public Object regularVariousItem() { return subItemMap().get("regularVariousItem"); } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SubItemImplicit> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof SubItemImplicit) { return OptionalThing.of((SubItemImplicit)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SubItemImplicit> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static SubItemImplicit codeOf(Object code) { if (code == null) { return null; } if (code instanceof SubItemImplicit) { return (SubItemImplicit)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static SubItemImplicit nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<SubItemImplicit> listAll() { return new ArrayList<SubItemImplicit>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<SubItemImplicit> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: SubItemImplicit." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<SubItemImplicit> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<SubItemImplicit> clsList = new ArrayList<SubItemImplicit>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<SubItemImplicit> groupOf(String groupName) { return new ArrayList<SubItemImplicit>(4); } @Override public String toString() { return code(); } } /** * the test of sub-item map for table classification */ public enum SubItemTable implements CDef { /** 正式会員: 正式な会員としてサイトサービスが利用可能 */ 正式会員("FML", "正式会員", emptyStrings()) , /** 退会会員: 退会が確定した会員でサイトサービスはダメ */ 退会会員("WDL", "退会会員", emptyStrings()) , /** 仮会員: 入会直後のステータスで一部のサイトサービスが利用可能 */ 仮会員("PRV", "仮会員", emptyStrings()) ; private static final Map<String, SubItemTable> _codeClsMap = new HashMap<String, SubItemTable>(); private static final Map<String, SubItemTable> _nameClsMap = new HashMap<String, SubItemTable>(); static { for (SubItemTable value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private static final Map<String, Map<String, Object>> _subItemMapMap = new HashMap<String, Map<String, Object>>(); static { { Map<String, Object> subItemMap = new HashMap<String, Object>(); subItemMap.put("key1", "1"); subItemMap.put("key2", "正式会員"); subItemMap.put("key3", null); _subItemMapMap.put(正式会員.code(), Collections.unmodifiableMap(subItemMap)); } { Map<String, Object> subItemMap = new HashMap<String, Object>(); subItemMap.put("key1", "2"); subItemMap.put("key2", "退会会員"); subItemMap.put("key3", null); _subItemMapMap.put(退会会員.code(), Collections.unmodifiableMap(subItemMap)); } { Map<String, Object> subItemMap = new HashMap<String, Object>(); subItemMap.put("key1", "3"); subItemMap.put("key2", "仮会員"); subItemMap.put("key3", null); _subItemMapMap.put(仮会員.code(), Collections.unmodifiableMap(subItemMap)); } } private String _code; private String _alias; private Set<String> _sisterSet; private SubItemTable(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return _subItemMapMap.get(code()); } public ClassificationMeta meta() { return CDef.DefMeta.SubItemTable; } public String key1() { return (String)subItemMap().get("key1"); } public String key2() { return (String)subItemMap().get("key2"); } public String key3() { return (String)subItemMap().get("key3"); } /** * Is the classification in the group? <br> * サービスが利用できる会員 <br> * The group elements:[正式会員, 仮会員] * @return The determination, true or false. */ public boolean isServiceAvailable() { return 正式会員.equals(this) || 仮会員.equals(this); } /** * Is the classification in the group? <br> * The group elements:[退会会員] * @return The determination, true or false. */ public boolean isLastestStatus() { return 退会会員.equals(this); } public boolean inGroup(String groupName) { if ("serviceAvailable".equals(groupName)) { return isServiceAvailable(); } if ("lastestStatus".equals(groupName)) { return isLastestStatus(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SubItemTable> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof SubItemTable) { return OptionalThing.of((SubItemTable)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<SubItemTable> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static SubItemTable codeOf(Object code) { if (code == null) { return null; } if (code instanceof SubItemTable) { return (SubItemTable)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static SubItemTable nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<SubItemTable> listAll() { return new ArrayList<SubItemTable>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<SubItemTable> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("serviceAvailable".equalsIgnoreCase(groupName)) { return listOfServiceAvailable(); } if ("lastestStatus".equalsIgnoreCase(groupName)) { return listOfLastestStatus(); } throw new ClassificationNotFoundException("Unknown classification group: SubItemTable." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<SubItemTable> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<SubItemTable> clsList = new ArrayList<SubItemTable>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * サービスが利用できる会員 <br> * The group elements:[正式会員, 仮会員] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<SubItemTable> listOfServiceAvailable() { return new ArrayList<SubItemTable>(Arrays.asList(正式会員, 仮会員)); } /** * Get the list of group classification elements. (returns new copied list) <br> * The group elements:[退会会員] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<SubItemTable> listOfLastestStatus() { return new ArrayList<SubItemTable>(Arrays.asList(退会会員)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<SubItemTable> groupOf(String groupName) { if ("serviceAvailable".equals(groupName)) { return listOfServiceAvailable(); } if ("lastestStatus".equals(groupName)) { return listOfLastestStatus(); } return new ArrayList<SubItemTable>(4); } @Override public String toString() { return code(); } } /** * boolean classification for boolean column */ public enum BooleanFlg implements CDef { /** Checked: means yes */ True("true", "Checked", emptyStrings()) , /** Unchecked: means no */ False("false", "Unchecked", emptyStrings()) ; private static final Map<String, BooleanFlg> _codeClsMap = new HashMap<String, BooleanFlg>(); private static final Map<String, BooleanFlg> _nameClsMap = new HashMap<String, BooleanFlg>(); static { for (BooleanFlg value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private BooleanFlg(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.BooleanFlg; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<BooleanFlg> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof BooleanFlg) { return OptionalThing.of((BooleanFlg)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<BooleanFlg> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static BooleanFlg codeOf(Object code) { if (code == null) { return null; } if (code instanceof BooleanFlg) { return (BooleanFlg)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static BooleanFlg nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<BooleanFlg> listAll() { return new ArrayList<BooleanFlg>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<BooleanFlg> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: BooleanFlg." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<BooleanFlg> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<BooleanFlg> clsList = new ArrayList<BooleanFlg>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<BooleanFlg> groupOf(String groupName) { return new ArrayList<BooleanFlg>(4); } @Override public String toString() { return code(); } } /** * master type of variant relation (biz-many-to-one) */ public enum VariantRelationMasterType implements CDef { /** FooCls */ FooCls("FOO", "FooCls", emptyStrings()) , /** BarCls */ BarCls("BAR", "BarCls", emptyStrings()) , /** QuxCls */ QuxCls("QUX", "QuxCls", emptyStrings()) , /** CorgeCls */ CorgeCls("CORGE", "CorgeCls", emptyStrings()) ; private static final Map<String, VariantRelationMasterType> _codeClsMap = new HashMap<String, VariantRelationMasterType>(); private static final Map<String, VariantRelationMasterType> _nameClsMap = new HashMap<String, VariantRelationMasterType>(); static { for (VariantRelationMasterType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private VariantRelationMasterType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.VariantRelationMasterType; } /** * Is the classification in the group? <br> * Foo or Bar or Qux <br> * The group elements:[FooCls, BarCls, QuxCls] * @return The determination, true or false. */ public boolean isFooBarQux() { return FooCls.equals(this) || BarCls.equals(this) || QuxCls.equals(this); } public boolean inGroup(String groupName) { if ("fooBarQux".equals(groupName)) { return isFooBarQux(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<VariantRelationMasterType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof VariantRelationMasterType) { return OptionalThing.of((VariantRelationMasterType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<VariantRelationMasterType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static VariantRelationMasterType codeOf(Object code) { if (code == null) { return null; } if (code instanceof VariantRelationMasterType) { return (VariantRelationMasterType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static VariantRelationMasterType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<VariantRelationMasterType> listAll() { return new ArrayList<VariantRelationMasterType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<VariantRelationMasterType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("fooBarQux".equalsIgnoreCase(groupName)) { return listOfFooBarQux(); } throw new ClassificationNotFoundException("Unknown classification group: VariantRelationMasterType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<VariantRelationMasterType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<VariantRelationMasterType> clsList = new ArrayList<VariantRelationMasterType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * Foo or Bar or Qux <br> * The group elements:[FooCls, BarCls, QuxCls] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<VariantRelationMasterType> listOfFooBarQux() { return new ArrayList<VariantRelationMasterType>(Arrays.asList(FooCls, BarCls, QuxCls)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<VariantRelationMasterType> groupOf(String groupName) { if ("fooBarQux".equals(groupName)) { return listOfFooBarQux(); } return new ArrayList<VariantRelationMasterType>(4); } @Override public String toString() { return code(); } } /** * qux type of variant relation (biz-many-to-one) */ public enum VariantRelationQuxType implements CDef { /** Qua */ Qua("Qua", "Qua", emptyStrings()) , /** Que */ Que("Que", "Que", emptyStrings()) , /** Quo */ Quo("Quo", "Quo", emptyStrings()) ; private static final Map<String, VariantRelationQuxType> _codeClsMap = new HashMap<String, VariantRelationQuxType>(); private static final Map<String, VariantRelationQuxType> _nameClsMap = new HashMap<String, VariantRelationQuxType>(); static { for (VariantRelationQuxType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private VariantRelationQuxType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.VariantRelationQuxType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<VariantRelationQuxType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof VariantRelationQuxType) { return OptionalThing.of((VariantRelationQuxType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<VariantRelationQuxType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static VariantRelationQuxType codeOf(Object code) { if (code == null) { return null; } if (code instanceof VariantRelationQuxType) { return (VariantRelationQuxType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static VariantRelationQuxType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<VariantRelationQuxType> listAll() { return new ArrayList<VariantRelationQuxType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<VariantRelationQuxType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: VariantRelationQuxType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<VariantRelationQuxType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<VariantRelationQuxType> clsList = new ArrayList<VariantRelationQuxType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<VariantRelationQuxType> groupOf(String groupName) { return new ArrayList<VariantRelationQuxType>(4); } @Override public String toString() { return code(); } } /** * merged */ public enum QuxCls implements CDef { /** Merged: merged qux element */ Merged("MRG", "Merged", emptyStrings()) , /** QuxOne: QuxOne */ QuxOne("Q01", "QuxOne", emptyStrings()) , /** QuxTwo: QuxTwo */ QuxTwo("Q02", "QuxTwo", emptyStrings()) , /** QuxThree: QuxThree */ QuxThree("Q03", "QuxThree", emptyStrings()) ; private static final Map<String, QuxCls> _codeClsMap = new HashMap<String, QuxCls>(); private static final Map<String, QuxCls> _nameClsMap = new HashMap<String, QuxCls>(); static { for (QuxCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private QuxCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.QuxCls; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<QuxCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof QuxCls) { return OptionalThing.of((QuxCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<QuxCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static QuxCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof QuxCls) { return (QuxCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static QuxCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<QuxCls> listAll() { return new ArrayList<QuxCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<QuxCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: QuxCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<QuxCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<QuxCls> clsList = new ArrayList<QuxCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<QuxCls> groupOf(String groupName) { return new ArrayList<QuxCls>(4); } @Override public String toString() { return code(); } } /** * delimiter; &amp; endBrace} &amp; path\foo\bar */ public enum EscapedDfpropCls implements CDef { /** First: delimiter &amp; rear escape char */ First(";@\\", "First", emptyStrings()) , /** Second: escape char &amp; endBrace &amp; delimiter */ Second("\\};", "Second", emptyStrings()) , /** Third: startBrace &amp; equal &amp; endBrace */ Third("{=}", "Third", emptyStrings()) ; private static final Map<String, EscapedDfpropCls> _codeClsMap = new HashMap<String, EscapedDfpropCls>(); private static final Map<String, EscapedDfpropCls> _nameClsMap = new HashMap<String, EscapedDfpropCls>(); static { for (EscapedDfpropCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private EscapedDfpropCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.EscapedDfpropCls; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedDfpropCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof EscapedDfpropCls) { return OptionalThing.of((EscapedDfpropCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedDfpropCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static EscapedDfpropCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof EscapedDfpropCls) { return (EscapedDfpropCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static EscapedDfpropCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<EscapedDfpropCls> listAll() { return new ArrayList<EscapedDfpropCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<EscapedDfpropCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: EscapedDfpropCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<EscapedDfpropCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<EscapedDfpropCls> clsList = new ArrayList<EscapedDfpropCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<EscapedDfpropCls> groupOf(String groupName) { return new ArrayList<EscapedDfpropCls>(4); } @Override public String toString() { return code(); } } /** * /*IF pmb.yourTop&#42;/&gt;&lt;&amp; */ public enum EscapedJavaDocCls implements CDef { /** First: /*IF pmb.yourFooComment&#42;/&gt;&lt;&amp; */ First("FOO", "First", emptyStrings()) , /** Second: /*IF pmb.yourBarComment&#42;/&gt;&lt;&amp; */ Second("BAR", "Second", emptyStrings()) ; private static final Map<String, EscapedJavaDocCls> _codeClsMap = new HashMap<String, EscapedJavaDocCls>(); private static final Map<String, EscapedJavaDocCls> _nameClsMap = new HashMap<String, EscapedJavaDocCls>(); static { for (EscapedJavaDocCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private EscapedJavaDocCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.EscapedJavaDocCls; } /** * Is the classification in the group? <br> * /*IF pmb.yourGroup&#42;/&gt;&lt;&amp; <br> * The group elements:[First, Second] * @return The determination, true or false. */ public boolean isLineGroup() { return First.equals(this) || Second.equals(this); } public boolean inGroup(String groupName) { if ("lineGroup".equals(groupName)) { return isLineGroup(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedJavaDocCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof EscapedJavaDocCls) { return OptionalThing.of((EscapedJavaDocCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedJavaDocCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static EscapedJavaDocCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof EscapedJavaDocCls) { return (EscapedJavaDocCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static EscapedJavaDocCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<EscapedJavaDocCls> listAll() { return new ArrayList<EscapedJavaDocCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<EscapedJavaDocCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("lineGroup".equalsIgnoreCase(groupName)) { return listOfLineGroup(); } throw new ClassificationNotFoundException("Unknown classification group: EscapedJavaDocCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<EscapedJavaDocCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<EscapedJavaDocCls> clsList = new ArrayList<EscapedJavaDocCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * /*IF pmb.yourGroup&#42;/&gt;&lt;&amp; <br> * The group elements:[First, Second] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<EscapedJavaDocCls> listOfLineGroup() { return new ArrayList<EscapedJavaDocCls>(Arrays.asList(First, Second)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<EscapedJavaDocCls> groupOf(String groupName) { if ("lineGroup".equals(groupName)) { return listOfLineGroup(); } return new ArrayList<EscapedJavaDocCls>(4); } @Override public String toString() { return code(); } } /** * 6 */ public enum EscapedNumberInitialCls implements CDef { /** 1Foo */ N1Foo("1FO", "1Foo", emptyStrings()) , /** 3Bar */ N3Bar("3BA", "3Bar", emptyStrings()) , /** 7Qux */ N7Qux("7QU", "7Qux", emptyStrings()) , /** Corge9 */ Corge9("CO9", "Corge9", emptyStrings()) ; private static final Map<String, EscapedNumberInitialCls> _codeClsMap = new HashMap<String, EscapedNumberInitialCls>(); private static final Map<String, EscapedNumberInitialCls> _nameClsMap = new HashMap<String, EscapedNumberInitialCls>(); static { for (EscapedNumberInitialCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private EscapedNumberInitialCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.EscapedNumberInitialCls; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedNumberInitialCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof EscapedNumberInitialCls) { return OptionalThing.of((EscapedNumberInitialCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<EscapedNumberInitialCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static EscapedNumberInitialCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof EscapedNumberInitialCls) { return (EscapedNumberInitialCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static EscapedNumberInitialCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<EscapedNumberInitialCls> listAll() { return new ArrayList<EscapedNumberInitialCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<EscapedNumberInitialCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: EscapedNumberInitialCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<EscapedNumberInitialCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<EscapedNumberInitialCls> clsList = new ArrayList<EscapedNumberInitialCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<EscapedNumberInitialCls> groupOf(String groupName) { return new ArrayList<EscapedNumberInitialCls>(4); } @Override public String toString() { return code(); } } /** * top first line top second line top third line */ public enum LineSepCommentCls implements CDef { /** First: foo first line foo second line */ First("FOO", "First", emptyStrings()) , /** Second: bar first line bar second line */ Second("BAR", "Second", emptyStrings()) ; private static final Map<String, LineSepCommentCls> _codeClsMap = new HashMap<String, LineSepCommentCls>(); private static final Map<String, LineSepCommentCls> _nameClsMap = new HashMap<String, LineSepCommentCls>(); static { for (LineSepCommentCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private LineSepCommentCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.LineSepCommentCls; } /** * Is the classification in the group? <br> * group first line group second line <br> * The group elements:[First, Second] * @return The determination, true or false. */ public boolean isLineGroup() { return First.equals(this) || Second.equals(this); } public boolean inGroup(String groupName) { if ("lineGroup".equals(groupName)) { return isLineGroup(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<LineSepCommentCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof LineSepCommentCls) { return OptionalThing.of((LineSepCommentCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<LineSepCommentCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static LineSepCommentCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof LineSepCommentCls) { return (LineSepCommentCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static LineSepCommentCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<LineSepCommentCls> listAll() { return new ArrayList<LineSepCommentCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<LineSepCommentCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("lineGroup".equalsIgnoreCase(groupName)) { return listOfLineGroup(); } throw new ClassificationNotFoundException("Unknown classification group: LineSepCommentCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<LineSepCommentCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<LineSepCommentCls> clsList = new ArrayList<LineSepCommentCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * group first line group second line <br> * The group elements:[First, Second] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<LineSepCommentCls> listOfLineGroup() { return new ArrayList<LineSepCommentCls>(Arrays.asList(First, Second)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<LineSepCommentCls> groupOf(String groupName) { if ("lineGroup".equals(groupName)) { return listOfLineGroup(); } return new ArrayList<LineSepCommentCls>(4); } @Override public String toString() { return code(); } } /** * no camelizing classification */ public enum NamingDefaultCamelizingType implements CDef { /** Bonvo */ Bonvo("BONVO", "Bonvo", emptyStrings()) , /** dstore */ Dstore("DSTORE", "dstore", emptyStrings()) , /** LAND陸oneman */ LAND陸oneman("LAND", "LAND陸oneman", emptyStrings()) , /** PI AR-I */ PiArI("PIARI", "PI AR-I", emptyStrings()) , /** SEA海MYSTIC */ Sea海mystic("SEA", "SEA海MYSTIC", emptyStrings()) ; private static final Map<String, NamingDefaultCamelizingType> _codeClsMap = new HashMap<String, NamingDefaultCamelizingType>(); private static final Map<String, NamingDefaultCamelizingType> _nameClsMap = new HashMap<String, NamingDefaultCamelizingType>(); static { for (NamingDefaultCamelizingType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private NamingDefaultCamelizingType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.NamingDefaultCamelizingType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<NamingDefaultCamelizingType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof NamingDefaultCamelizingType) { return OptionalThing.of((NamingDefaultCamelizingType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<NamingDefaultCamelizingType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static NamingDefaultCamelizingType codeOf(Object code) { if (code == null) { return null; } if (code instanceof NamingDefaultCamelizingType) { return (NamingDefaultCamelizingType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static NamingDefaultCamelizingType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<NamingDefaultCamelizingType> listAll() { return new ArrayList<NamingDefaultCamelizingType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<NamingDefaultCamelizingType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: NamingDefaultCamelizingType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<NamingDefaultCamelizingType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<NamingDefaultCamelizingType> clsList = new ArrayList<NamingDefaultCamelizingType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<NamingDefaultCamelizingType> groupOf(String groupName) { return new ArrayList<NamingDefaultCamelizingType>(4); } @Override public String toString() { return code(); } } /** * no camelizing classification */ public enum NamingNoCamelizingType implements CDef { /** Bonvo */ Bonvo("BONVO", "Bonvo", emptyStrings()) , /** dstore */ dstore("DSTORE", "dstore", emptyStrings()) , /** LAND陸oneman */ LAND陸oneman("LAND", "LAND陸oneman", emptyStrings()) , /** PI AR-I */ PI_ARI("PIARI", "PI AR-I", emptyStrings()) , /** SEA海MYSTIC */ SEA海MYSTIC("SEA", "SEA海MYSTIC", emptyStrings()) ; private static final Map<String, NamingNoCamelizingType> _codeClsMap = new HashMap<String, NamingNoCamelizingType>(); private static final Map<String, NamingNoCamelizingType> _nameClsMap = new HashMap<String, NamingNoCamelizingType>(); static { for (NamingNoCamelizingType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private NamingNoCamelizingType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.NamingNoCamelizingType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<NamingNoCamelizingType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof NamingNoCamelizingType) { return OptionalThing.of((NamingNoCamelizingType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<NamingNoCamelizingType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static NamingNoCamelizingType codeOf(Object code) { if (code == null) { return null; } if (code instanceof NamingNoCamelizingType) { return (NamingNoCamelizingType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static NamingNoCamelizingType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<NamingNoCamelizingType> listAll() { return new ArrayList<NamingNoCamelizingType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<NamingNoCamelizingType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: NamingNoCamelizingType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<NamingNoCamelizingType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<NamingNoCamelizingType> clsList = new ArrayList<NamingNoCamelizingType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<NamingNoCamelizingType> groupOf(String groupName) { return new ArrayList<NamingNoCamelizingType>(4); } @Override public String toString() { return code(); } } /** * is deprecated classification */ @Deprecated public enum DeprecatedTopBasicType implements CDef { /** FooName */ FooName("FOO", "FooName", emptyStrings()) , /** BarName */ BarName("BAR", "BarName", emptyStrings()) , /** QuxName */ QuxName("QUX", "QuxName", emptyStrings()) ; private static final Map<String, DeprecatedTopBasicType> _codeClsMap = new HashMap<String, DeprecatedTopBasicType>(); private static final Map<String, DeprecatedTopBasicType> _nameClsMap = new HashMap<String, DeprecatedTopBasicType>(); static { for (DeprecatedTopBasicType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private DeprecatedTopBasicType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedTopBasicType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedTopBasicType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof DeprecatedTopBasicType) { return OptionalThing.of((DeprecatedTopBasicType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedTopBasicType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static DeprecatedTopBasicType codeOf(Object code) { if (code == null) { return null; } if (code instanceof DeprecatedTopBasicType) { return (DeprecatedTopBasicType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static DeprecatedTopBasicType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<DeprecatedTopBasicType> listAll() { return new ArrayList<DeprecatedTopBasicType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<DeprecatedTopBasicType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: DeprecatedTopBasicType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<DeprecatedTopBasicType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<DeprecatedTopBasicType> clsList = new ArrayList<DeprecatedTopBasicType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<DeprecatedTopBasicType> groupOf(String groupName) { return new ArrayList<DeprecatedTopBasicType>(4); } @Override public String toString() { return code(); } } /** * has deprecated element */ public enum DeprecatedMapBasicType implements CDef { /** FooName */ FooName("FOO", "FooName", emptyStrings()) , /** BarName: (deprecated: test of deprecated) */ @Deprecated BarName("BAR", "BarName", emptyStrings()) , /** QuxName */ QuxName("QUX", "QuxName", emptyStrings()) ; private static final Map<String, DeprecatedMapBasicType> _codeClsMap = new HashMap<String, DeprecatedMapBasicType>(); private static final Map<String, DeprecatedMapBasicType> _nameClsMap = new HashMap<String, DeprecatedMapBasicType>(); static { for (DeprecatedMapBasicType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private DeprecatedMapBasicType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedMapBasicType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedMapBasicType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof DeprecatedMapBasicType) { return OptionalThing.of((DeprecatedMapBasicType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedMapBasicType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static DeprecatedMapBasicType codeOf(Object code) { if (code == null) { return null; } if (code instanceof DeprecatedMapBasicType) { return (DeprecatedMapBasicType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static DeprecatedMapBasicType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<DeprecatedMapBasicType> listAll() { return new ArrayList<DeprecatedMapBasicType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<DeprecatedMapBasicType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: DeprecatedMapBasicType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<DeprecatedMapBasicType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<DeprecatedMapBasicType> clsList = new ArrayList<DeprecatedMapBasicType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<DeprecatedMapBasicType> groupOf(String groupName) { return new ArrayList<DeprecatedMapBasicType>(4); } @Override public String toString() { return code(); } } /** * has deprecated element */ public enum DeprecatedMapCollaborationType implements CDef { /** FooName */ FooName("FOO", "FooName", emptyStrings()) , /** BarBar: here (deprecated: test of deprecated) */ @Deprecated BarName("BAR", "BarBar", emptyStrings()) , /** QuxQux: (deprecated: no original comment) */ @Deprecated QuxName("QUX", "QuxQux", emptyStrings()) ; private static final Map<String, DeprecatedMapCollaborationType> _codeClsMap = new HashMap<String, DeprecatedMapCollaborationType>(); private static final Map<String, DeprecatedMapCollaborationType> _nameClsMap = new HashMap<String, DeprecatedMapCollaborationType>(); static { for (DeprecatedMapCollaborationType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private DeprecatedMapCollaborationType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedMapCollaborationType; } /** * Is the classification in the group? <br> * contains deprecated element here <br> * The group elements:[FooName, BarName] * @return The determination, true or false. */ public boolean isContainsDeprecated() { return FooName.equals(this) || BarName.equals(this); } public boolean inGroup(String groupName) { if ("containsDeprecated".equals(groupName)) { return isContainsDeprecated(); } return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedMapCollaborationType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof DeprecatedMapCollaborationType) { return OptionalThing.of((DeprecatedMapCollaborationType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<DeprecatedMapCollaborationType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static DeprecatedMapCollaborationType codeOf(Object code) { if (code == null) { return null; } if (code instanceof DeprecatedMapCollaborationType) { return (DeprecatedMapCollaborationType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static DeprecatedMapCollaborationType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<DeprecatedMapCollaborationType> listAll() { return new ArrayList<DeprecatedMapCollaborationType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<DeprecatedMapCollaborationType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } if ("containsDeprecated".equalsIgnoreCase(groupName)) { return listOfContainsDeprecated(); } throw new ClassificationNotFoundException("Unknown classification group: DeprecatedMapCollaborationType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<DeprecatedMapCollaborationType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<DeprecatedMapCollaborationType> clsList = new ArrayList<DeprecatedMapCollaborationType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of group classification elements. (returns new copied list) <br> * contains deprecated element here <br> * The group elements:[FooName, BarName] * @return The snapshot list of classification elements in the group. (NotNull) */ public static List<DeprecatedMapCollaborationType> listOfContainsDeprecated() { return new ArrayList<DeprecatedMapCollaborationType>(Arrays.asList(FooName, BarName)); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<DeprecatedMapCollaborationType> groupOf(String groupName) { if ("containsDeprecated".equals(groupName)) { return listOfContainsDeprecated(); } return new ArrayList<DeprecatedMapCollaborationType>(4); } @Override public String toString() { return code(); } } /** * unique key as classification */ public enum UQClassificationType implements CDef { ; private static final Map<String, UQClassificationType> _codeClsMap = new HashMap<String, UQClassificationType>(); private static final Map<String, UQClassificationType> _nameClsMap = new HashMap<String, UQClassificationType>(); static { for (UQClassificationType value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private UQClassificationType(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.UQClassificationType; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<UQClassificationType> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof UQClassificationType) { return OptionalThing.of((UQClassificationType)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<UQClassificationType> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static UQClassificationType codeOf(Object code) { if (code == null) { return null; } if (code instanceof UQClassificationType) { return (UQClassificationType)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static UQClassificationType nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<UQClassificationType> listAll() { return new ArrayList<UQClassificationType>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<UQClassificationType> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: UQClassificationType." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<UQClassificationType> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<UQClassificationType> clsList = new ArrayList<UQClassificationType>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<UQClassificationType> groupOf(String groupName) { return new ArrayList<UQClassificationType>(4); } @Override public String toString() { return code(); } } /** * Classification of Bar */ public enum BarCls implements CDef { /** BarOne: BarOne */ BarOne("B01", "BarOne", emptyStrings()) , /** BarTwo: BarTwo */ BarTwo("B02", "BarTwo", emptyStrings()) , /** BarThree: BarThree */ BarThree("B03", "BarThree", emptyStrings()) , /** BarFour: BarFour */ BarFour("B04", "BarFour", emptyStrings()) , /** BarFive: BarFive */ BarFive("B05", "BarFive", emptyStrings()) ; private static final Map<String, BarCls> _codeClsMap = new HashMap<String, BarCls>(); private static final Map<String, BarCls> _nameClsMap = new HashMap<String, BarCls>(); static { for (BarCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private BarCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.BarCls; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<BarCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof BarCls) { return OptionalThing.of((BarCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<BarCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static BarCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof BarCls) { return (BarCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static BarCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<BarCls> listAll() { return new ArrayList<BarCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<BarCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: BarCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<BarCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<BarCls> clsList = new ArrayList<BarCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<BarCls> groupOf(String groupName) { return new ArrayList<BarCls>(4); } @Override public String toString() { return code(); } } /** * Classification of Foo */ public enum FooCls implements CDef { /** FooOne: FooOne */ FooOne("F01", "FooOne", emptyStrings()) , /** FooTwo: FooTwo */ FooTwo("F02", "FooTwo", emptyStrings()) , /** FooThree: FooThree */ FooThree("F03", "FooThree", emptyStrings()) , /** FooFour: FooFour */ FooFour("F04", "FooFour", emptyStrings()) ; private static final Map<String, FooCls> _codeClsMap = new HashMap<String, FooCls>(); private static final Map<String, FooCls> _nameClsMap = new HashMap<String, FooCls>(); static { for (FooCls value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private FooCls(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.FooCls; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<FooCls> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof FooCls) { return OptionalThing.of((FooCls)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<FooCls> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static FooCls codeOf(Object code) { if (code == null) { return null; } if (code instanceof FooCls) { return (FooCls)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static FooCls nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<FooCls> listAll() { return new ArrayList<FooCls>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<FooCls> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: FooCls." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<FooCls> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<FooCls> clsList = new ArrayList<FooCls>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<FooCls> groupOf(String groupName) { return new ArrayList<FooCls>(4); } @Override public String toString() { return code(); } } /** * フラグを示す */ public enum Flg implements CDef { /** はい: 有効を示す */ True("1", "はい", emptyStrings()) , /** いいえ: 無効を示す */ False("0", "いいえ", emptyStrings()) ; private static final Map<String, Flg> _codeClsMap = new HashMap<String, Flg>(); private static final Map<String, Flg> _nameClsMap = new HashMap<String, Flg>(); static { for (Flg value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private Flg(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.Flg; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<Flg> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof Flg) { return OptionalThing.of((Flg)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<Flg> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static Flg codeOf(Object code) { if (code == null) { return null; } if (code instanceof Flg) { return (Flg)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static Flg nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<Flg> listAll() { return new ArrayList<Flg>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<Flg> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: Flg." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<Flg> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<Flg> clsList = new ArrayList<Flg>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<Flg> groupOf(String groupName) { return new ArrayList<Flg>(4); } @Override public String toString() { return code(); } } /** * 会員ステータス: 会員の状態を示す */ public enum MemberStatus implements CDef { /** 正式会員: 正式な会員を示す */ Formalized("FML", "正式会員", emptyStrings()) , /** 仮会員: 仮の会員を示す */ Provisional("PRV", "仮会員", emptyStrings()) , /** 退会会員: 退会した会員を示す */ Withdrawal("WDL", "退会会員", emptyStrings()) ; private static final Map<String, MemberStatus> _codeClsMap = new HashMap<String, MemberStatus>(); private static final Map<String, MemberStatus> _nameClsMap = new HashMap<String, MemberStatus>(); static { for (MemberStatus value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private MemberStatus(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.MemberStatus; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<MemberStatus> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof MemberStatus) { return OptionalThing.of((MemberStatus)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<MemberStatus> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static MemberStatus codeOf(Object code) { if (code == null) { return null; } if (code instanceof MemberStatus) { return (MemberStatus)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static MemberStatus nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<MemberStatus> listAll() { return new ArrayList<MemberStatus>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<MemberStatus> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: MemberStatus." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<MemberStatus> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<MemberStatus> clsList = new ArrayList<MemberStatus>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<MemberStatus> groupOf(String groupName) { return new ArrayList<MemberStatus>(4); } @Override public String toString() { return code(); } } /** * 商品ステータス: 商品の状態を示す */ public enum ProductStatus implements CDef { /** 生産販売可能 */ OnSale("ONS", "生産販売可能", emptyStrings()) , /** 生産中止 */ ProductStop("PST", "生産中止", emptyStrings()) , /** 販売中止 */ SaleStop("SST", "販売中止", emptyStrings()) ; private static final Map<String, ProductStatus> _codeClsMap = new HashMap<String, ProductStatus>(); private static final Map<String, ProductStatus> _nameClsMap = new HashMap<String, ProductStatus>(); static { for (ProductStatus value : values()) { _codeClsMap.put(value.code().toLowerCase(), value); for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); } _nameClsMap.put(value.name().toLowerCase(), value); } } private String _code; private String _alias; private Set<String> _sisterSet; private ProductStatus(String code, String alias, String[] sisters) { _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); } public String code() { return _code; } public String alias() { return _alias; } public Set<String> sisterSet() { return _sisterSet; } public Map<String, Object> subItemMap() { return Collections.emptyMap(); } public ClassificationMeta meta() { return CDef.DefMeta.ProductStatus; } public boolean inGroup(String groupName) { return false; } /** * Get the classification of the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty) * @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<ProductStatus> of(Object code) { if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); } if (code instanceof ProductStatus) { return OptionalThing.of((ProductStatus)code); } if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); } return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification code: " + code); }); } /** * Find the classification by the name. (CaseInsensitive) * @param name The string of name, which is case-insensitive. (NotNull) * @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty) */ public static OptionalThing<ProductStatus> byName(String name) { if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); } return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{ throw new ClassificationNotFoundException("Unknown classification name: " + name); }); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br> * Get the classification by the code. (CaseInsensitive) * @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null) */ public static ProductStatus codeOf(Object code) { if (code == null) { return null; } if (code instanceof ProductStatus) { return (ProductStatus)code; } return _codeClsMap.get(code.toString().toLowerCase()); } /** * <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br> * Get the classification by the name (also called 'value' in ENUM world). * @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null) * @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null) */ public static ProductStatus nameOf(String name) { if (name == null) { return null; } try { return valueOf(name); } catch (RuntimeException ignored) { return null; } } /** * Get the list of all classification elements. (returns new copied list) * @return The snapshot list of all classification elements. (NotNull) */ public static List<ProductStatus> listAll() { return new ArrayList<ProductStatus>(Arrays.asList(values())); } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception) */ public static List<ProductStatus> listByGroup(String groupName) { if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); } throw new ClassificationNotFoundException("Unknown classification group: ProductStatus." + groupName); } /** * Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br> * @param codeList The list of plain code, which is case-insensitive. (NotNull) * @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified) */ public static List<ProductStatus> listOf(Collection<String> codeList) { if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); } List<ProductStatus> clsList = new ArrayList<ProductStatus>(codeList.size()); for (String code : codeList) { clsList.add(of(code).get()); } return clsList; } /** * Get the list of classification elements in the specified group. (returns new copied list) <br> * @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list) * @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found) */ public static List<ProductStatus> groupOf(String groupName) { return new ArrayList<ProductStatus>(4); } @Override public String toString() { return code(); } } public enum DefMeta implements ClassificationMeta { /** 会員が受けられるサービスのランクを示す */ ServiceRank , /** mainly region of member address */ Region , /** reason for member withdrawal */ WithdrawalReason , /** 支払方法 */ PaymentMethod , /** the test of reference variable in grouping map */ GroupingReference , /** The test of relation reference */ SelfReference , /** The test of top only */ TopCommentOnly , /** the test of sub-item map for implicit classification */ SubItemImplicit , /** the test of sub-item map for table classification */ SubItemTable , /** boolean classification for boolean column */ BooleanFlg , /** master type of variant relation (biz-many-to-one) */ VariantRelationMasterType , /** qux type of variant relation (biz-many-to-one) */ VariantRelationQuxType , /** merged */ QuxCls , /** delimiter; &amp; endBrace} &amp; path\foo\bar */ EscapedDfpropCls , /** /*IF pmb.yourTop&#42;/&gt;&lt;&amp; */ EscapedJavaDocCls , /** 6 */ EscapedNumberInitialCls , /** top first line top second line top third line */ LineSepCommentCls , /** no camelizing classification */ NamingDefaultCamelizingType , /** no camelizing classification */ NamingNoCamelizingType , /** is deprecated classification */ DeprecatedTopBasicType , /** has deprecated element */ DeprecatedMapBasicType , /** has deprecated element */ DeprecatedMapCollaborationType , /** unique key as classification */ UQClassificationType , /** Classification of Bar */ BarCls , /** Classification of Foo */ FooCls , /** フラグを示す */ Flg , /** 会員ステータス: 会員の状態を示す */ MemberStatus , /** 商品ステータス: 商品の状態を示す */ ProductStatus ; public String classificationName() { return name(); // same as definition name } public OptionalThing<? extends Classification> of(Object code) { if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.of(code); } if (Region.name().equals(name())) { return CDef.Region.of(code); } if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.of(code); } if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.of(code); } if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.of(code); } if (SelfReference.name().equals(name())) { return CDef.SelfReference.of(code); } if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.of(code); } if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.of(code); } if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.of(code); } if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.of(code); } if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.of(code); } if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.of(code); } if (QuxCls.name().equals(name())) { return CDef.QuxCls.of(code); } if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.of(code); } if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.of(code); } if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.of(code); } if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.of(code); } if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.of(code); } if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.of(code); } if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.of(code); } if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.of(code); } if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.of(code); } if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.of(code); } if (BarCls.name().equals(name())) { return CDef.BarCls.of(code); } if (FooCls.name().equals(name())) { return CDef.FooCls.of(code); } if (Flg.name().equals(name())) { return CDef.Flg.of(code); } if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.of(code); } if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.of(code); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public OptionalThing<? extends Classification> byName(String name) { if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.byName(name); } if (Region.name().equals(name())) { return CDef.Region.byName(name); } if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.byName(name); } if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.byName(name); } if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.byName(name); } if (SelfReference.name().equals(name())) { return CDef.SelfReference.byName(name); } if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.byName(name); } if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.byName(name); } if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.byName(name); } if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.byName(name); } if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.byName(name); } if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.byName(name); } if (QuxCls.name().equals(name())) { return CDef.QuxCls.byName(name); } if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.byName(name); } if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.byName(name); } if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.byName(name); } if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.byName(name); } if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.byName(name); } if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.byName(name); } if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.byName(name); } if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.byName(name); } if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.byName(name); } if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.byName(name); } if (BarCls.name().equals(name())) { return CDef.BarCls.byName(name); } if (FooCls.name().equals(name())) { return CDef.FooCls.byName(name); } if (Flg.name().equals(name())) { return CDef.Flg.byName(name); } if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.byName(name); } if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.byName(name); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public Classification codeOf(Object code) { // null if not found, old style so use of(code) if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.codeOf(code); } if (Region.name().equals(name())) { return CDef.Region.codeOf(code); } if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.codeOf(code); } if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.codeOf(code); } if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.codeOf(code); } if (SelfReference.name().equals(name())) { return CDef.SelfReference.codeOf(code); } if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.codeOf(code); } if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.codeOf(code); } if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.codeOf(code); } if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.codeOf(code); } if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.codeOf(code); } if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.codeOf(code); } if (QuxCls.name().equals(name())) { return CDef.QuxCls.codeOf(code); } if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.codeOf(code); } if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.codeOf(code); } if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.codeOf(code); } if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.codeOf(code); } if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.codeOf(code); } if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.codeOf(code); } if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.codeOf(code); } if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.codeOf(code); } if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.codeOf(code); } if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.codeOf(code); } if (BarCls.name().equals(name())) { return CDef.BarCls.codeOf(code); } if (FooCls.name().equals(name())) { return CDef.FooCls.codeOf(code); } if (Flg.name().equals(name())) { return CDef.Flg.codeOf(code); } if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.codeOf(code); } if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.codeOf(code); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public Classification nameOf(String name) { // null if not found, old style so use byName(name) if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.valueOf(name); } if (Region.name().equals(name())) { return CDef.Region.valueOf(name); } if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.valueOf(name); } if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.valueOf(name); } if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.valueOf(name); } if (SelfReference.name().equals(name())) { return CDef.SelfReference.valueOf(name); } if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.valueOf(name); } if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.valueOf(name); } if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.valueOf(name); } if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.valueOf(name); } if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.valueOf(name); } if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.valueOf(name); } if (QuxCls.name().equals(name())) { return CDef.QuxCls.valueOf(name); } if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.valueOf(name); } if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.valueOf(name); } if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.valueOf(name); } if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.valueOf(name); } if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.valueOf(name); } if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.valueOf(name); } if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.valueOf(name); } if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.valueOf(name); } if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.valueOf(name); } if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.valueOf(name); } if (BarCls.name().equals(name())) { return CDef.BarCls.valueOf(name); } if (FooCls.name().equals(name())) { return CDef.FooCls.valueOf(name); } if (Flg.name().equals(name())) { return CDef.Flg.valueOf(name); } if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.valueOf(name); } if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.valueOf(name); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public List<Classification> listAll() { if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listAll()); } if (Region.name().equals(name())) { return toClsList(CDef.Region.listAll()); } if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listAll()); } if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listAll()); } if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listAll()); } if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listAll()); } if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listAll()); } if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listAll()); } if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listAll()); } if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listAll()); } if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listAll()); } if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listAll()); } if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listAll()); } if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listAll()); } if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listAll()); } if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listAll()); } if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listAll()); } if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listAll()); } if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listAll()); } if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listAll()); } if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listAll()); } if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listAll()); } if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listAll()); } if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listAll()); } if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listAll()); } if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listAll()); } if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listAll()); } if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listAll()); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public List<Classification> listByGroup(String groupName) { // exception if not found if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listByGroup(groupName)); } if (Region.name().equals(name())) { return toClsList(CDef.Region.listByGroup(groupName)); } if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listByGroup(groupName)); } if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listByGroup(groupName)); } if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listByGroup(groupName)); } if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listByGroup(groupName)); } if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listByGroup(groupName)); } if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listByGroup(groupName)); } if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listByGroup(groupName)); } if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listByGroup(groupName)); } if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listByGroup(groupName)); } if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listByGroup(groupName)); } if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listByGroup(groupName)); } if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listByGroup(groupName)); } if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listByGroup(groupName)); } if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listByGroup(groupName)); } if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listByGroup(groupName)); } if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listByGroup(groupName)); } if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listByGroup(groupName)); } if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listByGroup(groupName)); } if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listByGroup(groupName)); } if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listByGroup(groupName)); } if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listByGroup(groupName)); } if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listByGroup(groupName)); } if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listByGroup(groupName)); } if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listByGroup(groupName)); } if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listByGroup(groupName)); } if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listByGroup(groupName)); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public List<Classification> listOf(Collection<String> codeList) { if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listOf(codeList)); } if (Region.name().equals(name())) { return toClsList(CDef.Region.listOf(codeList)); } if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listOf(codeList)); } if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listOf(codeList)); } if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listOf(codeList)); } if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listOf(codeList)); } if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listOf(codeList)); } if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listOf(codeList)); } if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listOf(codeList)); } if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listOf(codeList)); } if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listOf(codeList)); } if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listOf(codeList)); } if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listOf(codeList)); } if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listOf(codeList)); } if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listOf(codeList)); } if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listOf(codeList)); } if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listOf(codeList)); } if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listOf(codeList)); } if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listOf(codeList)); } if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listOf(codeList)); } if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listOf(codeList)); } if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listOf(codeList)); } if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listOf(codeList)); } if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listOf(codeList)); } if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listOf(codeList)); } if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listOf(codeList)); } if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listOf(codeList)); } if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listOf(codeList)); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } public List<Classification> groupOf(String groupName) { // old style if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.groupOf(groupName)); } if (Region.name().equals(name())) { return toClsList(CDef.Region.groupOf(groupName)); } if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.groupOf(groupName)); } if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.groupOf(groupName)); } if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.groupOf(groupName)); } if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.groupOf(groupName)); } if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.groupOf(groupName)); } if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.groupOf(groupName)); } if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.groupOf(groupName)); } if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.groupOf(groupName)); } if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.groupOf(groupName)); } if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.groupOf(groupName)); } if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.groupOf(groupName)); } if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.groupOf(groupName)); } if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.groupOf(groupName)); } if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.groupOf(groupName)); } if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.groupOf(groupName)); } if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.groupOf(groupName)); } if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.groupOf(groupName)); } if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.groupOf(groupName)); } if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.groupOf(groupName)); } if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.groupOf(groupName)); } if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.groupOf(groupName)); } if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.groupOf(groupName)); } if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.groupOf(groupName)); } if (Flg.name().equals(name())) { return toClsList(CDef.Flg.groupOf(groupName)); } if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.groupOf(groupName)); } if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.groupOf(groupName)); } throw new IllegalStateException("Unknown definition: " + this); // basically unreachable } @SuppressWarnings("unchecked") private List<Classification> toClsList(List<?> clsList) { return (List<Classification>)clsList; } public ClassificationCodeType codeType() { if (ServiceRank.name().equals(name())) { return ClassificationCodeType.String; } if (Region.name().equals(name())) { return ClassificationCodeType.Number; } if (WithdrawalReason.name().equals(name())) { return ClassificationCodeType.String; } if (PaymentMethod.name().equals(name())) { return ClassificationCodeType.String; } if (GroupingReference.name().equals(name())) { return ClassificationCodeType.String; } if (SelfReference.name().equals(name())) { return ClassificationCodeType.Number; } if (TopCommentOnly.name().equals(name())) { return ClassificationCodeType.String; } if (SubItemImplicit.name().equals(name())) { return ClassificationCodeType.Number; } if (SubItemTable.name().equals(name())) { return ClassificationCodeType.String; } if (BooleanFlg.name().equals(name())) { return ClassificationCodeType.Boolean; } if (VariantRelationMasterType.name().equals(name())) { return ClassificationCodeType.String; } if (VariantRelationQuxType.name().equals(name())) { return ClassificationCodeType.String; } if (QuxCls.name().equals(name())) { return ClassificationCodeType.String; } if (EscapedDfpropCls.name().equals(name())) { return ClassificationCodeType.String; } if (EscapedJavaDocCls.name().equals(name())) { return ClassificationCodeType.String; } if (EscapedNumberInitialCls.name().equals(name())) { return ClassificationCodeType.String; } if (LineSepCommentCls.name().equals(name())) { return ClassificationCodeType.String; } if (NamingDefaultCamelizingType.name().equals(name())) { return ClassificationCodeType.String; } if (NamingNoCamelizingType.name().equals(name())) { return ClassificationCodeType.String; } if (DeprecatedTopBasicType.name().equals(name())) { return ClassificationCodeType.String; } if (DeprecatedMapBasicType.name().equals(name())) { return ClassificationCodeType.String; } if (DeprecatedMapCollaborationType.name().equals(name())) { return ClassificationCodeType.String; } if (UQClassificationType.name().equals(name())) { return ClassificationCodeType.String; } if (BarCls.name().equals(name())) { return ClassificationCodeType.String; } if (FooCls.name().equals(name())) { return ClassificationCodeType.String; } if (Flg.name().equals(name())) { return ClassificationCodeType.Number; } if (MemberStatus.name().equals(name())) { return ClassificationCodeType.String; } if (ProductStatus.name().equals(name())) { return ClassificationCodeType.String; } return ClassificationCodeType.String; // as default } public ClassificationUndefinedHandlingType undefinedHandlingType() { if (ServiceRank.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (Region.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (WithdrawalReason.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (PaymentMethod.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (GroupingReference.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (SelfReference.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (TopCommentOnly.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (SubItemImplicit.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (SubItemTable.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (BooleanFlg.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (VariantRelationMasterType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (VariantRelationQuxType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (QuxCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (EscapedDfpropCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (EscapedJavaDocCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (EscapedNumberInitialCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (LineSepCommentCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (NamingDefaultCamelizingType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (NamingNoCamelizingType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (DeprecatedTopBasicType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (DeprecatedMapBasicType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (DeprecatedMapCollaborationType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (UQClassificationType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (BarCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (FooCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (Flg.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (MemberStatus.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } if (ProductStatus.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; } return ClassificationUndefinedHandlingType.LOGGING; // as default } public static OptionalThing<CDef.DefMeta> find(String classificationName) { // instead of valueOf() if (classificationName == null) { throw new IllegalArgumentException("The argument 'classificationName' should not be null."); } if (ServiceRank.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.ServiceRank); } if (Region.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.Region); } if (WithdrawalReason.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.WithdrawalReason); } if (PaymentMethod.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.PaymentMethod); } if (GroupingReference.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.GroupingReference); } if (SelfReference.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SelfReference); } if (TopCommentOnly.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.TopCommentOnly); } if (SubItemImplicit.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SubItemImplicit); } if (SubItemTable.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SubItemTable); } if (BooleanFlg.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.BooleanFlg); } if (VariantRelationMasterType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.VariantRelationMasterType); } if (VariantRelationQuxType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.VariantRelationQuxType); } if (QuxCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.QuxCls); } if (EscapedDfpropCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedDfpropCls); } if (EscapedJavaDocCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedJavaDocCls); } if (EscapedNumberInitialCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedNumberInitialCls); } if (LineSepCommentCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.LineSepCommentCls); } if (NamingDefaultCamelizingType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.NamingDefaultCamelizingType); } if (NamingNoCamelizingType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.NamingNoCamelizingType); } if (DeprecatedTopBasicType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedTopBasicType); } if (DeprecatedMapBasicType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedMapBasicType); } if (DeprecatedMapCollaborationType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedMapCollaborationType); } if (UQClassificationType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.UQClassificationType); } if (BarCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.BarCls); } if (FooCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.FooCls); } if (Flg.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.Flg); } if (MemberStatus.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.MemberStatus); } if (ProductStatus.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.ProductStatus); } return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("Unknown classification: " + classificationName); }); } public static CDef.DefMeta meta(String classificationName) { // old style so use find(name) if (classificationName == null) { throw new IllegalArgumentException("The argument 'classificationName' should not be null."); } if (ServiceRank.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.ServiceRank; } if (Region.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.Region; } if (WithdrawalReason.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.WithdrawalReason; } if (PaymentMethod.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.PaymentMethod; } if (GroupingReference.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.GroupingReference; } if (SelfReference.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SelfReference; } if (TopCommentOnly.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.TopCommentOnly; } if (SubItemImplicit.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SubItemImplicit; } if (SubItemTable.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SubItemTable; } if (BooleanFlg.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.BooleanFlg; } if (VariantRelationMasterType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.VariantRelationMasterType; } if (VariantRelationQuxType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.VariantRelationQuxType; } if (QuxCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.QuxCls; } if (EscapedDfpropCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedDfpropCls; } if (EscapedJavaDocCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedJavaDocCls; } if (EscapedNumberInitialCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedNumberInitialCls; } if (LineSepCommentCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.LineSepCommentCls; } if (NamingDefaultCamelizingType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.NamingDefaultCamelizingType; } if (NamingNoCamelizingType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.NamingNoCamelizingType; } if (DeprecatedTopBasicType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedTopBasicType; } if (DeprecatedMapBasicType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedMapBasicType; } if (DeprecatedMapCollaborationType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedMapCollaborationType; } if (UQClassificationType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.UQClassificationType; } if (BarCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.BarCls; } if (FooCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.FooCls; } if (Flg.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.Flg; } if (MemberStatus.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.MemberStatus; } if (ProductStatus.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.ProductStatus; } throw new IllegalStateException("Unknown classification: " + classificationName); } @SuppressWarnings("unused") private String[] xinternalEmptyString() { return emptyStrings(); // to suppress 'unused' warning of import statement } } }
dbflute-test/dbflute-test-dbms-mysql
src/main/java/org/docksidestage/mysql/dbflute/allcommon/CDef.java
Java
apache-2.0
262,223
(function () { 'use strict'; angular .module('brew_journal.layout', [ 'brew_journal.layout.controllers' ]); angular .module('brew_journal.layout.controllers', []); })();
moonboy13/brew-journal
brew_journal/static/js/layout/layout.module.js
JavaScript
apache-2.0
205
<?php /** * @link https://github.com/gridiron-guru/FantasyDataAPI for the canonical source repository * @copyright Copyright (c) 2014 Robert Gunnar Johnson Jr. * @license http://opensource.org/licenses/Apache-2.0 * @package FantasyDataAPI */ namespace FantasyDataAPI\Test\DailyFantasyPlayers\Response; use GuzzleHttp\Message\Response; use GuzzleHttp\Message\RequestInterface; use GuzzleHttp\Stream; class Mock extends Response { public function __construct (RequestInterface $pRequest) { /** url parsing "formula" for resource */ list(, , , $format) = explode( '/', $pRequest->getPath() ); $subscription = 'developer'; $file_partial = __DIR__ . '/' . implode('.', [$subscription, $format]); $headers = include($file_partial . '.header.php'); $response_code = explode(' ', $headers[0])[1]; $mocked_response = file_get_contents($file_partial . '.body.' . $format); $stream = Stream\Stream::factory($mocked_response); parent::__construct($response_code, $headers, $stream); } }
DizzyBHigh/FantasyDataAPI-v2
test/phpunit/DailyFantasyPlayers/Response/Mock.php
PHP
apache-2.0
1,080
// Copyright (c) 2017 Ubisoft Entertainment // // 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. using System; using System.Collections.Generic; using System.IO; using Sharpmake.Generators; using Sharpmake.Generators.FastBuild; using Sharpmake.Generators.VisualStudio; namespace Sharpmake { public static partial class Windows { [PlatformImplementation(Platform.win64, typeof(IPlatformDescriptor), typeof(IFastBuildCompilerSettings), typeof(IWindowsFastBuildCompilerSettings), typeof(IPlatformBff), typeof(IMicrosoftPlatformBff), typeof(IPlatformVcxproj))] public sealed class Win64Platform : BaseWindowsPlatform { #region IPlatformDescriptor implementation public override string SimplePlatformString => "x64"; public override EnvironmentVariableResolver GetPlatformEnvironmentResolver(params VariableAssignment[] assignments) { return new Win64EnvironmentVariableResolver(assignments); } #endregion #region IMicrosoftPlatformBff implementation public override string BffPlatformDefine => "WIN64"; public override string CConfigName => ".win64Config"; public override bool SupportsResourceFiles => true; public override void AddCompilerSettings( IDictionary<string, CompilerSettings> masterCompilerSettings, string compilerName, string rootPath, DevEnv devEnv, string projectRootPath ) { var fastBuildCompilerSettings = PlatformRegistry.Get<IWindowsFastBuildCompilerSettings>(Platform.win64); if (!fastBuildCompilerSettings.BinPath.ContainsKey(devEnv)) fastBuildCompilerSettings.BinPath.Add(devEnv, devEnv.GetVisualStudioBinPath(Platform.win64)); if (!fastBuildCompilerSettings.LinkerPath.ContainsKey(devEnv)) fastBuildCompilerSettings.LinkerPath.Add(devEnv, fastBuildCompilerSettings.BinPath[devEnv]); if (!fastBuildCompilerSettings.ResCompiler.ContainsKey(devEnv)) fastBuildCompilerSettings.ResCompiler.Add(devEnv, devEnv.GetWindowsResourceCompiler(Platform.win64)); CompilerSettings compilerSettings = GetMasterCompilerSettings(masterCompilerSettings, compilerName, rootPath, devEnv, projectRootPath, false); compilerSettings.PlatformFlags |= Platform.win64; SetConfiguration(compilerSettings.Configurations, string.Empty, projectRootPath, devEnv, false); } public override CompilerSettings GetMasterCompilerSettings( IDictionary<string, CompilerSettings> masterCompilerSettings, string compilerName, string rootPath, DevEnv devEnv, string projectRootPath, bool useCCompiler ) { CompilerSettings compilerSettings; if (masterCompilerSettings.ContainsKey(compilerName)) { compilerSettings = masterCompilerSettings[compilerName]; } else { string pathToCompiler = devEnv.GetVisualStudioBinPath(Platform.win64).ReplaceHeadPath(rootPath, "$RootPath$"); Strings extraFiles = new Strings(); extraFiles.Add( Path.Combine(pathToCompiler, "c1.dll"), Path.Combine(pathToCompiler, "c1xx.dll"), Path.Combine(pathToCompiler, "c2.dll"), Path.Combine(pathToCompiler, "mspdbcore.dll"), Path.Combine(pathToCompiler, "mspdbsrv.exe"), Path.Combine(pathToCompiler, @"1033\clui.dll") ); switch (devEnv) { case DevEnv.vs2012: { extraFiles.Add( Path.Combine(pathToCompiler, "c1ast.dll"), Path.Combine(pathToCompiler, "c1xxast.dll"), Path.Combine(pathToCompiler, "mspft110.dll"), Path.Combine(pathToCompiler, "msobj110.dll"), Path.Combine(pathToCompiler, "mspdb110.dll"), @"$RootPath$\redist\x64\Microsoft.VC110.CRT\msvcp110.dll", @"$RootPath$\redist\x64\Microsoft.VC110.CRT\msvcr110.dll", @"$RootPath$\redist\x64\Microsoft.VC110.CRT\vccorlib110.dll" ); } break; case DevEnv.vs2013: { extraFiles.Add( Path.Combine(pathToCompiler, "c1ast.dll"), Path.Combine(pathToCompiler, "c1xxast.dll"), Path.Combine(pathToCompiler, "mspft120.dll"), Path.Combine(pathToCompiler, "msobj120.dll"), Path.Combine(pathToCompiler, "mspdb120.dll"), @"$RootPath$\redist\x64\Microsoft.VC120.CRT\msvcp120.dll", @"$RootPath$\redist\x64\Microsoft.VC120.CRT\msvcr120.dll", @"$RootPath$\redist\x64\Microsoft.VC120.CRT\vccorlib120.dll" ); } break; case DevEnv.vs2015: case DevEnv.vs2017: { string systemDllPath = FastBuildSettings.SystemDllRoot; if (systemDllPath == null) systemDllPath = KitsRootPaths.GetRoot(KitsRootEnum.KitsRoot10) + @"Redist\ucrt\DLLs\x64\"; if (!Path.IsPathRooted(systemDllPath)) systemDllPath = Util.SimplifyPath(Path.Combine(projectRootPath, systemDllPath)); extraFiles.Add( Path.Combine(pathToCompiler, "msobj140.dll"), Path.Combine(pathToCompiler, "mspft140.dll"), Path.Combine(pathToCompiler, "mspdb140.dll") ); if (devEnv == DevEnv.vs2015) { extraFiles.Add( Path.Combine(pathToCompiler, "vcvars64.bat"), @"$RootPath$\redist\x64\Microsoft.VC140.CRT\concrt140.dll", @"$RootPath$\redist\x64\Microsoft.VC140.CRT\msvcp140.dll", @"$RootPath$\redist\x64\Microsoft.VC140.CRT\vccorlib140.dll", @"$RootPath$\redist\x64\Microsoft.VC140.CRT\vcruntime140.dll", Path.Combine(systemDllPath, "ucrtbase.dll") ); } else { extraFiles.Add( Path.Combine(pathToCompiler, "mspdbcore.dll"), Path.Combine(pathToCompiler, "msvcdis140.dll"), Path.Combine(pathToCompiler, "msvcp140.dll"), Path.Combine(pathToCompiler, "pgodb140.dll"), Path.Combine(pathToCompiler, "vcruntime140.dll"), @"$RootPath$\Auxiliary\Build\vcvars64.bat" ); } try { foreach (string p in Directory.EnumerateFiles(systemDllPath, "api-ms-win-*.dll")) extraFiles.Add(p); } catch { } } break; default: throw new NotImplementedException("This devEnv (" + devEnv + ") is not supported!"); } string executable = Path.Combine(pathToCompiler, "cl.exe"); compilerSettings = new CompilerSettings(compilerName, Platform.win64, extraFiles, executable, rootPath, devEnv, new Dictionary<string, CompilerSettings.Configuration>()); masterCompilerSettings.Add(compilerName, compilerSettings); } return compilerSettings; } public override void SetConfiguration(IDictionary<string, CompilerSettings.Configuration> configurations, string compilerName, string projectRootPath, DevEnv devEnv, bool useCCompiler) { string configName = ".win64Config"; if (!configurations.ContainsKey(configName)) { var fastBuildCompilerSettings = PlatformRegistry.Get<IWindowsFastBuildCompilerSettings>(Platform.win64); string binPath = fastBuildCompilerSettings.BinPath[devEnv]; string linkerPath = fastBuildCompilerSettings.LinkerPath[devEnv]; string resCompiler = fastBuildCompilerSettings.ResCompiler[devEnv]; configurations.Add(configName, new CompilerSettings.Configuration( Platform.win64, binPath: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, binPath)), linkerPath: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, linkerPath)), resourceCompiler: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, resCompiler)), librarian: @"$LinkerPath$\lib.exe", linker: @"$LinkerPath$\link.exe" ) ); configurations.Add(".win64ConfigMasm", new CompilerSettings.Configuration(Platform.win64, compiler: @"$BinPath$\ml64.exe", usingOtherConfiguration: @".win64Config")); } } #endregion #region IPlatformVcxproj implementation public override bool HasEditAndContinueDebuggingSupport => true; public override IEnumerable<string> GetImplicitlyDefinedSymbols(IGenerationContext context) { var defines = new List<string>(); defines.AddRange(base.GetImplicitlyDefinedSymbols(context)); defines.Add("WIN64"); return defines; } public override void SetupPlatformTargetOptions(IGenerationContext context) { context.Options["TargetMachine"] = "MachineX64"; context.CommandLineOptions["TargetMachine"] = "/MACHINE:X64"; } protected override IEnumerable<string> GetPlatformIncludePathsImpl(IGenerationContext context) { return EnumerateSemiColonSeparatedString(context.DevelopmentEnvironment.GetWindowsIncludePath()); } #endregion } } }
nidoizo/Sharpmake
Sharpmake.Platforms/Sharpmake.CommonPlatforms/Windows/Win64Platform.cs
C#
apache-2.0
12,450
/* * Copyright 2015-2018 Igor Maznitsa. * * 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.igormaznitsa.mindmap.plugins.processors; import com.igormaznitsa.mindmap.model.Extra; import com.igormaznitsa.mindmap.model.Topic; import com.igormaznitsa.mindmap.plugins.PopUpSection; import com.igormaznitsa.mindmap.plugins.api.AbstractFocusedTopicPlugin; import com.igormaznitsa.mindmap.plugins.api.ExternallyExecutedPlugin; import com.igormaznitsa.mindmap.plugins.api.PluginContext; import com.igormaznitsa.mindmap.swing.panel.Texts; import com.igormaznitsa.mindmap.swing.services.IconID; import com.igormaznitsa.mindmap.swing.services.ImageIconServiceProvider; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.Icon; public class ExtraJumpPlugin extends AbstractFocusedTopicPlugin implements ExternallyExecutedPlugin { private static final Icon ICO = ImageIconServiceProvider.findInstance().getIconForId(IconID.POPUP_EXTRAS_JUMP); @Override public int getOrder() { return 4; } @Override @Nullable protected Icon getIcon(@Nonnull final PluginContext contextl, @Nullable final Topic activeTopic) { return ICO; } @Override @Nonnull protected String getName(@Nonnull final PluginContext context, @Nullable final Topic activeTopic) { if (activeTopic == null) { return "..."; } return activeTopic.getExtras().containsKey(Extra.ExtraType.TOPIC) ? Texts.getString("MMDGraphEditor.makePopUp.miEditTransition") : Texts.getString("MMDGraphEditor.makePopUp.miAddTransition"); } @Override @Nonnull public PopUpSection getSection() { return PopUpSection.EXTRAS; } }
raydac/netbeans-mmd-plugin
mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/plugins/processors/ExtraJumpPlugin.java
Java
apache-2.0
2,189
package com.therealdanvega.blog.repository; import com.therealdanvega.blog.domain.Blog; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Blog entity. */ @SuppressWarnings("unused") public interface BlogRepository extends JpaRepository<Blog,Long> { @Query("select blog from Blog blog where blog.user.login = ?#{principal.username}") List<Blog> findByUserIsCurrentUser(); }
cfaddict/jhipster-course
sample-app/entblog/src/main/java/com/therealdanvega/blog/repository/BlogRepository.java
Java
apache-2.0
453
//----------------------------------------------------------------------- // <copyright file="TypeExtensionsTests.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using Akka.TestKit; using Akka.Util; using FluentAssertions; using Xunit; namespace Akka.Tests.Util { public class AkkaVersionSpec { [Fact] public void Version_should_compare_3_digit_version() { AppVersion.Create("1.2.3").Should().Be(AppVersion.Create("1.2.3")); AppVersion.Create("1.2.3").Should().NotBe(AppVersion.Create("1.2.4")); AppVersion.Create("1.2.4").Should().BeGreaterThan(AppVersion.Create("1.2.3")); AppVersion.Create("3.2.1").Should().BeGreaterThan(AppVersion.Create("1.2.3")); AppVersion.Create("3.2.1").Should().BeLessThan(AppVersion.Create("3.3.1")); AppVersion.Create("3.2.0").Should().BeLessThan(AppVersion.Create("3.2.1")); } [Fact] public void Version_should_not_support_more_than_3_digits_version() { XAssert.Throws<ArgumentOutOfRangeException>(() => AppVersion.Create("1.2.3.1")); } [Fact] public void Version_should_compare_2_digit_version() { AppVersion.Create("1.2").Should().Be(AppVersion.Create("1.2")); AppVersion.Create("1.2").Should().Be(AppVersion.Create("1.2.0")); AppVersion.Create("1.2").Should().NotBe(AppVersion.Create("1.3")); AppVersion.Create("1.2.1").Should().BeGreaterThan(AppVersion.Create("1.2")); AppVersion.Create("2.4").Should().BeGreaterThan(AppVersion.Create("2.3")); AppVersion.Create("3.2").Should().BeLessThan(AppVersion.Create("3.2.7")); } [Fact] public void Version_should_compare_single_digit_version() { AppVersion.Create("1").Should().Be(AppVersion.Create("1")); AppVersion.Create("1").Should().Be(AppVersion.Create("1.0")); AppVersion.Create("1").Should().Be(AppVersion.Create("1.0.0")); AppVersion.Create("1").Should().NotBe(AppVersion.Create("2")); AppVersion.Create("3").Should().BeGreaterThan(AppVersion.Create("2")); AppVersion.Create("2b").Should().BeGreaterThan(AppVersion.Create("2a")); AppVersion.Create("2020-09-07").Should().BeGreaterThan(AppVersion.Create("2020-08-30")); } [Fact] public void Version_should_compare_extra() { AppVersion.Create("1.2.3-M1").Should().Be(AppVersion.Create("1.2.3-M1")); AppVersion.Create("1.2-M1").Should().Be(AppVersion.Create("1.2-M1")); AppVersion.Create("1.2.0-M1").Should().Be(AppVersion.Create("1.2-M1")); AppVersion.Create("1.2.3-M1").Should().NotBe(AppVersion.Create("1.2.3-M2")); AppVersion.Create("1.2-M1").Should().BeLessThan(AppVersion.Create("1.2.0")); AppVersion.Create("1.2.0-M1").Should().BeLessThan(AppVersion.Create("1.2.0")); AppVersion.Create("1.2.3-M2").Should().BeGreaterThan(AppVersion.Create("1.2.3-M1")); } [Fact] public void Version_should_require_digits() { XAssert.Throws<FormatException>(() => AppVersion.Create("1.x.3")); XAssert.Throws<FormatException>(() => AppVersion.Create("1.2x.3")); XAssert.Throws<FormatException>(() => AppVersion.Create("1.2.x")); XAssert.Throws<FormatException>(() => AppVersion.Create("1.2.3x")); XAssert.Throws<FormatException>(() => AppVersion.Create("x.3")); XAssert.Throws<FormatException>(() => AppVersion.Create("1.x")); XAssert.Throws<FormatException>(() => AppVersion.Create("1.2x")); } [Fact] public void Version_should_compare_dynver_format() { // dynver format AppVersion.Create("1.0.10+3-1234abcd").Should().BeLessThan(AppVersion.Create("1.0.11")); AppVersion.Create("1.0.10+3-1234abcd").Should().BeLessThan(AppVersion.Create("1.0.10+10-1234abcd")); AppVersion.Create("1.2+3-1234abcd").Should().BeLessThan(AppVersion.Create("1.2+10-1234abcd")); AppVersion.Create("1.0.0+3-1234abcd+20140707-1030").Should().BeLessThan(AppVersion.Create("1.0.0+3-1234abcd+20140707-1130")); AppVersion.Create("0.0.0+3-2234abcd").Should().BeLessThan(AppVersion.Create("0.0.0+4-1234abcd")); AppVersion.Create("HEAD+20140707-1030").Should().BeLessThan(AppVersion.Create("HEAD+20140707-1130")); AppVersion.Create("1.0.10-3-1234abcd").Should().BeLessThan(AppVersion.Create("1.0.10-10-1234abcd")); AppVersion.Create("1.0.0-3-1234abcd+20140707-1030").Should().BeLessThan(AppVersion.Create("1.0.0-3-1234abcd+20140707-1130")); // not real dynver, but should still work AppVersion.Create("1.0.10+3a-1234abcd").Should().BeLessThan(AppVersion.Create("1.0.10+3b-1234abcd")); } [Fact] public void Version_should_compare_extra_without_digits() { AppVersion.Create("foo").Should().Be(AppVersion.Create("foo")); AppVersion.Create("foo").Should().NotBe(AppVersion.Create("bar")); AppVersion.Create("foo").Should().BeLessThan(AppVersion.Create("1.2.3")); AppVersion.Create("foo").Should().BeGreaterThan(AppVersion.Create("bar")); AppVersion.Create("1-foo").Should().NotBe(AppVersion.Create("01-foo")); AppVersion.Create("1-foo").Should().BeGreaterThan(AppVersion.Create("02-foo")); } } }
simonlaroche/akka.net
src/core/Akka.Tests/Util/AkkaVersionSpec.cs
C#
apache-2.0
5,887
/* * Copyright 2014 Wouter Pinnoo * * 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 eu.pinnoo.garbagecalendar.data; import java.io.Serializable; /** * * @author Wouter Pinnoo <pinnoo.wouter@gmail.com> */ public class Sector implements Serializable { private static final long serialVersionUID = -843402748713889036L; private AreaType type; private String code; public Sector(AreaType type, String code) { this.type = type; this.code = code; } @Override public boolean equals(Object o) { if (o instanceof Sector) { Sector s = (Sector) o; return s.getCode().equals(getCode()) && s.getType().equals(getType()); } return false; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + (this.type != null ? this.type.hashCode() : 0); hash = 23 * hash + (this.code != null ? this.code.hashCode() : 0); return hash; } @Override public String toString() { return type.toString() + code; } public Sector(String str) { if (str.matches("[LlVv][0-9][0-9]")) { switch (str.charAt(0)) { case 'L': type = AreaType.L; break; case 'V': type = AreaType.V; break; default: type = AreaType.NONE; } code = str.substring(1); } else { type = AreaType.CITY; code = str; } } public AreaType getType() { return type; } public String getCode() { return code; } }
wpinnoo/GarbageCalendar
app/src/main/java/eu/pinnoo/garbagecalendar/data/Sector.java
Java
apache-2.0
2,236
# # Author:: Baptiste Courtois (<b.courtois@criteo.com>) # Cookbook:: sql_server # Attribute:: configure # # Copyright:: 2011-2019, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Tcp settings default['sql_server']['tcp_enabled'] = true default['sql_server']['port'] = 1433 # Keep port for backward compatibility default['sql_server']['tcp_dynamic_ports'] = '' # Named Pipes settings default['sql_server']['np_enabled'] = false # Shared Memory settings default['sql_server']['sm_enabled'] = true # Via settings default['sql_server']['via_default_port'] = '0:1433' default['sql_server']['via_enabled'] = false default['sql_server']['via_listen_info'] = '0:1433'
chef-cookbooks/sql_server
attributes/configure.rb
Ruby
apache-2.0
1,226
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.serialization.record.util; import org.apache.nifi.serialization.SimpleRecordSchema; import org.apache.nifi.serialization.record.DataType; import org.apache.nifi.serialization.record.MapRecord; import org.apache.nifi.serialization.record.Record; import org.apache.nifi.serialization.record.RecordField; import org.apache.nifi.serialization.record.RecordFieldType; import org.apache.nifi.serialization.record.RecordSchema; import org.apache.nifi.serialization.record.type.ArrayDataType; import org.apache.nifi.serialization.record.type.ChoiceDataType; import org.apache.nifi.serialization.record.type.DecimalDataType; import org.apache.nifi.serialization.record.type.EnumDataType; import org.apache.nifi.serialization.record.type.MapDataType; import org.apache.nifi.serialization.record.type.RecordDataType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.TimeZone; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; public class DataTypeUtils { private static final Logger logger = LoggerFactory.getLogger(DataTypeUtils.class); // Regexes for parsing Floating-Point numbers private static final String OptionalSign = "[\\-\\+]?"; private static final String Infinity = "(Infinity)"; private static final String NotANumber = "(NaN)"; private static final String Base10Digits = "\\d+"; private static final String Base10Decimal = "\\." + Base10Digits; private static final String OptionalBase10Decimal = "(\\.\\d*)?"; private static final String Base10Exponent = "[eE]" + OptionalSign + Base10Digits; private static final String OptionalBase10Exponent = "(" + Base10Exponent + ")?"; private static final String doubleRegex = OptionalSign + "(" + Infinity + "|" + NotANumber + "|"+ "(" + Base10Digits + OptionalBase10Decimal + ")" + "|" + "(" + Base10Digits + OptionalBase10Decimal + Base10Exponent + ")" + "|" + "(" + Base10Decimal + OptionalBase10Exponent + ")" + ")"; private static final String decimalRegex = OptionalSign + "(" + Base10Digits + OptionalBase10Decimal + ")" + "|" + "(" + Base10Digits + OptionalBase10Decimal + Base10Exponent + ")" + "|" + "(" + Base10Decimal + OptionalBase10Exponent + ")"; private static final Pattern FLOATING_POINT_PATTERN = Pattern.compile(doubleRegex); private static final Pattern DECIMAL_PATTERN = Pattern.compile(decimalRegex); private static final TimeZone gmt = TimeZone.getTimeZone("gmt"); private static final Supplier<DateFormat> DEFAULT_DATE_FORMAT = () -> getDateFormat(RecordFieldType.DATE.getDefaultFormat()); private static final Supplier<DateFormat> DEFAULT_TIME_FORMAT = () -> getDateFormat(RecordFieldType.TIME.getDefaultFormat()); private static final Supplier<DateFormat> DEFAULT_TIMESTAMP_FORMAT = () -> getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat()); private static final int FLOAT_SIGNIFICAND_PRECISION = 24; // As specified in IEEE 754 binary32 private static final int DOUBLE_SIGNIFICAND_PRECISION = 53; // As specified in IEEE 754 binary64 private static final Long MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT = Double.valueOf(Math.pow(2, FLOAT_SIGNIFICAND_PRECISION)).longValue(); private static final Long MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT = -MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT; private static final Long MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE = Double.valueOf(Math.pow(2, DOUBLE_SIGNIFICAND_PRECISION)).longValue(); private static final Long MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE = -MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE; private static final BigInteger MAX_FLOAT_VALUE_IN_BIGINT = BigInteger.valueOf(MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT); private static final BigInteger MIN_FLOAT_VALUE_IN_BIGINT = BigInteger.valueOf(MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT); private static final BigInteger MAX_DOUBLE_VALUE_IN_BIGINT = BigInteger.valueOf(MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE); private static final BigInteger MIN_DOUBLE_VALUE_IN_BIGINT = BigInteger.valueOf(MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE); private static final double MAX_FLOAT_VALUE_IN_DOUBLE = Float.valueOf(Float.MAX_VALUE).doubleValue(); private static final double MIN_FLOAT_VALUE_IN_DOUBLE = -MAX_FLOAT_VALUE_IN_DOUBLE; private static final Map<RecordFieldType, Predicate<Object>> NUMERIC_VALIDATORS = new EnumMap<>(RecordFieldType.class); static { NUMERIC_VALIDATORS.put(RecordFieldType.BIGINT, value -> value instanceof BigInteger); NUMERIC_VALIDATORS.put(RecordFieldType.LONG, value -> value instanceof Long); NUMERIC_VALIDATORS.put(RecordFieldType.INT, value -> value instanceof Integer); NUMERIC_VALIDATORS.put(RecordFieldType.BYTE, value -> value instanceof Byte); NUMERIC_VALIDATORS.put(RecordFieldType.SHORT, value -> value instanceof Short); NUMERIC_VALIDATORS.put(RecordFieldType.DOUBLE, value -> value instanceof Double); NUMERIC_VALIDATORS.put(RecordFieldType.FLOAT, value -> value instanceof Float); NUMERIC_VALIDATORS.put(RecordFieldType.DECIMAL, value -> value instanceof BigDecimal); } public static Object convertType(final Object value, final DataType dataType, final String fieldName) { return convertType(value, dataType, fieldName, StandardCharsets.UTF_8); } public static Object convertType(final Object value, final DataType dataType, final String fieldName, final Charset charset) { return convertType(value, dataType, DEFAULT_DATE_FORMAT, DEFAULT_TIME_FORMAT, DEFAULT_TIMESTAMP_FORMAT, fieldName, charset); } public static DateFormat getDateFormat(final RecordFieldType fieldType, final Supplier<DateFormat> dateFormat, final Supplier<DateFormat> timeFormat, final Supplier<DateFormat> timestampFormat) { switch (fieldType) { case DATE: return dateFormat.get(); case TIME: return timeFormat.get(); case TIMESTAMP: return timestampFormat.get(); } return null; } public static Object convertType(final Object value, final DataType dataType, final Supplier<DateFormat> dateFormat, final Supplier<DateFormat> timeFormat, final Supplier<DateFormat> timestampFormat, final String fieldName) { return convertType(value, dataType, dateFormat, timeFormat, timestampFormat, fieldName, StandardCharsets.UTF_8); } public static Object convertType(final Object value, final DataType dataType, final Supplier<DateFormat> dateFormat, final Supplier<DateFormat> timeFormat, final Supplier<DateFormat> timestampFormat, final String fieldName, final Charset charset) { if (value == null) { return null; } switch (dataType.getFieldType()) { case BIGINT: return toBigInt(value, fieldName); case BOOLEAN: return toBoolean(value, fieldName); case BYTE: return toByte(value, fieldName); case CHAR: return toCharacter(value, fieldName); case DATE: return toDate(value, dateFormat, fieldName); case DECIMAL: return toBigDecimal(value, fieldName); case DOUBLE: return toDouble(value, fieldName); case FLOAT: return toFloat(value, fieldName); case INT: return toInteger(value, fieldName); case LONG: return toLong(value, fieldName); case SHORT: return toShort(value, fieldName); case ENUM: return toEnum(value, (EnumDataType) dataType, fieldName); case STRING: return toString(value, () -> getDateFormat(dataType.getFieldType(), dateFormat, timeFormat, timestampFormat), charset); case TIME: return toTime(value, timeFormat, fieldName); case TIMESTAMP: return toTimestamp(value, timestampFormat, fieldName); case ARRAY: return toArray(value, fieldName, ((ArrayDataType)dataType).getElementType(), charset); case MAP: return toMap(value, fieldName); case RECORD: final RecordDataType recordType = (RecordDataType) dataType; final RecordSchema childSchema = recordType.getChildSchema(); return toRecord(value, childSchema, fieldName, charset); case CHOICE: { final ChoiceDataType choiceDataType = (ChoiceDataType) dataType; final DataType chosenDataType = chooseDataType(value, choiceDataType); if (chosenDataType == null) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " for field " + fieldName + " to any of the following available Sub-Types for a Choice: " + choiceDataType.getPossibleSubTypes()); } return convertType(value, chosenDataType, fieldName, charset); } } return null; } public static boolean isCompatibleDataType(final Object value, final DataType dataType) { switch (dataType.getFieldType()) { case ARRAY: return isArrayTypeCompatible(value, ((ArrayDataType) dataType).getElementType()); case BIGINT: return isBigIntTypeCompatible(value); case BOOLEAN: return isBooleanTypeCompatible(value); case BYTE: return isByteTypeCompatible(value); case CHAR: return isCharacterTypeCompatible(value); case DATE: return isDateTypeCompatible(value, dataType.getFormat()); case DECIMAL: return isDecimalTypeCompatible(value); case DOUBLE: return isDoubleTypeCompatible(value); case FLOAT: return isFloatTypeCompatible(value); case INT: return isIntegerTypeCompatible(value); case LONG: return isLongTypeCompatible(value); case RECORD: { final RecordSchema schema = ((RecordDataType) dataType).getChildSchema(); return isRecordTypeCompatible(schema, value); } case SHORT: return isShortTypeCompatible(value); case TIME: return isTimeTypeCompatible(value, dataType.getFormat()); case TIMESTAMP: return isTimestampTypeCompatible(value, dataType.getFormat()); case STRING: return isStringTypeCompatible(value); case ENUM: return isEnumTypeCompatible(value, (EnumDataType) dataType); case MAP: return isMapTypeCompatible(value); case CHOICE: { final DataType chosenDataType = chooseDataType(value, (ChoiceDataType) dataType); return chosenDataType != null; } } return false; } public static DataType chooseDataType(final Object value, final ChoiceDataType choiceType) { Queue<DataType> possibleSubTypes = new LinkedList<>(choiceType.getPossibleSubTypes()); List<DataType> compatibleSimpleSubTypes = new ArrayList<>(); DataType subType; while ((subType = possibleSubTypes.poll()) != null) { if (subType instanceof ChoiceDataType) { possibleSubTypes.addAll(((ChoiceDataType) subType).getPossibleSubTypes()); } else { if (isCompatibleDataType(value, subType)) { compatibleSimpleSubTypes.add(subType); } } } int nrOfCompatibleSimpleSubTypes = compatibleSimpleSubTypes.size(); final DataType chosenSimpleType; if (nrOfCompatibleSimpleSubTypes == 0) { chosenSimpleType = null; } else if (nrOfCompatibleSimpleSubTypes == 1) { chosenSimpleType = compatibleSimpleSubTypes.get(0); } else { chosenSimpleType = findMostSuitableType(value, compatibleSimpleSubTypes, Function.identity()) .orElse(compatibleSimpleSubTypes.get(0)); } return chosenSimpleType; } public static <T> Optional<T> findMostSuitableType(Object value, List<T> types, Function<T, DataType> dataTypeMapper) { if (value instanceof String) { return findMostSuitableTypeByStringValue((String) value, types, dataTypeMapper); } else { DataType inferredDataType = inferDataType(value, null); if (inferredDataType != null && !inferredDataType.getFieldType().equals(RecordFieldType.STRING)) { for (T type : types) { if (inferredDataType.equals(dataTypeMapper.apply(type))) { return Optional.of(type); } } for (T type : types) { if (getWiderType(dataTypeMapper.apply(type), inferredDataType).isPresent()) { return Optional.of(type); } } } } return Optional.empty(); } public static <T> Optional<T> findMostSuitableTypeByStringValue(String valueAsString, List<T> types, Function<T, DataType> dataTypeMapper) { // Sorting based on the RecordFieldType enum ordering looks appropriate here as we want simpler types // first and the enum's ordering seems to reflect that Collections.sort(types, Comparator.comparing(type -> dataTypeMapper.apply(type).getFieldType())); for (T type : types) { try { if (isCompatibleDataType(valueAsString, dataTypeMapper.apply(type))) { return Optional.of(type); } } catch (Exception e) { logger.error("Exception thrown while checking if '" + valueAsString + "' is compatible with '" + type + "'", e); } } return Optional.empty(); } public static Record toRecord(final Object value, final RecordSchema recordSchema, final String fieldName) { return toRecord(value, recordSchema, fieldName, StandardCharsets.UTF_8); } public static Record toRecord(final Object value, final RecordSchema recordSchema, final String fieldName, final Charset charset) { if (value == null) { return null; } if (value instanceof Record) { return ((Record) value); } if (value instanceof Map) { if (recordSchema == null) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Record for field " + fieldName + " because the value is a Map but no Record Schema was provided"); } final Map<?, ?> map = (Map<?, ?>) value; final Map<String, Object> coercedValues = new LinkedHashMap<>(); for (final Map.Entry<?, ?> entry : map.entrySet()) { final Object keyValue = entry.getKey(); if (keyValue == null) { continue; } final String key = keyValue.toString(); final Optional<DataType> desiredTypeOption = recordSchema.getDataType(key); if (!desiredTypeOption.isPresent()) { continue; } final Object rawValue = entry.getValue(); final Object coercedValue = convertType(rawValue, desiredTypeOption.get(), fieldName, charset); coercedValues.put(key, coercedValue); } return new MapRecord(recordSchema, coercedValues); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Record for field " + fieldName); } public static Record toRecord(final Object value, final String fieldName) { return toRecord(value, fieldName, StandardCharsets.UTF_8); } public static RecordSchema inferSchema(final Map<String, Object> values, final String fieldName, final Charset charset) { if (values == null) { return null; } final List<RecordField> inferredFieldTypes = new ArrayList<>(); final Map<String, Object> coercedValues = new LinkedHashMap<>(); for (final Map.Entry<?, ?> entry : values.entrySet()) { final Object keyValue = entry.getKey(); if (keyValue == null) { continue; } final String key = keyValue.toString(); final Object rawValue = entry.getValue(); final DataType inferredDataType = inferDataType(rawValue, RecordFieldType.STRING.getDataType()); final RecordField recordField = new RecordField(key, inferredDataType, true); inferredFieldTypes.add(recordField); final Object coercedValue = convertType(rawValue, inferredDataType, fieldName, charset); coercedValues.put(key, coercedValue); } final RecordSchema inferredSchema = new SimpleRecordSchema(inferredFieldTypes); return inferredSchema; } public static Record toRecord(final Object value, final String fieldName, final Charset charset) { if (value == null) { return null; } if (value instanceof Record) { return ((Record) value); } final List<RecordField> inferredFieldTypes = new ArrayList<>(); if (value instanceof Map) { final Map<?, ?> map = (Map<?, ?>) value; final Map<String, Object> coercedValues = new LinkedHashMap<>(); for (final Map.Entry<?, ?> entry : map.entrySet()) { final Object keyValue = entry.getKey(); if (keyValue == null) { continue; } final String key = keyValue.toString(); final Object rawValue = entry.getValue(); final DataType inferredDataType = inferDataType(rawValue, RecordFieldType.STRING.getDataType()); final RecordField recordField = new RecordField(key, inferredDataType, true); inferredFieldTypes.add(recordField); final Object coercedValue = convertType(rawValue, inferredDataType, fieldName, charset); coercedValues.put(key, coercedValue); } final RecordSchema inferredSchema = new SimpleRecordSchema(inferredFieldTypes); return new MapRecord(inferredSchema, coercedValues); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Record for field " + fieldName); } public static DataType inferDataType(final Object value, final DataType defaultType) { if (value == null) { return defaultType; } if (value instanceof String) { return RecordFieldType.STRING.getDataType(); } if (value instanceof Record) { final RecordSchema schema = ((Record) value).getSchema(); return RecordFieldType.RECORD.getRecordDataType(schema); } if (value instanceof Number) { if (value instanceof Long) { return RecordFieldType.LONG.getDataType(); } if (value instanceof Integer) { return RecordFieldType.INT.getDataType(); } if (value instanceof Short) { return RecordFieldType.SHORT.getDataType(); } if (value instanceof Byte) { return RecordFieldType.BYTE.getDataType(); } if (value instanceof Float) { return RecordFieldType.FLOAT.getDataType(); } if (value instanceof Double) { return RecordFieldType.DOUBLE.getDataType(); } if (value instanceof BigInteger) { return RecordFieldType.BIGINT.getDataType(); } if (value instanceof BigDecimal) { final BigDecimal bigDecimal = (BigDecimal) value; return RecordFieldType.DECIMAL.getDecimalDataType(bigDecimal.precision(), bigDecimal.scale()); } } if (value instanceof Boolean) { return RecordFieldType.BOOLEAN.getDataType(); } if (value instanceof java.sql.Time) { return RecordFieldType.TIME.getDataType(); } if (value instanceof java.sql.Timestamp) { return RecordFieldType.TIMESTAMP.getDataType(); } if (value instanceof java.util.Date) { return RecordFieldType.DATE.getDataType(); } if (value instanceof Character) { return RecordFieldType.CHAR.getDataType(); } // A value of a Map could be either a Record or a Map type. In either case, it must have Strings as keys. if (value instanceof Map) { final Map<String, Object> map; // Only transform the map if the keys aren't strings boolean allStrings = true; for (final Object key : ((Map<?, ?>) value).keySet()) { if (!(key instanceof String)) { allStrings = false; break; } } if (allStrings) { map = (Map<String, Object>) value; } else { final Map<?, ?> m = (Map<?, ?>) value; map = new HashMap<>(m.size()); m.forEach((k, v) -> map.put(k == null ? null : k.toString(), v)); } return inferRecordDataType(map); // // Check if all types are the same. // if (map.isEmpty()) { // return RecordFieldType.MAP.getMapDataType(RecordFieldType.STRING.getDataType()); // } // // Object valueFromMap = null; // Class<?> valueClass = null; // for (final Object val : map.values()) { // if (val == null) { // continue; // } // // valueFromMap = val; // final Class<?> currentValClass = val.getClass(); // if (valueClass == null) { // valueClass = currentValClass; // } else { // // If we have two elements that are of different types, then we cannot have a Map. Must be a Record. // if (valueClass != currentValClass) { // return inferRecordDataType(map); // } // } // } // // // All values appear to be of the same type, so assume that it's a map. // final DataType elementDataType = inferDataType(valueFromMap, RecordFieldType.STRING.getDataType()); // return RecordFieldType.MAP.getMapDataType(elementDataType); } if (value.getClass().isArray()) { DataType mergedDataType = null; int length = Array.getLength(value); for(int index = 0; index < length; index++) { final DataType inferredDataType = inferDataType(Array.get(value, index), RecordFieldType.STRING.getDataType()); mergedDataType = mergeDataTypes(mergedDataType, inferredDataType); } if (mergedDataType == null) { mergedDataType = RecordFieldType.STRING.getDataType(); } return RecordFieldType.ARRAY.getArrayDataType(mergedDataType); } if (value instanceof Iterable) { final Iterable iterable = (Iterable<?>) value; DataType mergedDataType = null; for (final Object arrayValue : iterable) { final DataType inferredDataType = inferDataType(arrayValue, RecordFieldType.STRING.getDataType()); mergedDataType = mergeDataTypes(mergedDataType, inferredDataType); } if (mergedDataType == null) { mergedDataType = RecordFieldType.STRING.getDataType(); } return RecordFieldType.ARRAY.getArrayDataType(mergedDataType); } return defaultType; } private static DataType inferRecordDataType(final Map<String, ?> map) { final List<RecordField> fields = new ArrayList<>(map.size()); for (final Map.Entry<String, ?> entry : map.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); final DataType dataType = inferDataType(value, RecordFieldType.STRING.getDataType()); final RecordField field = new RecordField(key, dataType, true); fields.add(field); } final RecordSchema schema = new SimpleRecordSchema(fields); return RecordFieldType.RECORD.getRecordDataType(schema); } /** * Check if the given record structured object compatible with the schema. * @param schema record schema, schema validation will not be performed if schema is null * @param value the record structured object, i.e. Record or Map * @return True if the object is compatible with the schema */ private static boolean isRecordTypeCompatible(RecordSchema schema, Object value) { if (value == null) { return false; } if (!(value instanceof Record) && !(value instanceof Map)) { return false; } if (schema == null) { return true; } for (final RecordField childField : schema.getFields()) { final Object childValue; if (value instanceof Record) { childValue = ((Record) value).getValue(childField); } else { childValue = ((Map) value).get(childField.getFieldName()); } if (childValue == null && !childField.isNullable()) { logger.debug("Value is not compatible with schema because field {} has a null value, which is not allowed in the schema", childField.getFieldName()); return false; } if (childValue == null) { continue; // consider compatible } if (!isCompatibleDataType(childValue, childField.getDataType())) { return false; } } return true; } public static Object[] toArray(final Object value, final String fieldName, final DataType elementDataType) { return toArray(value, fieldName, elementDataType, StandardCharsets.UTF_8); } public static Object[] toArray(final Object value, final String fieldName, final DataType elementDataType, final Charset charset) { if (value == null) { return null; } if (value instanceof Object[]) { return (Object[]) value; } if (value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType)) { byte[] src = ((String) value).getBytes(charset); Byte[] dest = new Byte[src.length]; for (int i = 0; i < src.length; i++) { dest[i] = src[i]; } return dest; } if (value instanceof byte[]) { byte[] src = (byte[]) value; Byte[] dest = new Byte[src.length]; for (int i = 0; i < src.length; i++) { dest[i] = src[i]; } return dest; } if (value instanceof List) { final List<?> list = (List<?>)value; return list.toArray(); } try { if (value instanceof Blob) { Blob blob = (Blob) value; long rawBlobLength = blob.length(); if(rawBlobLength > Integer.MAX_VALUE) { throw new IllegalTypeConversionException("Value of type " + value.getClass() + " too large to convert to Object Array for field " + fieldName); } int blobLength = (int) rawBlobLength; byte[] src = blob.getBytes(1, blobLength); Byte[] dest = new Byte[blobLength]; for (int i = 0; i < src.length; i++) { dest[i] = src[i]; } return dest; } else { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Object Array for field " + fieldName); } } catch (IllegalTypeConversionException itce) { throw itce; } catch (Exception e) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Object Array for field " + fieldName, e); } } public static boolean isArrayTypeCompatible(final Object value, final DataType elementDataType) { if (value == null) { return false; } // Either an object array (check the element type) or a String to be converted to byte[] if (value instanceof Object[]) { for (Object o : ((Object[]) value)) { // Check each element to ensure its type is the same or can be coerced (if need be) if (!isCompatibleDataType(o, elementDataType)) { return false; } } return true; } else { return value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType); } } @SuppressWarnings("unchecked") public static Map<String, Object> toMap(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Map) { final Map<?, ?> original = (Map<?, ?>) value; boolean keysAreStrings = true; for (final Object key : original.keySet()) { if (!(key instanceof String)) { keysAreStrings = false; } } if (keysAreStrings) { return (Map<String, Object>) value; } final Map<String, Object> transformed = new LinkedHashMap<>(); for (final Map.Entry<?, ?> entry : original.entrySet()) { final Object key = entry.getKey(); if (key == null) { transformed.put(null, entry.getValue()); } else { transformed.put(key.toString(), entry.getValue()); } } return transformed; } if (value instanceof Record) { final Record record = (Record) value; final RecordSchema recordSchema = record.getSchema(); if (recordSchema == null) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type Record to Map for field " + fieldName + " because Record does not have an associated Schema"); } final Map<String, Object> map = new LinkedHashMap<>(); for (final String recordFieldName : recordSchema.getFieldNames()) { map.put(recordFieldName, record.getValue(recordFieldName)); } return map; } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Map for field " + fieldName); } /** * Creates a native Java object from a given object of a specified type. Non-scalar (complex, nested, etc.) data types are processed iteratively/recursively, such that all * included objects are native Java objects, rather than Record API objects or implementation-specific objects. * @param value The object to be converted * @param dataType The type of the provided object * @return An object representing a native Java conversion of the given input object */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Object convertRecordFieldtoObject(final Object value, final DataType dataType) { if (value == null) { return null; } if (value instanceof Record) { Record record = (Record) value; RecordSchema recordSchema = record.getSchema(); if (recordSchema == null) { throw new IllegalTypeConversionException("Cannot convert value of type Record to Map because Record does not have an associated Schema"); } final Map<String, Object> recordMap = new LinkedHashMap<>(); for (RecordField field : recordSchema.getFields()) { final DataType fieldDataType = field.getDataType(); final String fieldName = field.getFieldName(); Object fieldValue = record.getValue(fieldName); if (fieldValue == null) { recordMap.put(fieldName, null); } else if (isScalarValue(fieldDataType, fieldValue)) { recordMap.put(fieldName, fieldValue); } else if (fieldDataType instanceof RecordDataType) { Record nestedRecord = (Record) fieldValue; recordMap.put(fieldName, convertRecordFieldtoObject(nestedRecord, fieldDataType)); } else if (fieldDataType instanceof MapDataType) { recordMap.put(fieldName, convertRecordMapToJavaMap((Map) fieldValue, ((MapDataType)fieldDataType).getValueType())); } else if (fieldDataType instanceof ArrayDataType) { recordMap.put(fieldName, convertRecordArrayToJavaArray((Object[])fieldValue, ((ArrayDataType) fieldDataType).getElementType())); } else { throw new IllegalTypeConversionException("Cannot convert value [" + fieldValue + "] of type " + fieldDataType.toString() + " to Map for field " + fieldName + " because the type is not supported"); } } return recordMap; } else if (value instanceof Map) { return convertRecordMapToJavaMap((Map) value, ((MapDataType) dataType).getValueType()); } else if (dataType != null && isScalarValue(dataType, value)) { return value; } else if (value instanceof Object[] && dataType instanceof ArrayDataType) { // This is likely a Map whose values are represented as an array. Return a new array with each element converted to a Java object return convertRecordArrayToJavaArray((Object[]) value, ((ArrayDataType) dataType).getElementType()); } throw new IllegalTypeConversionException("Cannot convert value of class " + value.getClass().getName() + " because the type is not supported"); } public static Map<String, Object> convertRecordMapToJavaMap(final Map<String, Object> map, DataType valueDataType) { if (map == null) { return null; } Map<String, Object> resultMap = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : map.entrySet()) { resultMap.put(entry.getKey(), convertRecordFieldtoObject(entry.getValue(), valueDataType)); } return resultMap; } public static Object[] convertRecordArrayToJavaArray(final Object[] array, DataType elementDataType) { if (array == null || array.length == 0 || isScalarValue(elementDataType, array[0])) { return array; } else { // Must be an array of complex types, build an array of converted values Object[] resultArray = new Object[array.length]; for (int i = 0; i < array.length; i++) { resultArray[i] = convertRecordFieldtoObject(array[i], elementDataType); } return resultArray; } } public static boolean isMapTypeCompatible(final Object value) { return value != null && (value instanceof Map || value instanceof MapRecord); } public static String toString(final Object value, final Supplier<DateFormat> format) { return toString(value, format, StandardCharsets.UTF_8); } public static String toString(final Object value, final Supplier<DateFormat> format, final Charset charset) { if (value == null) { return null; } if (value instanceof String) { return (String) value; } if (format == null && value instanceof java.util.Date) { return String.valueOf(((java.util.Date) value).getTime()); } if (value instanceof java.util.Date) { return formatDate((java.util.Date) value, format); } if (value instanceof byte[]) { return new String((byte[])value, charset); } if (value instanceof Byte[]) { Byte[] src = (Byte[]) value; byte[] dest = new byte[src.length]; for(int i=0;i<src.length;i++) { dest[i] = src[i]; } return new String(dest, charset); } if (value instanceof Object[]) { Object[] o = (Object[]) value; if (o.length > 0) { byte[] dest = new byte[o.length]; for (int i = 0; i < o.length; i++) { dest[i] = (byte) o[i]; } return new String(dest, charset); } else { return ""; // Empty array = empty string } } if (value instanceof Clob) { Clob clob = (Clob) value; StringBuilder sb = new StringBuilder(); char[] buffer = new char[32 * 1024]; // 32K default buffer try (Reader reader = clob.getCharacterStream()) { int charsRead; while ((charsRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, charsRead); } return sb.toString(); } catch (Exception e) { throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e); } } return value.toString(); } private static String formatDate(final java.util.Date date, final Supplier<DateFormat> formatSupplier) { final DateFormat dateFormat = formatSupplier.get(); if (dateFormat == null) { return String.valueOf((date).getTime()); } return dateFormat.format(date); } public static String toString(final Object value, final String format) { return toString(value, format, StandardCharsets.UTF_8); } public static String toString(final Object value, final String format, final Charset charset) { if (value == null) { return null; } if (value instanceof String) { return (String) value; } if (format == null && value instanceof java.util.Date) { return String.valueOf(((java.util.Date) value).getTime()); } if (value instanceof java.sql.Date) { return getDateFormat(format).format((java.util.Date) value); } if (value instanceof java.sql.Time) { return getDateFormat(format).format((java.util.Date) value); } if (value instanceof java.sql.Timestamp) { return getDateFormat(format).format((java.util.Date) value); } if (value instanceof java.util.Date) { return getDateFormat(format).format((java.util.Date) value); } if (value instanceof Blob) { Blob blob = (Blob) value; StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[32 * 1024]; // 32K default buffer try (InputStream inStream = blob.getBinaryStream()) { int bytesRead; while ((bytesRead = inStream.read(buffer)) != -1) { sb.append(new String(buffer, charset), 0, bytesRead); } return sb.toString(); } catch (Exception e) { throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e); } } if (value instanceof Clob) { Clob clob = (Clob) value; StringBuilder sb = new StringBuilder(); char[] buffer = new char[32 * 1024]; // 32K default buffer try (Reader reader = clob.getCharacterStream()) { int charsRead; while ((charsRead = reader.read(buffer)) != -1) { sb.append(buffer, 0, charsRead); } return sb.toString(); } catch (Exception e) { throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e); } } if (value instanceof Object[]) { return Arrays.toString((Object[]) value); } if (value instanceof byte[]) { return new String((byte[]) value, charset); } return value.toString(); } public static boolean isStringTypeCompatible(final Object value) { return value != null; } public static boolean isEnumTypeCompatible(final Object value, final EnumDataType enumType) { return enumType.getEnums() != null && enumType.getEnums().contains(value); } private static Object toEnum(Object value, EnumDataType dataType, String fieldName) { if(dataType.getEnums() != null && dataType.getEnums().contains(value)) { return value.toString(); } throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + dataType.toString() + " for field " + fieldName); } public static java.sql.Date toDate(final Object value, final Supplier<DateFormat> format, final String fieldName) { if (value == null) { return null; } if (value instanceof Date) { return (Date) value; } if (value instanceof java.util.Date) { java.util.Date _temp = (java.util.Date)value; return new Date(_temp.getTime()); } if (value instanceof Number) { final long longValue = ((Number) value).longValue(); return new Date(longValue); } if (value instanceof String) { try { final String string = ((String) value).trim(); if (string.isEmpty()) { return null; } if (format == null) { return new Date(Long.parseLong(string)); } final DateFormat dateFormat = format.get(); if (dateFormat == null) { return new Date(Long.parseLong(string)); } final java.util.Date utilDate = dateFormat.parse(string); return new Date(utilDate.getTime()); } catch (final ParseException | NumberFormatException e) { throw new IllegalTypeConversionException("Could not convert value [" + value + "] of type java.lang.String to Date because the value is not in the expected date format: " + format + " for field " + fieldName); } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Date for field " + fieldName); } public static boolean isDateTypeCompatible(final Object value, final String format) { if (value == null) { return false; } if (value instanceof java.util.Date || value instanceof Number) { return true; } if (value instanceof String) { if (format == null) { return isInteger((String) value); } try { getDateFormat(format).parse((String) value); return true; } catch (final ParseException e) { return false; } } return false; } private static boolean isInteger(final String value) { if (value == null || value.isEmpty()) { return false; } for (int i = 0; i < value.length(); i++) { if (!Character.isDigit(value.charAt(i))) { return false; } } return true; } public static Time toTime(final Object value, final Supplier<DateFormat> format, final String fieldName) { if (value == null) { return null; } if (value instanceof Time) { return (Time) value; } if (value instanceof Number) { final long longValue = ((Number) value).longValue(); return new Time(longValue); } if (value instanceof String) { try { final String string = ((String) value).trim(); if (string.isEmpty()) { return null; } if (format == null) { return new Time(Long.parseLong(string)); } final DateFormat dateFormat = format.get(); if (dateFormat == null) { return new Time(Long.parseLong(string)); } final java.util.Date utilDate = dateFormat.parse(string); return new Time(utilDate.getTime()); } catch (final ParseException e) { throw new IllegalTypeConversionException("Could not convert value [" + value + "] of type java.lang.String to Time for field " + fieldName + " because the value is not in the expected date format: " + format); } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Time for field " + fieldName); } public static DateFormat getDateFormat(final String format) { if (format == null) { return null; } final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(gmt); return df; } public static DateFormat getDateFormat(final String format, final String timezoneID) { if (format == null || timezoneID == null) { return null; } final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(TimeZone.getTimeZone(timezoneID)); return df; } public static boolean isTimeTypeCompatible(final Object value, final String format) { return isDateTypeCompatible(value, format); } public static Timestamp toTimestamp(final Object value, final Supplier<DateFormat> format, final String fieldName) { if (value == null) { return null; } if (value instanceof Timestamp) { return (Timestamp) value; } if (value instanceof java.util.Date) { return new Timestamp(((java.util.Date)value).getTime()); } if (value instanceof Number) { final long longValue = ((Number) value).longValue(); return new Timestamp(longValue); } if (value instanceof String) { final String string = ((String) value).trim(); if (string.isEmpty()) { return null; } try { if (format == null) { return new Timestamp(Long.parseLong(string)); } final DateFormat dateFormat = format.get(); if (dateFormat == null) { return new Timestamp(Long.parseLong(string)); } final java.util.Date utilDate = dateFormat.parse(string); return new Timestamp(utilDate.getTime()); } catch (final ParseException e) { final DateFormat dateFormat = format.get(); final String formatDescription; if (dateFormat == null) { formatDescription = "Numeric"; } else if (dateFormat instanceof SimpleDateFormat) { formatDescription = ((SimpleDateFormat) dateFormat).toPattern(); } else { formatDescription = dateFormat.toString(); } throw new IllegalTypeConversionException("Could not convert value [" + value + "] of type java.lang.String to Timestamp for field " + fieldName + " because the value is not in the expected date format: " + formatDescription); } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Timestamp for field " + fieldName); } public static boolean isTimestampTypeCompatible(final Object value, final String format) { return isDateTypeCompatible(value, format); } public static BigInteger toBigInt(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof BigInteger) { return (BigInteger) value; } if (value instanceof Number) { return BigInteger.valueOf(((Number) value).longValue()); } if (value instanceof String) { try { return new BigInteger((String) value); } catch (NumberFormatException nfe) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigInteger for field " + fieldName + ", value is not a valid representation of BigInteger", nfe); } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigInteger for field " + fieldName); } public static boolean isBigIntTypeCompatible(final Object value) { return isNumberTypeCompatible(value, DataTypeUtils::isIntegral); } public static boolean isDecimalTypeCompatible(final Object value) { return isNumberTypeCompatible(value, DataTypeUtils::isDecimal); } public static Boolean toBoolean(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Boolean) { return (Boolean) value; } if (value instanceof String) { final String string = (String) value; if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } else if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Boolean for field " + fieldName); } public static boolean isBooleanTypeCompatible(final Object value) { if (value == null) { return false; } if (value instanceof Boolean) { return true; } if (value instanceof String) { final String string = (String) value; return string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false"); } return false; } public static BigDecimal toBigDecimal(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof BigDecimal) { return (BigDecimal) value; } if (value instanceof Number) { final Number number = (Number) value; if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) { return BigDecimal.valueOf(number.longValue()); } if (number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } if (number instanceof Float) { return new BigDecimal(Float.toString((Float) number)); } if (number instanceof Double) { return new BigDecimal(Double.toString((Double) number)); } } if (value instanceof String) { try { return new BigDecimal((String) value); } catch (NumberFormatException nfe) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigDecimal for field " + fieldName + ", value is not a valid representation of BigDecimal", nfe); } } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigDecimal for field " + fieldName); } public static Double toDouble(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).doubleValue(); } if (value instanceof String) { return Double.parseDouble((String) value); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Double for field " + fieldName); } public static boolean isDoubleTypeCompatible(final Object value) { return isNumberTypeCompatible(value, s -> isDouble(s)); } private static boolean isNumberTypeCompatible(final Object value, final Predicate<String> stringPredicate) { if (value == null) { return false; } if (value instanceof Number) { return true; } if (value instanceof String) { return stringPredicate.test((String) value); } return false; } public static Float toFloat(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).floatValue(); } if (value instanceof String) { return Float.parseFloat((String) value); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Float for field " + fieldName); } public static boolean isFloatTypeCompatible(final Object value) { return isNumberTypeCompatible(value, s -> isFloatingPoint(s)); } private static boolean isDecimal(final String value) { if (value == null || value.isEmpty()) { return false; } return DECIMAL_PATTERN.matcher(value).matches(); } private static boolean isFloatingPoint(final String value) { if (value == null || value.isEmpty()) { return false; } if (!FLOATING_POINT_PATTERN.matcher(value).matches()) { return false; } // Just to ensure that the exponents are in range, etc. try { Float.parseFloat(value); } catch (final NumberFormatException nfe) { return false; } return true; } private static boolean isDouble(final String value) { if (value == null || value.isEmpty()) { return false; } if (!FLOATING_POINT_PATTERN.matcher(value).matches()) { return false; } // Just to ensure that the exponents are in range, etc. try { Double.parseDouble(value); } catch (final NumberFormatException nfe) { return false; } return true; } public static Long toLong(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof String) { return Long.parseLong((String) value); } if (value instanceof java.util.Date) { return ((java.util.Date) value).getTime(); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Long for field " + fieldName); } public static boolean isLongTypeCompatible(final Object value) { if (value == null) { return false; } if (value instanceof Number) { return true; } if (value instanceof java.util.Date) { return true; } if (value instanceof String) { return isIntegral((String) value, Long.MIN_VALUE, Long.MAX_VALUE); } return false; } /** * Check if the value is an integral. */ private static boolean isIntegral(final String value) { if (value == null || value.isEmpty()) { return false; } int initialPosition = 0; final char firstChar = value.charAt(0); if (firstChar == '+' || firstChar == '-') { initialPosition = 1; if (value.length() == 1) { return false; } } for (int i = initialPosition; i < value.length(); i++) { if (!Character.isDigit(value.charAt(i))) { return false; } } return true; } /** * Check if the value is an integral within a value range. */ private static boolean isIntegral(final String value, final long minValue, final long maxValue) { if (!isIntegral(value)) { return false; } try { final long longValue = Long.parseLong(value); return longValue >= minValue && longValue <= maxValue; } catch (final NumberFormatException nfe) { // In case the value actually exceeds the max value of a Long return false; } } public static Integer toInteger(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { try { return Math.toIntExact(((Number) value).longValue()); } catch (ArithmeticException ae) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Integer for field " + fieldName + " as it causes an arithmetic overflow (the value is too large, e.g.)", ae); } } if (value instanceof String) { return Integer.parseInt((String) value); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Integer for field " + fieldName); } public static boolean isIntegerTypeCompatible(final Object value) { return isNumberTypeCompatible(value, s -> isIntegral(s, Integer.MIN_VALUE, Integer.MAX_VALUE)); } public static Short toShort(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).shortValue(); } if (value instanceof String) { return Short.parseShort((String) value); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Short for field " + fieldName); } public static boolean isShortTypeCompatible(final Object value) { return isNumberTypeCompatible(value, s -> isIntegral(s, Short.MIN_VALUE, Short.MAX_VALUE)); } public static Byte toByte(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).byteValue(); } if (value instanceof String) { return Byte.parseByte((String) value); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Byte for field " + fieldName); } public static boolean isByteTypeCompatible(final Object value) { return isNumberTypeCompatible(value, s -> isIntegral(s, Byte.MIN_VALUE, Byte.MAX_VALUE)); } public static Character toCharacter(final Object value, final String fieldName) { if (value == null) { return null; } if (value instanceof Character) { return ((Character) value); } if (value instanceof CharSequence) { final CharSequence charSeq = (CharSequence) value; if (charSeq.length() == 0) { throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Character because it has a length of 0 for field " + fieldName); } return charSeq.charAt(0); } throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Character for field " + fieldName); } public static boolean isCharacterTypeCompatible(final Object value) { return value != null && (value instanceof Character || (value instanceof CharSequence && ((CharSequence) value).length() > 0)); } public static RecordSchema merge(final RecordSchema thisSchema, final RecordSchema otherSchema) { if (thisSchema == null) { return otherSchema; } if (otherSchema == null) { return thisSchema; } if (thisSchema == otherSchema) { return thisSchema; } final List<RecordField> otherFields = otherSchema.getFields(); if (otherFields.isEmpty()) { return thisSchema; } final List<RecordField> thisFields = thisSchema.getFields(); if (thisFields.isEmpty()) { return otherSchema; } final Map<String, Integer> fieldIndices = new HashMap<>(); final List<RecordField> fields = new ArrayList<>(); for (int i = 0; i < thisFields.size(); i++) { final RecordField field = thisFields.get(i); final Integer index = Integer.valueOf(i); fieldIndices.put(field.getFieldName(), index); for (final String alias : field.getAliases()) { fieldIndices.put(alias, index); } fields.add(field); } for (final RecordField otherField : otherFields) { Integer fieldIndex = fieldIndices.get(otherField.getFieldName()); // Find the field in 'thisSchema' that corresponds to 'otherField', // if one exists. if (fieldIndex == null) { for (final String alias : otherField.getAliases()) { fieldIndex = fieldIndices.get(alias); if (fieldIndex != null) { break; } } } // If there is no field with the same name then just add 'otherField'. if (fieldIndex == null) { fields.add(otherField); continue; } // Merge the two fields, if necessary final RecordField thisField = fields.get(fieldIndex); if (isMergeRequired(thisField, otherField)) { final RecordField mergedField = merge(thisField, otherField); fields.set(fieldIndex, mergedField); } } return new SimpleRecordSchema(fields); } private static boolean isMergeRequired(final RecordField thisField, final RecordField otherField) { if (!thisField.getDataType().equals(otherField.getDataType())) { return true; } if (!thisField.getAliases().equals(otherField.getAliases())) { return true; } if (!Objects.equals(thisField.getDefaultValue(), otherField.getDefaultValue())) { return true; } return false; } public static RecordField merge(final RecordField thisField, final RecordField otherField) { final String fieldName = thisField.getFieldName(); final Set<String> aliases = new HashSet<>(); aliases.addAll(thisField.getAliases()); aliases.addAll(otherField.getAliases()); final Object defaultValue; if (thisField.getDefaultValue() == null && otherField.getDefaultValue() != null) { defaultValue = otherField.getDefaultValue(); } else { defaultValue = thisField.getDefaultValue(); } final DataType dataType = mergeDataTypes(thisField.getDataType(), otherField.getDataType()); return new RecordField(fieldName, dataType, defaultValue, aliases, thisField.isNullable() || otherField.isNullable()); } public static DataType mergeDataTypes(final DataType thisDataType, final DataType otherDataType) { if (thisDataType == null) { return otherDataType; } if (otherDataType == null) { return thisDataType; } if (thisDataType.equals(otherDataType)) { return thisDataType; } else { // If one type is 'wider' than the other (such as an INT and a LONG), just use the wider type (LONG, in this case), // rather than using a CHOICE of the two. final Optional<DataType> widerType = getWiderType(thisDataType, otherDataType); if (widerType.isPresent()) { return widerType.get(); } final Set<DataType> possibleTypes = new LinkedHashSet<>(); if (thisDataType.getFieldType() == RecordFieldType.CHOICE) { possibleTypes.addAll(((ChoiceDataType) thisDataType).getPossibleSubTypes()); } else { possibleTypes.add(thisDataType); } if (otherDataType.getFieldType() == RecordFieldType.CHOICE) { possibleTypes.addAll(((ChoiceDataType) otherDataType).getPossibleSubTypes()); } else { possibleTypes.add(otherDataType); } ArrayList<DataType> possibleChildTypes = new ArrayList<>(possibleTypes); Collections.sort(possibleChildTypes, Comparator.comparing(DataType::getFieldType)); return RecordFieldType.CHOICE.getChoiceDataType(possibleChildTypes); } } public static Optional<DataType> getWiderType(final DataType thisDataType, final DataType otherDataType) { final RecordFieldType thisFieldType = thisDataType.getFieldType(); final RecordFieldType otherFieldType = otherDataType.getFieldType(); final int thisIntTypeValue = getIntegerTypeValue(thisFieldType); final int otherIntTypeValue = getIntegerTypeValue(otherFieldType); if (thisIntTypeValue > -1 && otherIntTypeValue > -1) { if (thisIntTypeValue > otherIntTypeValue) { return Optional.of(thisDataType); } return Optional.of(otherDataType); } switch (thisFieldType) { case FLOAT: if (otherFieldType == RecordFieldType.DOUBLE) { return Optional.of(otherDataType); } else if (otherFieldType == RecordFieldType.DECIMAL) { return Optional.of(otherDataType); } break; case DOUBLE: if (otherFieldType == RecordFieldType.FLOAT) { return Optional.of(thisDataType); } else if (otherFieldType == RecordFieldType.DECIMAL) { return Optional.of(otherDataType); } break; case DECIMAL: if (otherFieldType == RecordFieldType.DOUBLE) { return Optional.of(thisDataType); } else if (otherFieldType == RecordFieldType.FLOAT) { return Optional.of(thisDataType); } else if (otherFieldType == RecordFieldType.DECIMAL) { final DecimalDataType thisDecimalDataType = (DecimalDataType) thisDataType; final DecimalDataType otherDecimalDataType = (DecimalDataType) otherDataType; final int precision = Math.max(thisDecimalDataType.getPrecision(), otherDecimalDataType.getPrecision()); final int scale = Math.max(thisDecimalDataType.getScale(), otherDecimalDataType.getScale()); return Optional.of(RecordFieldType.DECIMAL.getDecimalDataType(precision, scale)); } break; case CHAR: if (otherFieldType == RecordFieldType.STRING) { return Optional.of(otherDataType); } break; case STRING: if (otherFieldType == RecordFieldType.CHAR) { return Optional.of(thisDataType); } break; } return Optional.empty(); } private static int getIntegerTypeValue(final RecordFieldType fieldType) { switch (fieldType) { case BIGINT: return 4; case LONG: return 3; case INT: return 2; case SHORT: return 1; case BYTE: return 0; default: return -1; } } /** * Converts the specified field data type into a java.sql.Types constant (INTEGER = 4, e.g.) * * @param dataType the DataType to be converted * @return the SQL type corresponding to the specified RecordFieldType */ public static int getSQLTypeValue(final DataType dataType) { if (dataType == null) { return Types.NULL; } RecordFieldType fieldType = dataType.getFieldType(); switch (fieldType) { case BIGINT: case LONG: return Types.BIGINT; case BOOLEAN: return Types.BOOLEAN; case BYTE: return Types.TINYINT; case CHAR: return Types.CHAR; case DATE: return Types.DATE; case DOUBLE: return Types.DOUBLE; case FLOAT: return Types.FLOAT; case DECIMAL: return Types.NUMERIC; case INT: return Types.INTEGER; case SHORT: return Types.SMALLINT; case STRING: return Types.VARCHAR; case TIME: return Types.TIME; case TIMESTAMP: return Types.TIMESTAMP; case ARRAY: return Types.ARRAY; case MAP: case RECORD: return Types.STRUCT; case CHOICE: throw new IllegalTypeConversionException("Cannot convert CHOICE, type must be explicit"); default: throw new IllegalTypeConversionException("Cannot convert unknown type " + fieldType.name()); } } public static boolean isScalarValue(final DataType dataType, final Object value) { final RecordFieldType fieldType = dataType.getFieldType(); final RecordFieldType chosenType; if (fieldType == RecordFieldType.CHOICE) { final ChoiceDataType choiceDataType = (ChoiceDataType) dataType; final DataType chosenDataType = chooseDataType(value, choiceDataType); if (chosenDataType == null) { return false; } chosenType = chosenDataType.getFieldType(); } else { chosenType = fieldType; } switch (chosenType) { case ARRAY: case MAP: case RECORD: return false; } return true; } public static Charset getCharset(String charsetName) { if(charsetName == null) { return StandardCharsets.UTF_8; } else { return Charset.forName(charsetName); } } /** * Returns true if the given value is an integer value and fits into a float variable without precision loss. This is * decided based on the numerical value of the input and the significant bytes used in the float. * * @param value The value to check. * * @return True in case of the value meets the conditions, false otherwise. */ public static boolean isIntegerFitsToFloat(final Object value) { if (!(value instanceof Integer)) { return false; } final int intValue = (Integer) value; return MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT <= intValue && intValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT; } /** * Returns true if the given value is a long value and fits into a float variable without precision loss. This is * decided based on the numerical value of the input and the significant bytes used in the float. * * @param value The value to check. * * @return True in case of the value meets the conditions, false otherwise. */ public static boolean isLongFitsToFloat(final Object value) { if (!(value instanceof Long)) { return false; } final long longValue = (Long) value; return MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT <= longValue && longValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT; } /** * Returns true if the given value is a long value and fits into a double variable without precision loss. This is * decided based on the numerical value of the input and the significant bytes used in the double. * * @param value The value to check. * * @return True in case of the value meets the conditions, false otherwise. */ public static boolean isLongFitsToDouble(final Object value) { if (!(value instanceof Long)) { return false; } final long longValue = (Long) value; return MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE <= longValue && longValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE; } /** * Returns true if the given value is a BigInteger value and fits into a float variable without precision loss. This is * decided based on the numerical value of the input and the significant bytes used in the float. * * @param value The value to check. * * @return True in case of the value meets the conditions, false otherwise. */ public static boolean isBigIntFitsToFloat(final Object value) { if (!(value instanceof BigInteger)) { return false; } final BigInteger bigIntValue = (BigInteger) value; return bigIntValue.compareTo(MIN_FLOAT_VALUE_IN_BIGINT) >= 0 && bigIntValue.compareTo(MAX_FLOAT_VALUE_IN_BIGINT) <= 0; } /** * Returns true if the given value is a BigInteger value and fits into a double variable without precision loss. This is * decided based on the numerical value of the input and the significant bytes used in the double. * * @param value The value to check. * * @return True in case of the value meets the conditions, false otherwise. */ public static boolean isBigIntFitsToDouble(final Object value) { if (!(value instanceof BigInteger)) { return false; } final BigInteger bigIntValue = (BigInteger) value; return bigIntValue.compareTo(MIN_DOUBLE_VALUE_IN_BIGINT) >= 0 && bigIntValue.compareTo(MAX_DOUBLE_VALUE_IN_BIGINT) <= 0; } /** * Returns true in case the incoming value is a double which is within the range of float variable type. * * <p> * Note: the method only considers the covered range but not precision. The reason for this is that at this point the * double representation might already slightly differs from the original text value. * </p> * * @param value The value to check. * * @return True in case of the double value fits to float data type. */ public static boolean isDoubleWithinFloatInterval(final Object value) { if (!(value instanceof Double)) { return false; } final Double doubleValue = (Double) value; return MIN_FLOAT_VALUE_IN_DOUBLE <= doubleValue && doubleValue <= MAX_FLOAT_VALUE_IN_DOUBLE; } /** * Checks if an incoming value satisfies the requirements of a given (numeric) type or any of it's narrow data type. * * @param value Incoming value. * @param fieldType The expected field type. * * @return Returns true if the incoming value satisfies the data type of any of it's narrow data types. Otherwise returns false. Only numeric data types are supported. */ public static boolean isFittingNumberType(final Object value, final RecordFieldType fieldType) { if (NUMERIC_VALIDATORS.get(fieldType).test(value)) { return true; } for (final RecordFieldType recordFieldType : fieldType.getNarrowDataTypes()) { if (NUMERIC_VALIDATORS.get(recordFieldType).test(value)) { return true; } } return false; } }
mattyb149/nifi
nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/record/util/DataTypeUtils.java
Java
apache-2.0
80,351
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace FineUI.Examples.tree { public partial class tree_textselection { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// PageManager1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::FineUI.PageManager PageManager1; /// <summary> /// Tree1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::FineUI.Tree Tree1; } }
u0hz/FineUI
src/FineUI.Examples/tree/tree_textselection.aspx.designer.cs
C#
apache-2.0
1,477