code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
package com.turlir.abakgists.allgists.view.listing;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
abstract class ModelViewHolder<T> extends RecyclerView.ViewHolder {
ModelViewHolder(View itemView) {
super(itemView);
}
abstract void bind(T model);
}
|
Java
|
package com.zuoqing.demo.entity;
/**
* http 请求返回的最外层对象
*/
public class Result<T> {
private Integer code;
private String msg;
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
Java
|
/*
* 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 libthrift091;
public interface TEnum {
public int getValue();
}
|
Java
|
@*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*@
@import iht.models.RegistrationDetails
@import iht.models.application.tnrb._
@import iht.utils._
@import iht.utils.tnrb.TnrbHelperFixture
@import iht.models.application.tnrb.TnrbEligibiltyModel
@import iht.models.application.tnrb.WidowCheck
@import iht.config.AppConfig
@this(
implicit val appConfig: AppConfig,
form: FormWithCSRF,
ihtMainTemplateApplication: iht_main_template_application,
errorSummary: ihtHelpers.custom.error_summary,
inputYesNoRadioGroup: ihtHelpers.standard.input_yes_no_radio_group
)
@(partnerLivingInUkForm:Form[TnrbEligibiltyModel],
tnrbModel: TnrbEligibiltyModel,
widowCheck: WidowCheck,
cancelUrl:Call, registrationDetails: RegistrationDetails)(implicit request:Request[_], messages: Messages)
@deceasedName() = @{CommonHelper.getOrException(registrationDetails.deceasedDetails).name}
@partnerName() = @{TnrbHelperFixture().spouseOrCivilPartnerLabelGenitive(tnrbModel, widowCheck, deceasedName, true)}
@ihtMainTemplateApplication(
title = "",
browserTitle = Some(Messages("iht.registration.deceased.locationOfPermanentHome")),
cancelLabel=Some(Messages("page.iht.application.tnrb.returnToIncreasingThreshold")),
cancelUrl = Some(cancelUrl)
){
@errorSummary(partnerLivingInUkForm)
@form(action = iht.controllers.application.tnrb.routes.PermanentHomeController.onSubmit,'autoComplete -> "off") {
@inputYesNoRadioGroup(
partnerLivingInUkForm("isPartnerLivingInUk"),
'_hintText -> Html(Messages("page.iht.application.tnrb.permanentHome.question.hint")),
'_divClass -> Some("form-group"),
'_legend -> Messages("iht.estateReport.tnrb.permanentHome.question",partnerName),
'_legendClass -> Some("legend-with-heading"),
'_legendIsHeading -> true,
'_headingClass -> "heading-large"
)
<div id="action-button" class="form-group">
<button class="button" id="save-continue" name="action" value="save">@Messages("iht.saveAndContinue")</button>
</div>
}
}
|
Java
|
/*
* Copyright (c) 2013 EMBL - European Bioinformatics Institute
* 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.
*/
var lodeNamespacePrefixes = {
rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
owl: 'http://www.w3.org/2002/07/owl#',
dc: 'http://purl.org/dc/elements/1.1/',
dcterms: 'http://purl.org/dc/terms/',
obo: 'http://purl.obolibrary.org/obo/',
efo: 'http://www.ebi.ac.uk/efo/',
'biosd-terms': 'http://rdf.ebi.ac.uk/terms/biosd/',
pav: 'http://purl.org/pav/2.0/',
prov: 'http://www.w3.org/ns/prov#',
foaf: 'http://xmlns.com/foaf/0.1/',
sio: 'http://semanticscience.org/resource/',
atlas: 'http://rdf.ebi.ac.uk/terms/atlas/',
oac: 'http://www.openannotation.org/ns/'
};
|
Java
|
package utils
import java.io.{BufferedReader, File, InputStreamReader}
import scala.io.Source
/**
* Created by yujieshui on 2016/8/30.
*/
object NextLine {
type NextLine = () => String
def fromSystemIn(): NextLine = {
val bi = new BufferedReader(new InputStreamReader(System.in))
() => bi.readLine()
}
def fromFile(file: File): NextLine = {
fromSeq(Source.fromFile(file).getLines().toSeq)
}
def fromSeq(seq: Seq[String]): NextLine = {
var list = seq
() => {
val r = list.head
list = list.tail
r
}
}
}
|
Java
|
/*
* Copyright to the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.tools.cli;
import java.io.BufferedReader;
import java.io.PrintStream;
/**
* Define plugin interface for CLI option handlers. An OptionHandler is
* responsible for providing a option, or activity, that will be used through
* the CLI.
*
* @author Dennis Reedy
*/
public interface OptionHandler {
/**
* Process the option.
*
* @param input Parameters for the option, may be null
* @param br An optional BufferdReader, used if the option requires input.
* if this is null, the option handler may create a BufferedReader to
* handle the input
* @param out The PrintStream to use if the option prints results or
* choices for the user. Must not be null
*
* @return The result of the action.
*/
String process(String input, BufferedReader br, PrintStream out);
/**
* Get the usage of the command
*
* @return Command usage
*/
String getUsage();
}
|
Java
|
package com.eric.drools_demo;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
|
Java
|
// -----------------------------------------------------------------------------
// Copyright 2011-2012 Patrick Näf (herzbube@herzbube.ch)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -----------------------------------------------------------------------------
// Project includes
#include "TableViewCellFactory.h"
// -----------------------------------------------------------------------------
/// @brief The UiUtilities class is a container for various utility functions
/// related to UI controls.
///
/// All functions in UiUtilities are class methods, so there is no need to
/// create an instance of UiUtilities.
// -----------------------------------------------------------------------------
@interface UiUtilities : NSObject
{
}
+ (double) radians:(double)degrees;
+ (CGFloat) tableView:(UITableView*)tableView heightForCellOfType:(enum TableViewCellType)type withText:(NSString*)text hasDisclosureIndicator:(bool)hasDisclosureIndicator;
+ (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;
+ (void) createTableViewWithStyle:(UITableViewStyle)tableViewStyle forController:(UIViewController*)viewController;
+ (void) addGroupTableViewBackgroundToView:(UIView*)view;
+ (UIImage*) gradientImageWithSize:(CGSize)size startColor:(UIColor*)startColor endColor:(UIColor*)endColor;
+ (void) drawLinearGradientWithContext:(CGContextRef)context rect:(CGRect)rect startColor:(CGColorRef)startColor endColor:(CGColorRef)endColor;
@end
|
Java
|
package com.cognitionis.nlp_files;
import java.io.*;
import java.util.regex.*;
/**
*
* @author Héctor Llorens
* @since 2011
*/
public class TreebankFile extends NLPFile {
public TreebankFile(String filename) {
super(filename);
}
@Override
public Boolean isWellFormatted() {
int par_level = 0;
try {
if (super.getFile()==null) {
throw new Exception("No file loaded in NLPFile object");
}
BufferedReader reader = new BufferedReader(new FileReader(this.f));
try {
String line = null;
int linen = 0;
Pattern p = Pattern.compile("[\\(\\)]");
while ((line = reader.readLine()) != null) {
linen++; //System.getProperty("line.separator")
if (line.matches("\\s*[^\\(\\s].*")) {
throw new Exception("Treebank format error: line " + linen + " not begining with \\s*(");
}
Matcher m = p.matcher(line);
while (m.find()) {
if (m.group().equals("(")) {
par_level++;
} else {
par_level--;
if (par_level < 0) {
throw new Exception("Treebank format error: par_level lower than 0");
}
}
}
//System.out.println(linen+": "+line+" - parlevel="+ par_level);
}
} finally {
reader.close();
}
if (par_level != 0) {
throw new Exception("Treebank format error: positive unbalancement, par_level=" + par_level);
}
} catch (Exception e) {
System.err.println("Errors found ("+this.getClass().getSimpleName()+"):\n\t" + e.toString() + "\n");
if(System.getProperty("DEBUG")!=null && System.getProperty("DEBUG").equalsIgnoreCase("true")){e.printStackTrace(System.err);}
return false;
}
return true;
}
public String toPlain(String filename){
// one token, one space, one token, one space... (end of sentence -> \n)
return this.getFile().toString();
}
}
|
Java
|
package com.kashukov.convert;
/**
* Convert short to any primitive data type
*/
public class Short {
/**
* Convert short to boolean
*
* @param input short
* @return boolean
*/
public static boolean shortToBoolean(short input) {
return input != 0;
}
/**
* Convert short to byte
*
* @param input short
* @return byte
*/
public static byte shortToByte(short input) {
return (byte) input;
}
/**
* Convert short to byte[]
*
* @param input short
* @return byte[]
*/
public static byte[] shortToByteArray(short input) {
return new byte[]{
(byte) (input >>> 8),
(byte) input};
}
/**
* Convert short to char
*
* @param input short
* @return char
*/
public static char shortToChar(short input) {
return (char) input;
}
/**
* Convert short to double
*
* @param input short
* @return double
*/
public static double shortToDouble(short input) {
return (double) input;
}
/**
* Convert short to float
*
* @param input short
* @return float
*/
public static float shortToFloat(short input) {
return (float) input;
}
/**
* Convert short to int
*
* @param input short
* @return int
*/
public static int shortToInt(short input) {
return (int) input;
}
/**
* Convert short to long
*
* @param input short
* @return long
*/
public static long shortToLong(short input) {
return (long) input;
}
/**
* Convert short to String
*
* @param input short
* @return String
*/
public static java.lang.String shortToString(short input) {
return java.lang.Short.toString(input);
}
}
|
Java
|
<?php
/**
* PluginOp2CommunityEventMember form.
*
* @package opMTViewerPlugin
* @subpackage form
* @author Kimura Youichi <kim.upsilon@gmail.com>
*/
abstract class PluginOp2CommunityEventMemberForm extends BaseOp2CommunityEventMemberForm
{
}
|
Java
|
package be.dnsbelgium.rdap.sample.parser;
import be.dnsbelgium.rdap.sample.dto.Contact;
import be.dnsbelgium.rdap.sample.dto.DnsSecKey;
import be.dnsbelgium.rdap.sample.dto.SimpleContact;
public enum WhoisKeyBlock {
MAIN(),
DOMAIN(),
REGISTRAR(),
REGISTRANT(),
ADMIN(Contact.class),
TECH(Contact.class),
DNSSEC(),
DNSSECKEY(DnsSecKey.class, true),
HOST(),
SIMPLE_ADMIN(SimpleContact.class),
SIMPLE_TECH(SimpleContact.class);
private Class repeatClass = null;
private boolean hasIndexSuffix = false;
WhoisKeyBlock() {
}
WhoisKeyBlock(Class repeatClass) {
this.repeatClass = repeatClass;
}
WhoisKeyBlock(Class repeatClass, boolean hasIndexSuffix) {
this.repeatClass = repeatClass;
this.hasIndexSuffix = hasIndexSuffix;
}
public Class getRepeatClass() {
return repeatClass;
}
public boolean hasIndexSuffix() {
return hasIndexSuffix;
}
public boolean isRepeatable() {
return repeatClass != null;
}
}
|
Java
|
package com.github.hadoop.maven.plugin;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
/**
* Writes jars.
*
*
*/
public class JarWriter {
/**
* Given a root directory, this writes the contents of the same as a jar file.
* The path to files inside the jar are relative paths, relative to the root
* directory specified.
*
* @param jarRootDir
* Root Directory that serves as an input to writing the jars.
* @param os
* OutputStream to which the jar is to be packed
* @throws FileNotFoundException
* @throws IOException
*/
public void packToJar(File jarRootDir, OutputStream os)
throws FileNotFoundException, IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(os, manifest);
for (File nestedFile : jarRootDir.listFiles())
add(jarRootDir.getPath().replace("\\", "/"), nestedFile, target);
target.close();
}
private void add(String prefix, File source, JarOutputStream target)
throws IOException {
BufferedInputStream in = null;
try {
if (source.isDirectory()) {
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty()) {
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name.substring(prefix.length() + 1));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile : source.listFiles())
add(prefix, nestedFile, target);
return;
}
String jarentryName = source.getPath().replace("\\", "/").substring(
prefix.length() + 1);
JarEntry entry = new JarEntry(jarentryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
} finally {
if (in != null)
in.close();
}
}
}
|
Java
|
package dbtarzan.gui.table
import scalafx.scene.control.{TableView, TableColumn}
import scala.util.Random
import scalafx.Includes._
import dbtarzan.gui.util.JFXUtil
import dbtarzan.db._
object TableColumnsFitter {
/* a logistic (sigmoid) function, almost linear, returns max 50 */
def logistic(x : Double) : Double =
50.0 / (1.0 + 10.0 * scala.math.exp(-.1 * x))
}
class TableColumnsFitter[S](table : TableView[S], columns : List[Field]) {
private val maxSizes = new TableColumnsMaxSizes(columns, new Random())
private val charSize = JFXUtil.averageCharacterSize()
private def resizeColumn(column : TableColumn[S, _], size : Int) : Unit = {
val x = TableColumnsFitter.logistic((size+2))
column.prefWidth = x * charSize
}
def addRows(rows : List[Row]) : Unit = {
val columns = table.columns.drop(1)
maxSizes.addRows(rows)
val newSizes = maxSizes.maxLengths
// println("newSizes "+newSizes)
columns.zip(newSizes).foreach({
case (column, size) => resizeColumn(column, size)
})
}
}
|
Java
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.transfer.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum HomeDirectoryType {
PATH("PATH"),
LOGICAL("LOGICAL");
private String value;
private HomeDirectoryType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return HomeDirectoryType corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static HomeDirectoryType fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (HomeDirectoryType enumEntry : HomeDirectoryType.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
|
Java
|
package com.ilad.teamwork;
import org.openqa.selenium.WebElement;
import io.appium.java_client.android.AndroidDriver;
public class TabsMenu extends AbstractTeamWork {
public TabsMenu(AndroidDriver<WebElement> driver) {
super(driver);
}
public AllProjectsPage goToProjects() {
driver.findElementByXPath("//android.widget.TextView[@text='Projects']").click();
return new AllProjectsPage(driver);
}
}
|
Java
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_32965_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=10994#src-10994" >testAbaNumberCheck_32965_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:22
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32965_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=12585#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
Java
|
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
#
# 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 'spec_helper'
RSpec.describe OneviewSDK::API2200::C7000::VolumeTemplate do
include_context 'shared context'
it 'inherits from OneviewSDK::API2000::C7000::VolumeTemplate' do
expect(described_class).to be < OneviewSDK::API2000::C7000::VolumeTemplate
end
end
|
Java
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202111;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ActivityGroup#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link ActivityGroup#name}</td>
* </tr>
* <tr>
* <td>{@code impressionsLookback}</td>
* <td>{@link ActivityGroup#impressionsLookback}</td>
* </tr>
* <tr>
* <td>{@code clicksLookback}</td>
* <td>{@link ActivityGroup#clicksLookback}</td>
* </tr>
* <tr>
* <td>{@code status}</td>
* <td>{@link ActivityGroup#status}</td>
* </tr>
* </table>
*
* @param filterStatement a statement used to filter a set of activity groups
* @return the activity groups that match the given filter
*
*
* <p>Java class for getActivityGroupsByStatement element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getActivityGroupsByStatement">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202111}Statement" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"filterStatement"
})
@XmlRootElement(name = "getActivityGroupsByStatement")
public class ActivityGroupServiceInterfacegetActivityGroupsByStatement {
protected Statement filterStatement;
/**
* Gets the value of the filterStatement property.
*
* @return
* possible object is
* {@link Statement }
*
*/
public Statement getFilterStatement() {
return filterStatement;
}
/**
* Sets the value of the filterStatement property.
*
* @param value
* allowed object is
* {@link Statement }
*
*/
public void setFilterStatement(Statement value) {
this.filterStatement = value;
}
}
|
Java
|
package vnetpeering
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-11-01/network"
"github.com/giantswarm/microerror"
"github.com/giantswarm/operatorkit/v4/pkg/controller/context/reconciliationcanceledcontext"
"github.com/giantswarm/to"
"github.com/giantswarm/azure-operator/v5/service/controller/key"
)
const (
ProvisioningStateDeleting = "Deleting"
)
// This resource manages the VNet peering between the control plane and tenant cluster.
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
cr, err := key.ToCustomResource(obj)
if err != nil {
return microerror.Mask(err)
}
var tcVnet network.VirtualNetwork
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if TC virtual network %#q exists in resource group %#q", key.VnetName(cr), key.ResourceGroupName(cr)))
virtualNetworksClient, err := r.clientFactory.GetVirtualNetworksClient(ctx, cr.ObjectMeta)
if err != nil {
return microerror.Mask(err)
}
tcVnet, err = virtualNetworksClient.Get(ctx, key.ResourceGroupName(cr), key.VnetName(cr), "")
if IsNotFound(err) {
r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network does not exist in resource group")
reconciliationcanceledcontext.SetCanceled(ctx)
r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network exists in resource group")
}
var cpVnet network.VirtualNetwork
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if CP virtual network %#q exists in resource group %#q", r.mcVirtualNetworkName, r.mcResourceGroup))
cpVnet, err = r.cpAzureClientSet.VirtualNetworkClient.Get(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, "")
if IsNotFound(err) {
r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network does not exist in resource group")
reconciliationcanceledcontext.SetCanceled(ctx)
r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network exists")
}
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the tenant cluster vnet %#q in resource group %#q", r.mcVirtualNetworkName, key.VnetName(cr), key.ResourceGroupName(cr)))
vnetPeeringsClient, err := r.clientFactory.GetVnetPeeringsClient(ctx, cr.ObjectMeta)
if err != nil {
return microerror.Mask(err)
}
tcPeering := r.getTCVnetPeering(*cpVnet.ID)
_, err = vnetPeeringsClient.CreateOrUpdate(ctx, key.ResourceGroupName(cr), key.VnetName(cr), r.mcVirtualNetworkName, tcPeering)
if err != nil {
return microerror.Mask(err)
}
}
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the control plane vnet %#q in resource group %#q", key.ResourceGroupName(cr), r.mcVirtualNetworkName, r.mcResourceGroup))
cpPeering := r.getCPVnetPeering(*tcVnet.ID)
_, err = r.cpAzureClientSet.VnetPeeringClient.CreateOrUpdate(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, key.ResourceGroupName(cr), cpPeering)
if err != nil {
return microerror.Mask(err)
}
}
return nil
}
func (r *Resource) getCPVnetPeering(vnetId string) network.VirtualNetworkPeering {
peering := network.VirtualNetworkPeering{
VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{
AllowVirtualNetworkAccess: to.BoolP(true),
AllowForwardedTraffic: to.BoolP(false),
AllowGatewayTransit: to.BoolP(false),
UseRemoteGateways: to.BoolP(false),
RemoteVirtualNetwork: &network.SubResource{
ID: &vnetId,
},
},
}
return peering
}
func (r *Resource) getTCVnetPeering(vnetId string) network.VirtualNetworkPeering {
peering := network.VirtualNetworkPeering{
VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{
AllowVirtualNetworkAccess: to.BoolP(true),
AllowForwardedTraffic: to.BoolP(false),
AllowGatewayTransit: to.BoolP(false),
UseRemoteGateways: to.BoolP(false),
RemoteVirtualNetwork: &network.SubResource{
ID: &vnetId,
},
},
}
return peering
}
|
Java
|
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
@SuppressWarnings("unused")
public class ImportVmModel extends ListWithDetailsModel {
boolean sameSelectedDestinationStorage = false;
ArrayList<storage_domains> uniqueDestStorages;
ArrayList<storage_domains> allDestStorages;
storage_domains selectedDestinationStorage;
HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic;
HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic;
HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic;
VmImportDiskListModel importDiskListModel;
ArrayList<storage_domains> allStorageDomains;
int uniqueDomains;
Guid templateGuid;
private storage_domain_static privateSourceStorage;
public storage_domain_static getSourceStorage() {
return privateSourceStorage;
}
public void setSourceStorage(storage_domain_static value) {
privateSourceStorage = value;
}
private storage_pool privateStoragePool;
public storage_pool getStoragePool() {
return privateStoragePool;
}
public void setStoragePool(storage_pool value) {
privateStoragePool = value;
}
private ListModel privateDestinationStorage;
public ListModel getDestinationStorage() {
return privateDestinationStorage;
}
private void setDestinationStorage(ListModel value) {
privateDestinationStorage = value;
}
private ListModel privateAllDestinationStorage;
public ListModel getAllDestinationStorage() {
return privateAllDestinationStorage;
}
private void setAllDestinationStorage(ListModel value) {
privateAllDestinationStorage = value;
}
private ListModel privateCluster;
public ListModel getCluster() {
return privateCluster;
}
private void setCluster(ListModel value) {
privateCluster = value;
}
private ListModel privateSystemDiskFormat;
public ListModel getSystemDiskFormat() {
return privateSystemDiskFormat;
}
private void setSystemDiskFormat(ListModel value) {
privateSystemDiskFormat = value;
}
private ListModel privateDataDiskFormat;
public ListModel getDataDiskFormat() {
return privateDataDiskFormat;
}
private void setDataDiskFormat(ListModel value) {
privateDataDiskFormat = value;
}
private EntityModel collapseSnapshots;
public EntityModel getCollapseSnapshots() {
return collapseSnapshots;
}
public void setCollapseSnapshots(EntityModel value) {
this.collapseSnapshots = value;
}
private boolean isMissingStorages;
public boolean getIsMissingStorages() {
return isMissingStorages;
}
public void setIsMissingStorages(boolean value) {
if (isMissingStorages != value) {
isMissingStorages = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages"));
}
}
private String nameAndDescription;
private AsyncQuery onCollapseSnapshotsChangedFinish;
public String getNameAndDescription() {
return nameAndDescription;
}
public void setNameAndDescription(String value) {
if (!StringHelper.stringsEqual(nameAndDescription, value)) {
nameAndDescription = value;
OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription"));
}
}
private java.util.List<VM> problematicItems;
public java.util.List<VM> getProblematicItems() {
return problematicItems;
}
public void setProblematicItems(java.util.List<VM> value) {
if (problematicItems != value) {
problematicItems = value;
OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems"));
}
}
private EntityModel privateIsSingleDestStorage;
public EntityModel getIsSingleDestStorage() {
return privateIsSingleDestStorage;
}
public void setIsSingleDestStorage(EntityModel value) {
privateIsSingleDestStorage = value;
}
private ListModel privateStorageDoamins;
public ListModel getStorageDoamins() {
return privateStorageDoamins;
}
private void setStorageDoamins(ListModel value) {
privateStorageDoamins = value;
}
private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap;
public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap()
{
return privateDiskStorageMap;
}
public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value)
{
privateDiskStorageMap = value;
}
@Override
public void setSelectedItem(Object value) {
super.setSelectedItem(value);
OnEntityChanged();
}
public ImportVmModel() {
setProblematicItems(new ArrayList<VM>());
setCollapseSnapshots(new EntityModel());
getCollapseSnapshots().setEntity(false);
getCollapseSnapshots().getPropertyChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
OnCollapseSnapshotsChanged();
}
});
setDestinationStorage(new ListModel());
getDestinationStorage().getSelectedItemChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
DestinationStorage_SelectedItemChanged();
}
});
setCluster(new ListModel());
setSystemDiskFormat(new ListModel());
setDataDiskFormat(new ListModel());
setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>());
setIsSingleDestStorage(new EntityModel());
getIsSingleDestStorage().setEntity(true);
setAllDestinationStorage(new ListModel());
}
public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) {
this.onCollapseSnapshotsChangedFinish = _asyncQuery;
OnCollapseSnapshotsChanged();
}
public void initStorageDomains() {
templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>();
uniqueDomains = 0;
for (Object item : getItems()) {
VM vm = (VM) item;
templateGuid = vm.getvmt_guid();
if (templateGuid.equals(NGuid.Empty)) {
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(templateGuid, null);
templateGuidAllStorageDomainDic.put(templateGuid, null);
} else {
AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
ImportVmModel importVmModel = (ImportVmModel) target;
ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue;
ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>();
for (DiskImage disk : disks) {
allSourceStorages.add(disk.getstorage_ids());
}
ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages);
ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages);
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid,
intersectStorageDomains);
templateGuidAllStorageDomainDic.put(importVmModel.templateGuid,
unionStorageDomains);
templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks);
importVmModel.postInitStorageDomains();
}
}),
templateGuid);
}
}
postInitStorageDomains();
}
protected void postInitStorageDomains() {
if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) {
return;
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.Model = this;
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object returnValue) {
allStorageDomains = (ArrayList<storage_domains>) returnValue;
OnCollapseSnapshotsChanged();
initDiskStorageMap();
}
};
AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId());
}
private void initDiskStorageMap() {
for (Object item : getItems()) {
VM vm = (VM) item;
for (DiskImage disk : vm.getDiskMap().values()) {
if (NGuid.Empty.equals(vm.getvmt_guid())) {
Guid storageId = !allDestStorages.isEmpty() ?
allDestStorages.get(0).getId() : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
else {
ArrayList<Guid> storageIds =
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid());
Guid storageId = storageIds != null ?
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
}
}
}
public void OnCollapseSnapshotsChanged() {
if (this.getItems() == null || allStorageDomains == null) {
return;
}
selectedDestinationStorage = null;
sameSelectedDestinationStorage = false;
uniqueDestStorages = new ArrayList<storage_domains>();
allDestStorages = new ArrayList<storage_domains>();
setIsMissingStorages(false);
if (getDestinationStorage().getSelectedItem() != null) {
selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem();
}
for (storage_domains domain : allStorageDomains) {
boolean addStorage = false;
if (Linq.IsDataActiveStorageDomain(domain)) {
allDestStorages.add(domain);
if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) {
addStorage = true;
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet())
{
if (NGuid.Empty.equals(keyValuePair.getKey())) {
addStorage = true;
} else {
addStorage = false;
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
addStorage = true;
break;
}
}
}
if (addStorage == false) {
break;
}
}
}
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet())
{
if (!NGuid.Empty.equals(keyValuePair.getKey())) {
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
setIsMissingStorages(true);
break;
}
}
}
}
}
if (addStorage) {
uniqueDestStorages.add(domain);
if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) {
sameSelectedDestinationStorage = true;
selectedDestinationStorage = domain;
}
}
}
getAllDestinationStorage().setItems(allDestStorages);
getDestinationStorage().setItems(uniqueDestStorages);
if (sameSelectedDestinationStorage) {
getDestinationStorage().setSelectedItem(selectedDestinationStorage);
} else {
getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages));
}
if (getDetailModels() != null
&& getActiveDetailModel() instanceof VmImportDiskListModel) {
VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel();
detailModel
.setCollapseSnapshots((Boolean) getCollapseSnapshots()
.getEntity());
}
if (onCollapseSnapshotsChangedFinish != null) {
onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess(
onCollapseSnapshotsChangedFinish.getModel(), null);
onCollapseSnapshotsChangedFinish = null;
}
}
@Override
protected void ActiveDetailModelChanged() {
super.ActiveDetailModelChanged();
OnCollapseSnapshotsChanged();
}
@Override
protected void InitDetailModels() {
super.InitDetailModels();
importDiskListModel = new VmImportDiskListModel();
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(new VmGeneralModel());
list.add(new VmImportInterfaceListModel());
list.add(importDiskListModel);
list.add(new VmAppListModel());
setDetailModels(list);
}
public boolean Validate() {
getDestinationStorage().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
getCluster().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
return getDestinationStorage().getIsValid()
&& getCluster().getIsValid();
}
@Override
protected void OnSelectedItemChanged() {
super.OnSelectedItemChanged();
if (getSelectedItem() != null) {
VM vm = (VM) getSelectedItem();
setNameAndDescription(StringFormat.format("%1$s%2$s",
vm.getvm_name(),
!StringHelper.isNullOrEmpty(vm.getvm_description()) ? " ["
+ vm.getvm_description() + "]" : ""));
} else {
setNameAndDescription("");
}
}
public void setItems(Iterable value)
{
super.setItems(value);
for (Object vm : getItems()) {
getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>());
}
initStorageDomains();
}
@Override
protected String getListName() {
return "ImportVmModel";
}
public void setSelectedVMsCount(int size) {
importDiskListModel.setSelectedVMsCount(((List) getItems()).size());
}
storage_domains currStorageDomain = null;
private void DestinationStorage_SelectedItemChanged() {
storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem();
List destinationStorageDomains = ((List) getDestinationStorage().getItems());
if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) {
selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0);
}
if (currStorageDomain == null || selectedStorageDomain == null
|| !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) {
currStorageDomain = selectedStorageDomain;
UpdateImportWarnings();
}
}
public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) {
VM item = (VM) getSelectedItem();
addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId());
}
public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) {
HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId);
vmDiskStorageMap.put(disk.getId(), storageId);
}
private storage_domains getStorageDomainByName(String storageDomainName) {
storage_domains storage = null;
for (Object storageDomain : getDestinationStorage().getItems()) {
storage = (storage_domains) storageDomain;
if (storageDomainName.equals(storage.getstorage_name())) {
break;
}
}
return storage;
}
@Override
protected void ItemsChanged() {
super.ItemsChanged();
UpdateImportWarnings();
}
public VmImportDiskListModel getImportDiskListModel() {
return importDiskListModel;
}
private void UpdateImportWarnings() {
// Clear problematic state.
getProblematicItems().clear();
if (getItems() == null) {
return;
}
storage_domains destinationStorage = (storage_domains) getDestinationStorage()
.getSelectedItem();
for (Object item : getItems()) {
VM vm = (VM) item;
if (vm.getDiskMap() != null) {
for (java.util.Map.Entry<String, DiskImage> pair : vm
.getDiskMap().entrySet()) {
DiskImage disk = pair.getValue();
if (disk.getvolume_type() == VolumeType.Sparse
&& disk.getvolume_format() == VolumeFormat.RAW
&& destinationStorage != null
&& (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage
.getstorage_type() == StorageType.FCP)) {
getProblematicItems().add(vm);
}
}
}
}
// Decide what to do with the CollapseSnapshots option.
if (problematicItems.size() > 0) {
if (problematicItems.size() == Linq.Count(getItems())) {
// All items are problematic.
getCollapseSnapshots().setIsChangable(false);
getCollapseSnapshots().setEntity(true);
getCollapseSnapshots()
.setMessage(
"Note that all snapshots will be collapsed due to different storage types");
} else {
// Some items are problematic.
getCollapseSnapshots()
.setMessage(
"Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs");
}
} else {
// No problematic items.
getCollapseSnapshots().setIsChangable(true);
getCollapseSnapshots().setMessage(null);
}
}
public void VolumeType_SelectedItemChanged(DiskImage disk,
VolumeType tempVolumeType) {
for (Object item : getItems()) {
VM vm = (VM) item;
java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>();
for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap()
.entrySet()) {
if (a.getValue().getQueryableId().equals(disk.getQueryableId())) {
a.getValue().setvolume_type(tempVolumeType);
break;
}
}
}
}
public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) {
ArrayList<String> storageDomains = null;
ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId);
if (storageDomainsIds != null) {
storageDomains = new ArrayList<String>();
for (Guid storageId : storageDomainsIds) {
if (Linq.IsActiveStorageDomain(getStorageById(storageId))) {
storageDomains.add(getStorageNameById(storageId));
}
}
}
if (storageDomains != null) {
Collections.sort(storageDomains);
}
return storageDomains;
}
public String getStorageNameById(NGuid storageId) {
String storageName = "";
for (Object storageDomain : getAllDestinationStorage().getItems()) {
storage_domains storage = (storage_domains) storageDomain;
if (storage.getId().equals(storageId)) {
storageName = storage.getstorage_name();
}
}
return storageName;
}
public storage_domains getStorageById(Guid storageId) {
for (storage_domains storage : allDestStorages) {
if (storage.getId().equals(storageId)) {
return storage;
}
}
return null;
}
}
|
Java
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Ais.Internal.Dcm.ModernUIV2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ais.Internal.Dcm.ModernUIV2")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Java
|
# Accelerator backends
It's pretty straightforward to describe a `Tensor` calculation, but when and how that calculation
is performed will depend on which backend is used for the `Tensor`s and when the results
are needed on the host CPU.
Behind the scenes, operations on `Tensor`s are dispatched to accelerators like GPUs or
[TPUs](https://cloud.google.com/tpu), or run on the CPU when no accelerator is available. This
happens automatically for you, and makes it easy to perform complex parallel calculations using
a high-level interface. However, it can be useful to understand how this dispatch occurs and be
able to customize it for optimal performance.
Swift for TensorFlow has two backends for performing accelerated computation: TensorFlow eager mode
and X10. The default backend is TensorFlow eager mode, but that can be overridden. An
[interactive tutorial](https://colab.research.google.com/github/tensorflow/swift/blob/main/docs/site/tutorials/introducing_x10.ipynb)
is available that walks you through the use of these different backends.
## TensorFlow eager mode
The TensorFlow eager mode backend leverages
[the TensorFlow C API](https://www.tensorflow.org/install/lang_c) to send each `Tensor` operation
to a GPU or CPU as it is encountered. The result of that operation is then retrieved and passed on
to the next operation.
This operation-by-operation dispatch is straightforward to understand and requires no explicit
configuration within your code. However, in many cases it does not result in optimal performance
due to the overhead from sending off many small operations, combined with the lack of operation
fusion and optimization that can occur when graphs of operations are present. Finally, TensorFlow eager mode is incompatible with TPUs, and can only be used with CPUs and GPUs.
## X10 (XLA-based tracing)
X10 is the name of the Swift for TensorFlow backend that uses lazy tensor tracing and [the XLA
optimizing compiler](https://www.tensorflow.org/xla) to in many cases significantly improve
performance over operation-by-operation dispatch. Additionally, it adds compatibility for
[TPUs](https://cloud.google.com/tpu), accelerators specifically optimized for the kinds of
calculations found within machine learning models.
The use of X10 for `Tensor` calculations is not the default, so you need to opt in to this backend.
That is done by specifying that a `Tensor` is placed on an XLA device:
```swift
let tensor1 = Tensor<Float>([0.0, 1.0, 2.0], on: Device.defaultXLA)
let tensor2 = Tensor<Float>([1.5, 2.5, 3.5], on: Device.defaultXLA)
```
After that point, describing a calculation is exactly the same as for TensorFlow eager mode:
```swift
let tensor3 = tensor1 + tensor2
```
Further detail can be provided when creating a `Tensor`, such as what kind of accelerator to use
and even which one, if several are available. For example, a `Tensor` can be created on the second
TPU device (assuming it is visible to the host the program is running on) using the following:
```swift
let tpuTensor = Tensor<Float>([0.0, 1.0, 2.0], on: Device(kind: .TPU, ordinal: 1, backend: .XLA))
```
No implicit movement of `Tensor`s between devices is performed, so if two `Tensor`s on different
devices are used in an operation together, a runtime error will occur. To manually copy the
contents of a `Tensor` to a new device, you can use the `Tensor(copying:to:)` initializer. Some
larger-scale structures that contain `Tensor`s within them, like models and optimizers, have helper
functions for moving all of their interior `Tensor`s to a new device in one step.
Unlike TensorFlow eager mode, operations using the X10 backend are not individually dispatched as
they are encountered. Instead, dispatching to an accelerator is only triggered by either reading
calculated values back to the host or by placing an explicit barrier. The way this works is that
the runtime starts from the value being read to the host (or the last calculation before a manual
barrier) and traces the graph of calculations that result in that value.
This traced graph is then converted to the XLA HLO intermediate representation and passed to the
XLA compiler to be optimized and compiled for execution on the accelerator. From there, the entire
calculation is sent to the accelerator and the end result obtained.
Calculation is a time-consuming process, so X10 is best used with massively parallel calculations
that are expressed via a graph and that are performed many times. Hash values and caching are used so that identical graphs are only compiled once for every unique configuration.
For machine learning models, the training process often involves a loop where the model is
subjected to the same series of calculations over and over. You'll want each of these passes to be
seen as a repetition of the same trace, rather than one long graph with repeated units inside it.
This is enabled by the manual insertion of a call to `LazyTensorBarrier()` function at the
locations in your code where you wish for a trace to end.
### Mixed-precision support in X10
Training with mixed precision via X10 is supported and both low-level and
high-level API are provided to control it. The
[low-level API](https://github.com/tensorflow/swift-apis/blob/main/Sources/TensorFlow/Core/MixedPrecision.swift)
offers two computed properties: `toReducedPrecision` and `toFullPrecision` which
convert between full and reduced precision, along with `isReducedPrecision`
to query the precision. Besides `Tensor`s, models and optimizers can be converted
between full and reduced precision using this API.
Note that conversion to reduced precision doesn't change the logical type of a
`Tensor`. If `t` is a `Tensor<Float>`, `t.toReducedPrecision` is also a
`Tensor<Float>` with a reduced-precision underlying representation.
As with devices, operations between tensors of different precisions are not
allowed. This avoids silent and unwanted promotion to 32-bit floats, which would be hard
to detect by the user.
|
Java
|
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Wpf.Mvvm.TestHarness")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wpf.Mvvm.TestHarness")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Java
|
package com.pengrad.telegrambot.request;
import com.pengrad.telegrambot.response.BaseResponse;
/**
* Mirco Ianese
* 07 December 2021
*/
public class UnbanChatSenderChat extends BaseRequest<UnbanChatSenderChat, BaseResponse> {
public UnbanChatSenderChat(Object chatId, long sender_chat_id) {
super(BaseResponse.class);
add("chat_id", chatId).add("sender_chat_id", sender_chat_id);
}
}
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DevZH.UI
{
[StructLayout(LayoutKind.Sequential)]
public struct InitOptions
{
public UIntPtr Size;
}
}
|
Java
|
/**
* @author: Alberto Cerqueira
* @email: alberto.cerqueira1990@gmail.com
*/
jQuery.controller = function() {
var controllerClass = function() {
this.init = (function(){
$("#gravar").click(function(){
_self.gravar();
return false;
});
});
this.gravar = (function() {
$("#manterEntidade").ajaxSubmit({
url : systemURL,
dataType : "json",
success : (function(jsonReturn){
var consequence = jsonReturn.consequence;
if (consequence == "ERRO") {
alert(jsonReturn.message);
} else if (consequence == "SUCESSO") {
alert(jsonReturn.message + ": " + jsonReturn.dado.toString());
} else if(consequence == "MUITOS_ERROS"){
var mensagem = [''];
jQuery.each(jsonReturn.dado, function(i, dado) {
mensagem.push(dado.localizedMessage + "\n");
});
alert(mensagem.join(''));
}
//location.reload();
}),
error : (function(XMLHttpRequest, textStatus, errorThrown){
alert(errorConexao);
})
});
});
var _self = this;
};
return new controllerClass();
};
|
Java
|
/*
* Copyright (c) 2017-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 li.allan.easycache.config;
import li.allan.easycache.CacheKeyGenerator;
import li.allan.easycache.LocalCacheConfig;
/**
* @author lialun
*/
public class ConfigProperties {
private LocalCacheConfig localCacheConfig;
private CacheKeyGenerator cacheKeyGenerator;
public LocalCacheConfig getLocalCacheConfig() {
return localCacheConfig;
}
public void setLocalCacheConfig(LocalCacheConfig localCacheConfig) {
this.localCacheConfig = localCacheConfig;
}
public CacheKeyGenerator getCacheKeyGenerator() {
return cacheKeyGenerator;
}
public void setCacheKeyGenerator(CacheKeyGenerator cacheKeyGenerator) {
this.cacheKeyGenerator = cacheKeyGenerator;
}
}
|
Java
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from solum.api.controllers import common_types
from solum.api.controllers.v1.datamodel import types as api_types
#from solum.openstack.common import log as logging
#LOG = logging.getLogger(__name__)
class Extensions(api_types.Base):
"""extensions resource"""
extension_links = [common_types.Link]
"""This attribute contains Links to extension resources that contain
information about the extensions supported by this Platform."""
def __init__(self, **kwds):
# LOG.debug("extensions constructor: %s" % kwds)
super(Extensions, self).__init__(**kwds)
|
Java
|
<div class='row row-pad'>
<div class='col-sm-2 col-md-2 col-lg-2 text-center'>
<h5>Quick Menu</h5>
</div>
<div class='col-sm-8 col-md-8 col-lg-8 text-center'>
<h5>Videos</h5>
</div>
<div class='col-sm-2 col-md-2 col-lg-2 text-center'>
<h5>Following</h5>
</div>
</div>
<div class='row row-pad'>
<div class='col-sm-2 col-md-2 col-lg-2'>
<?= $videoNav ?>
</div>
<div class='col-sm-8 col-md-8 col-lg-8'>
<div class='row well row-pad'>
<?php if (count($videos) > 0): ?>
<div class='row scroll-h'>
<div class='scroll-h-inner row-pad'>
<?php foreach ($videos as $video): ?>
<span class='vid-thumb-container'>
<a href="/videos/single/<?= $video->id ?>">
<h4><?= $video->title; ?></h4>
<img class='vid-thumb' src=<?= $video->thumbnail ?>>
</a>
</span>
<?php endforeach; ?>
</div>
</div>
<?php else: ?>
<div class='well well-sm'>
It looks like this user has no videos yet!
</div>
<?php endif; ?>
</div>
</div>
<div class='col-sm-2 col-md-2 col-lg-2'>
<?= $friendsNav ?>
</div>
</div>
|
Java
|
/*
* Copyright 2014-2019 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.appsync.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appsync-2017-07-25/GetFunction" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetFunctionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The <code>Function</code> object.
* </p>
*/
private FunctionConfiguration functionConfiguration;
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
*/
public void setFunctionConfiguration(FunctionConfiguration functionConfiguration) {
this.functionConfiguration = functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @return The <code>Function</code> object.
*/
public FunctionConfiguration getFunctionConfiguration() {
return this.functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetFunctionResult withFunctionConfiguration(FunctionConfiguration functionConfiguration) {
setFunctionConfiguration(functionConfiguration);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFunctionConfiguration() != null)
sb.append("FunctionConfiguration: ").append(getFunctionConfiguration());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetFunctionResult == false)
return false;
GetFunctionResult other = (GetFunctionResult) obj;
if (other.getFunctionConfiguration() == null ^ this.getFunctionConfiguration() == null)
return false;
if (other.getFunctionConfiguration() != null && other.getFunctionConfiguration().equals(this.getFunctionConfiguration()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFunctionConfiguration() == null) ? 0 : getFunctionConfiguration().hashCode());
return hashCode;
}
@Override
public GetFunctionResult clone() {
try {
return (GetFunctionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
Java
|
/*
* Copyright 2008-2010 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 groovy.lang;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Field annotation to simplify lazy initialization.
* <p>
* Example usage without any special modifiers just defers initialization until the first call but is not thread-safe:
* <pre>
* {@code @Lazy} T x
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* if ($x != null)
* return $x
* else {
* $x = new T()
* return $x
* }
* }
* </pre>
*
* If the field is declared volatile then initialization will be synchronized using
* the <a href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> pattern as shown here:
*
* <pre>
* {@code @Lazy} volatile T x
* </pre>
* becomes
* <pre>
* private volatile T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = new T()
* }
* return $x
* }
* }
* }
* </pre>
*
* By default a field will be initialized by calling its default constructor.
*
* If the field has an initial value expression then this expression will be used instead of calling the default constructor.
* In particular, it is possible to use closure <code>{ ... } ()</code> syntax as follows:
*
* <pre>
* {@code @Lazy} T x = { [1, 2, 3] } ()
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = { [1, 2, 3] } ()
* }
* return $x
* }
* }
* }
* </pre>
* <p>
* <code>@Lazy(soft=true)</code> will use a soft reference instead of the field and use the above rules each time re-initialization is required.
* <p>
* If the <code>soft</code> flag for the annotation is not set but the field is static, then
* the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">initialization on demand holder idiom</a> is
* used as follows:
* <pre>
* {@code @Lazy} static FieldType field
* {@code @Lazy} static Date date1
* {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }()
* {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* </pre>
* becomes these methods and inners classes within the class containing the above definitions:
* <pre>
* private static class FieldTypeHolder_field {
* private static final FieldType INSTANCE = new FieldType()
* }
*
* private static class DateHolder_date1 {
* private static final Date INSTANCE = new Date()
* }
*
* private static class DateHolder_date2 {
* private static final Date INSTANCE = { new Date().updated(year: 2000) }()
* }
*
* private static class DateHolder_date3 {
* private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* }
*
* static FieldType getField() {
* return FieldTypeHolder_field.INSTANCE
* }
*
* static Date getDate1() {
* return DateHolder_date1.INSTANCE
* }
*
* static Date getDate2() {
* return DateHolder_date2.INSTANCE
* }
*
* static Date getDate3() {
* return DateHolder_date3.INSTANCE
* }
* </pre>
*
* @author Alex Tkachman
* @author Paul King
*/
@java.lang.annotation.Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation")
public @interface Lazy {
/**
* @return if field should be soft referenced instead of hard referenced
*/
boolean soft () default false;
}
|
Java
|
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.event.listener;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.artifact_cache.ArtifactCacheConnectEvent;
import com.facebook.buck.artifact_cache.CacheResult;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.event.CommandEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEventFetchData;
import com.facebook.buck.event.ArtifactCompressionEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.event.ChromeTraceEvent;
import com.facebook.buck.event.CompilerPluginDurationEvent;
import com.facebook.buck.event.PerfEventId;
import com.facebook.buck.event.SimplePerfEvent;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.AnnotationProcessingEvent;
import com.facebook.buck.jvm.java.tracing.JavacPhaseEvent;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.BuildRuleKeys;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleStatus;
import com.facebook.buck.rules.BuildRuleSuccessType;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.timing.FakeClock;
import com.facebook.buck.timing.IncrementingFakeClock;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.perf.PerfStatsTracking;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
public class ChromeTraceBuildListenerTest {
private static final long TIMESTAMP_NANOS = 1409702151000000000L;
private static final String EXPECTED_DIR =
"buck-out/log/2014-09-02_23h55m51s_no_sub_command_BUILD_ID/";
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
private InvocationInfo invocationInfo;
@Before
public void setUp() throws IOException {
invocationInfo = InvocationInfo.builder()
.setTimestampMillis(TimeUnit.NANOSECONDS.toMillis(TIMESTAMP_NANOS))
.setBuckLogDir(tmpDir.getRoot().toPath().resolve("buck-out/log"))
.setBuildId(new BuildId("BUILD_ID"))
.setSubCommand("no_sub_command")
.setIsDaemon(false)
.setSuperConsoleEnabled(false)
.build();
}
@Test
public void testDeleteFiles() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
String tracePath = invocationInfo.getLogDirectoryPath().resolve("build.trace").toString();
File traceFile = new File(tracePath);
projectFilesystem.createParentDirs(tracePath);
traceFile.createNewFile();
traceFile.setLastModified(0);
for (int i = 0; i < 10; ++i) {
File oldResult = new File(
String.format("%s/build.100%d.trace", invocationInfo.getLogDirectoryPath(), i));
oldResult.createNewFile();
oldResult.setLastModified(TimeUnit.SECONDS.toMillis(i));
}
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
ImmutableList<String> files = FluentIterable.
from(Arrays.asList(projectFilesystem.listFiles(invocationInfo.getLogDirectoryPath()))).
filter(input -> input.toString().endsWith(".trace")).
transform(File::getName).
toList();
assertEquals(4, files.size());
assertEquals(
ImmutableSortedSet.of(
"build.trace",
"build.1009.trace",
"build.1008.trace",
"build.2014-09-02.16-55-51.BUILD_ID.trace"),
ImmutableSortedSet.copyOf(files));
}
@Test
public void testBuildJson() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ObjectMapper mapper = ObjectMappers.newDefaultInstance();
BuildId buildId = new BuildId("ChromeTraceBuildListenerTestBuildId");
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
mapper,
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 42,
false);
BuildTarget target = BuildTargetFactory.newInstance("//fake:rule");
FakeBuildRule rule = new FakeBuildRule(
target,
new SourcePathResolver(
new BuildRuleResolver(
TargetGraph.EMPTY,
new DefaultTargetNodeToBuildRuleTransformer())
),
ImmutableSortedSet.of());
RuleKey ruleKey = new RuleKey("abc123");
String stepShortName = "fakeStep";
String stepDescription = "I'm a Fake Step!";
UUID stepUuid = UUID.randomUUID();
ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of(target);
Iterable<String> buildArgs = Iterables.transform(buildTargets, Object::toString);
Clock fakeClock = new IncrementingFakeClock(TimeUnit.MILLISECONDS.toNanos(1));
BuckEventBus eventBus = BuckEventBusFactory.newInstance(fakeClock, buildId);
eventBus.register(listener);
CommandEvent.Started commandEventStarted = CommandEvent.started(
"party",
ImmutableList.of("arg1", "arg2"),
/* isDaemon */ true);
eventBus.post(commandEventStarted);
eventBus.post(new PerfStatsTracking.MemoryPerfStatsEvent(
/* freeMemoryBytes */ 1024 * 1024L,
/* totalMemoryBytes */ 3 * 1024 * 1024L,
/* timeSpentInGcMs */ -1,
/* currentMemoryBytesUsageByPool */ ImmutableMap.of("flower", 42L * 1024 * 1024)));
ArtifactCacheConnectEvent.Started artifactCacheConnectEventStarted =
ArtifactCacheConnectEvent.started();
eventBus.post(artifactCacheConnectEventStarted);
eventBus.post(ArtifactCacheConnectEvent.finished(artifactCacheConnectEventStarted));
BuildEvent.Started buildEventStarted = BuildEvent.started(buildArgs);
eventBus.post(buildEventStarted);
HttpArtifactCacheEvent.Started artifactCacheEventStarted =
HttpArtifactCacheEvent.newFetchStartedEvent(ruleKey);
eventBus.post(artifactCacheEventStarted);
eventBus.post(
HttpArtifactCacheEvent.newFinishedEventBuilder(artifactCacheEventStarted)
.setFetchDataBuilder(
HttpArtifactCacheEventFetchData.builder()
.setFetchResult(CacheResult.hit("http")))
.build());
ArtifactCompressionEvent.Started artifactCompressionStartedEvent =
ArtifactCompressionEvent.started(
ArtifactCompressionEvent.Operation.COMPRESS, ImmutableSet.of(ruleKey));
eventBus.post(artifactCompressionStartedEvent);
eventBus.post(ArtifactCompressionEvent.finished(artifactCompressionStartedEvent));
eventBus.post(BuildRuleEvent.started(rule));
eventBus.post(StepEvent.started(stepShortName, stepDescription, stepUuid));
JavacPhaseEvent.Started runProcessorsStartedEvent = JavacPhaseEvent.started(
target,
JavacPhaseEvent.Phase.RUN_ANNOTATION_PROCESSORS,
ImmutableMap.of());
eventBus.post(runProcessorsStartedEvent);
String annotationProcessorName = "com.facebook.FakeProcessor";
AnnotationProcessingEvent.Operation operation = AnnotationProcessingEvent.Operation.PROCESS;
int annotationRound = 1;
boolean isLastRound = false;
AnnotationProcessingEvent.Started annotationProcessingEventStarted =
AnnotationProcessingEvent.started(
target,
annotationProcessorName,
operation,
annotationRound,
isLastRound);
eventBus.post(annotationProcessingEventStarted);
HttpArtifactCacheEvent.Scheduled httpScheduled = HttpArtifactCacheEvent.newStoreScheduledEvent(
Optional.of("TARGET_ONE"), ImmutableSet.of(ruleKey));
HttpArtifactCacheEvent.Started httpStarted =
HttpArtifactCacheEvent.newStoreStartedEvent(httpScheduled);
eventBus.post(httpStarted);
HttpArtifactCacheEvent.Finished httpFinished =
HttpArtifactCacheEvent.newFinishedEventBuilder(httpStarted).build();
eventBus.post(httpFinished);
final CompilerPluginDurationEvent.Started processingPartOneStarted =
CompilerPluginDurationEvent.started(
target,
annotationProcessorName,
"processingPartOne",
ImmutableMap.of());
eventBus.post(processingPartOneStarted);
eventBus.post(
CompilerPluginDurationEvent.finished(
processingPartOneStarted,
ImmutableMap.of()));
eventBus.post(AnnotationProcessingEvent.finished(annotationProcessingEventStarted));
eventBus.post(
JavacPhaseEvent.finished(runProcessorsStartedEvent, ImmutableMap.of()));
eventBus.post(StepEvent.finished(
StepEvent.started(stepShortName, stepDescription, stepUuid),
0));
eventBus.post(
BuildRuleEvent.finished(
rule,
BuildRuleKeys.of(ruleKey),
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty()));
try (final SimplePerfEvent.Scope scope1 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("planning"),
ImmutableMap.<String, Object>of("nefarious", "true"))) {
try (final SimplePerfEvent.Scope scope2 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("scheming"))) {
scope2.appendFinishedInfo("success", "false");
}
}
eventBus.post(BuildEvent.finished(buildEventStarted, 0));
eventBus.post(CommandEvent.finished(commandEventStarted, /* exitCode */ 0));
listener.outputTrace(new BuildId("BUILD_ID"));
File resultFile = new File(tmpDir.getRoot(), "buck-out/log/build.trace");
List<ChromeTraceEvent> originalResultList = mapper.readValue(
resultFile,
new TypeReference<List<ChromeTraceEvent>>() {});
List<ChromeTraceEvent> resultListCopy = new ArrayList<>();
resultListCopy.addAll(originalResultList);
ImmutableMap<String, String> emptyArgs = ImmutableMap.of();
assertNextResult(
resultListCopy,
"process_name",
ChromeTraceEvent.Phase.METADATA,
ImmutableMap.of("name", "buck"));
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("command_args", "arg1 arg2"));
assertNextResult(
resultListCopy,
"memory",
ChromeTraceEvent.Phase.COUNTER,
ImmutableMap.of(
"used_memory_mb", "2",
"free_memory_mb", "1",
"total_memory_mb", "3",
"time_spent_in_gc_sec", "0",
"pool_flower_mb", "42"));
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"rule_key", "abc123",
"success", "true",
"cache_result", "HTTP_HIT"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("rule_key", "abc123"));
// BuildRuleEvent.Started
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of());
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of(
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"success", "true",
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"description", "I'm a Fake Step!",
"exit_code", "0"));
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"cache_result", "miss",
"success_type", "BUILT_LOCALLY"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("nefarious", "true"));
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("success", "false"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"command_args", "arg1 arg2",
"daemon", "true"));
assertEquals(0, resultListCopy.size());
}
private static void assertNextResult(
List<ChromeTraceEvent> resultList,
String expectedName,
ChromeTraceEvent.Phase expectedPhase,
ImmutableMap<String, String> expectedArgs) {
assertTrue(resultList.size() > 0);
assertEquals(expectedName, resultList.get(0).getName());
assertEquals(expectedPhase, resultList.get(0).getPhase());
assertEquals(expectedArgs, resultList.get(0).getArgs());
resultList.remove(0);
}
@Test
public void testOutputFailed() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
assumeTrue("Can make the root directory read-only", tmpDir.getRoot().setReadOnly());
try {
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
fail("Expected an exception.");
} catch (HumanReadableException e) {
assertEquals(
"Unable to write trace file: java.nio.file.AccessDeniedException: " +
projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()),
e.getMessage());
} finally {
tmpDir.getRoot().setWritable(true);
}
}
@Test
public void outputFileUsesCurrentTime() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
false);
listener.outputTrace(invocationInfo.getBuildId());
assertTrue(
projectFilesystem.exists(
Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace")));
}
@Test
public void canCompressTraces() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
true);
listener.outputTrace(invocationInfo.getBuildId());
Path tracePath = Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace.gz");
assertTrue(projectFilesystem.exists(tracePath));
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(projectFilesystem.newFileInputStream(tracePath))));
List<?> elements = new Gson().fromJson(reader, List.class);
assertThat(elements, notNullValue());
}
}
|
Java
|
<?php
/**
* Budget delivery methods.
* @package Google_Api_Ads_AdWords_v201605
* @subpackage v201605
*/
class BudgetBudgetDeliveryMethod
{
const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
const XSI_TYPE = "Budget.BudgetDeliveryMethod";
/**
* 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()
{
}
}
|
Java
|
/*
* Copyright (C) 2016 CaMnter yuanyu.camnter@gmail.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.camnter.savevolley.network.adapter.core;
import com.camnter.savevolley.network.core.http.SaveHttpEntity;
/**
* Description:SaveHttpEntityAdapter
* Created by:CaMnter
* Time:2016-05-27 14:10
*/
public interface SaveHttpEntityAdapter<T> {
SaveHttpEntity adaptiveEntity(T t);
}
|
Java
|
# Install script for directory: /home/york/Program/MachineLearning/nn/two_spiral/src
# Set the install prefix
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
if(BUILD_TYPE)
string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
else()
set(CMAKE_INSTALL_CONFIG_NAME "")
endif()
message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()
# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
if(COMPONENT)
message(STATUS "Install component: \"${COMPONENT}\"")
set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
else()
set(CMAKE_INSTALL_COMPONENT)
endif()
endif()
# Install shared libraries without execute permission?
if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
set(CMAKE_INSTALL_SO_NO_EXE "0")
endif()
if(CMAKE_INSTALL_COMPONENT)
set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
else()
set(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
endif()
string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT
"${CMAKE_INSTALL_MANIFEST_FILES}")
file(WRITE "/home/york/Program/MachineLearning/nn/two_spiral/src/${CMAKE_INSTALL_MANIFEST}"
"${CMAKE_INSTALL_MANIFEST_CONTENT}")
|
Java
|
---
layout: base
title: 'Statistics of Definite in UD_French'
udver: '2'
---
## Treebank Statistics: UD_French: Features: `Definite`
This feature is universal.
It occurs with 2 different values: `Def`, `Ind`.
53514 tokens (13%) have a non-empty value of `Definite`.
29 types (0%) occur at least once with a non-empty value of `Definite`.
6 lemmas (0%) occur at least once with a non-empty value of `Definite`.
The feature is used with 1 part-of-speech tags: <tt><a href="fr-pos-DET.html">DET</a></tt> (53514; 13% instances).
### `DET`
53514 <tt><a href="fr-pos-DET.html">DET</a></tt> tokens (87% of all `DET` tokens) have a non-empty value of `Definite`.
The most frequent other feature values with which `DET` and `Definite` co-occurred: <tt><a href="fr-feat-PronType.html">PronType</a></tt><tt>=Art</tt> (53432; 100%), <tt><a href="fr-feat-Number.html">Number</a></tt><tt>=Sing</tt> (41368; 77%), <tt><a href="fr-feat-Gender.html">Gender</a></tt><tt>=Masc</tt> (28229; 53%).
`DET` tokens may have the following values of `Definite`:
* `Def` (43357; 81% of non-empty `Definite`): <em>le, la, les, l', the, l, là</em>
* `Ind` (10157; 19% of non-empty `Definite`): <em>un, une, des, de, d', telle, in</em>
* `EMPTY` (8225): <em>son, sa, cette, ses, ce, leur, ces, plusieurs, leurs, tous</em>
|
Java
|
---
layout: postag
title: 'INTJ'
shortdef: 'interjection'
---
### Definition
An interjection is a word that is used most often as an exclamation or
part of an exclamation. It typically expresses an emotional reaction,
is not syntactically related to other accompanying expressions, and
may include a combination of sounds not otherwise found in the
language.
### Examples
(Note that no direct translation of interjections is possible.
The approximate translations below are for orientation purposes and they
cannot serve to judge the part of speech from the English perspective.)
- _ах _ “oh”
- _ого _ “wow”
- _ну _ “well”
- _ради бога _ “for God's sake”
<!-- Interlanguage links updated St lis 3 20:58:10 CET 2021 -->
|
Java
|
# Plesioneuron translucens Holttum SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
#include <iostream>
#include <fstream>
#include "disassembly/flowgraph.hpp"
#include "disassembly/functionfeaturegenerator.hpp"
#include "searchbackend/functionsimhashfeaturedump.hpp"
// Writes a DOT file for a given graphlet.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const Flowgraph& graphlet) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.dot", hashA, hashB);
graphlet.WriteDot(std::string(buf));
}
// Writes a JSON file for a given MnemTuple.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const MnemTuple& tuple) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.json", hashA, hashB);
std::ofstream jsonfile;
jsonfile.open(std::string(buf));
jsonfile << "[ " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << ", "
<< std::get<2>(tuple) << " ]" << std::endl;
}
// Writes an immediate that was encountered.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, uint64_t
immediate) {
std::ofstream immediates;
immediates.open("/var/tmp/immediates.txt",
std::ofstream::out | std::ofstream::app);
immediates << std::hex << hashA << " " << hashB << " " << immediate
<< std::endl;
}
|
Java
|
/*******************************************************************************
* Copyright 2007-2013 See AUTHORS file.
*
* 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 xworker.dataObject.http;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
public class DataObjectHttpUtils {
/**
* 通过给定的DataObject从httpRequest中分析参数。
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object parseHttpRequestData(ActionContext actionContext){
DataObject theData = (DataObject) actionContext.get("theData");
Thing self = (Thing) actionContext.get("self");
if(theData == null){
theData = new DataObject(self);
}
HttpServletRequest request = (HttpServletRequest) actionContext.get("request");
Map paramMap = request.getParameterMap();
for(Thing attribute : self.getChilds("attribute")){
String name = attribute.getString("name");
if(paramMap.containsKey(name)){
theData.put(name, request.getParameter(name));
}else if("truefalse".equals(attribute.getString("inputtype"))){
//checkbox特殊处理
theData.put(name, "false");
}
}
return theData;
}
}
|
Java
|
/*
* Copyright 2000-2009 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.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 17.11.2006
* Time: 17:36:42
*/
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class PatchFileType implements FileType {
public static final PatchFileType INSTANCE = new PatchFileType();
public static final String NAME = "PATCH";
@NotNull
@NonNls
public String getName() {
return NAME;
}
@NotNull
public String getDescription() {
return VcsBundle.message("patch.file.type.description");
}
@NotNull
@NonNls
public String getDefaultExtension() {
return "patch";
}
@Nullable
public Icon getIcon() {
return AllIcons.Nodes.Pointcut;
}
public boolean isBinary() {
return false;
}
public boolean isReadOnly() {
return false;
}
@Nullable
@NonNls
public String getCharset(@NotNull VirtualFile file, final byte[] content) {
return null;
}
}
|
Java
|
.footer__text {
font-family: Nunito, sans-serif;
font-size: 20px;
color: black;
font-weight: 900;
line-height: 60px;
padding: 0px 00px;
margin: 0px;
text-align: center;
}
.footer__text-right {
text-align: center;
}
@media only screen and (min-width: 320px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 480px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 768px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 992px) {
.footer__text {
}
.footer__text-right {
float: right;
padding: 0px 10px 0px 0px;
}
}
@media only screen and (min-width: 1200px) {
.footer__text {
}
.footer__text-right {
}
}
|
Java
|
package io.ray.streaming.runtime.core.processor;
import io.ray.streaming.message.Record;
import io.ray.streaming.operator.SourceOperator;
/**
* The processor for the stream sources, containing a SourceOperator.
*
* @param <T> The type of source data.
*/
public class SourceProcessor<T> extends StreamProcessor<Record, SourceOperator<T>> {
public SourceProcessor(SourceOperator<T> operator) {
super(operator);
}
@Override
public void process(Record record) {
throw new UnsupportedOperationException("SourceProcessor should not process record");
}
public void fetch() {
operator.fetch();
}
@Override
public void close() {}
}
|
Java
|
<div class="row">
<div class="col-md-12 no-padding">
<div class="col-lg-4 col-md-12">
<?php
$this->renderPartial('pod/description',array( "project" => $project, "tags" => $tags, "countries" => $countries,"isAdmin"=> $admin)); ?>
</div>
<div class ="col-lg-4 col-md-12">
<?php
$this->renderPartial('../pod/sliderPhoto', array("itemId" => (string)$project["_id"], "type" => PHType::TYPE_PROJECTS, "isAdmin"=> $admin));
?>
</div>
<div class ="col-lg-4 col-md-12">
<?php $this->renderPartial('pod/contributors',array( "contributors" => $contributors, "organizationTypes" => $organizationTypes, "project" => $project, "admin" => $admin)); ?>
</div>
</div>
<?php if (!empty($tasks) OR $admin==true){ ?>
<div class ="col-lg-8 col-md-8 timesheetphp">
</div>
<?php }
if (!empty($properties) OR $admin==true){ ?>
<div class ="col-lg-4 col-md-12">
<?php $this->renderPartial('pod/projectChart',array("itemId" => (string)$project["_id"], "properties" => $properties, "admin" =>$admin)); ?>
</div>
<?php } ?>
<div class="col-sm-6 col-xs-12 roomsPod">
<div class="panel panel-white pulsate">
<div class="panel-heading border-light ">
<h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Rooms Section</h4>
<div class="space5"></div>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12 needsPod">
<!--<div class="panel panel-white pulsate">
<div class="panel-heading border-light ">
<h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Something Section</h4>
<div class="space5"></div>
</div>
</div>-->
</div>
<div class="col-sm-6 col-xs-12">
<?php $this->renderPartial('../pod/eventsList',array( "events" => $events,
"contextId" => (String) $project["_id"],
"contextType" => Project::CONTROLLER,
"authorised" => $admin
)); ?>
</div>
</div>
<?php $this->renderPartial('/sig/generic/mapLibs'); ?>
<script type="text/javascript">
var contextMap = {};
contextMap["project"] = <?php echo json_encode($project)?>;
//contextMap["events"] = <?php //echo json_encode($events) ?>;
var idToSend = contextMap["project"]["_id"]["$id"]
contextMap["people"] = <?php echo json_encode($people) ?>;
contextMap["organizations"] = <?php echo json_encode($organizations) ?>;
var images = <?php echo json_encode($images) ?>;
var contentKeyBase = "<?php echo $contentKeyBase ?>";
jQuery(document).ready(function() {
bindBtnFollow();
getAjax(".roomsPod",baseUrl+"/"+moduleId+"/rooms/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>",null,"html");
getAjax(".timesheetphp",baseUrl+"/"+moduleId+"/gantt/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html");
getAjax(".needsPod",baseUrl+"/"+moduleId+"/needs/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html");
})
function bindBtnFollow(){
$(".disconnectBtn").off().on("click",function () {
$(this).empty();
$(this).html('<i class=" disconnectBtnIcon fa fa-spinner fa-spin"></i>');
var btnClick = $(this);
var idToDisconnect = $(this).data("id");
var typeToDisconnect = $(this).data("type");
var ownerLink = $(this).data("ownerlink");
var urlToSend = baseUrl+"/"+moduleId+"/person/disconnect/id/"+idToDisconnect+"/type/"+typeToDisconnect+"/ownerLink/"+ownerLink;
if("undefined" != typeof $(this).data("targetlink")){
var targetLink = $(this).data("targetlink");
urlToSend += "/targetLink/"+targetLink;
}
bootbox.confirm("Are you sure you want to delete <span class='text-red'>"+$(this).data("name")+"</span> connection ?",
function(result) {
if (!result) {
btnClick.empty();
btnClick.html('<i class=" disconnectBtnIcon fa fa-unlink"></i>');
return;
}
$.ajax({
type: "POST",
url: urlToSend,
dataType : "json"
})
.done(function (data)
{
if ( data && data.result ) {
toastr.info("LINK DIVORCED SUCCESFULLY!!");
$("#"+typeToDisconnect+idToDisconnect).remove();
$("#linkBtns").empty();
$("#linkBtns").html("<a href='javascript:;' class='connectBtn tooltips ' id='addAttendingRelation' data-placement='top' data-ownerlink='"+ownerLink+"' data-original-title='I contribute to this event' ><i class=' connectBtnIcon fa fa-link '></i>CONTRIBUTE</a></li>");
bindBtnFollow();
} else {
toastr.info("something went wrong!! please try again.");
$(".disconnectBtn").removeClass("fa-spinner fa-spin").addClass("fa-link");
}
});
});
});
$(".connectBtn").off().on("click",function () {
$(".connectBtnIcon").removeClass("fa-link").addClass("fa-spinner fa-spin");
var idConnect = "<?php echo (string)$project['_id'] ?>";
var ownerLink = $(this).data("ownerlink");
var urlToSend = baseUrl+"/"+moduleId+"/person/follows/id/"+idConnect+"/type/<?php echo Project::COLLECTION ?>/ownerLink/"+ownerLink;
if("undefined" != typeof $(this).data("targetlink")){
var targetLink = $(this).data("targetlink");
urlToSend += "/targetLink/"+targetLink;
}
$.ajax({
type: "POST",
url: urlToSend,
dataType : "json"
})
.done(function (data)
{
if ( data && data.result ) {
toastr.info("REALTION APPLIED SUCCESFULLY!! ");
$(".connectBtn").fadeOut();
$("#linkBtns").empty();
$("#linkBtns").html("<a href='javascript:;' class='disconnectBtn text-red tooltips' data-name='"+contextMap["project"]["name"]+" 'data-id='"+contextMap["project"]["_id"]["$id"]+"' data-type='<?php echo Project::COLLECTION ?>' data-ownerlink='"+ownerLink+"' data-placement='top' data-original-title='I no more contributing' ><i class='disconnectBtnIcon fa fa-unlink'></i>UNCONTRIBUTE</a>")
bindBtnFollow();
} else {
toastr.info("something went wrong!! please try again.");
$(".connectBtnIcon").removeClass("fa-spinner fa-spin").addClass("fa-link");
}
});
});
}
</script>
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<span>Time:</span>
<ul>
<li>From controller: ${time}</li>
<li>From Beetl</li>
</ul>
<span>Message: ${message}</span>
<span>submit: ${submit}</span>
</body>
</html>
|
Java
|
/**
* Copyright 2012-2015 Niall Gallagher
*
* 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.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.mockito.Mockito.*;
/**
* Tests for {@link PartialSortedKeyStatisticsAttributeIndex}.
*
* @author niall.gallagher
*/
public class PartialSortedKeyStatisticsAttributeIndexTest {
@Test
public void testGetDistinctKeys1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(noQueryOptions());
}
@Test
public void testGetDistinctKeys2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeysDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValues1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(noQueryOptions());
}
@Test
public void testGetKeysAndValues2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetCountForKey() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountForKey(1, noQueryOptions());
verify(backingIndex, times(1)).getCountForKey(1, noQueryOptions());
}
@Test
public void testGetCountOfDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountOfDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getCountOfDistinctKeys(noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeys(noQueryOptions());
}
static PartialSortedKeyStatisticsAttributeIndex<Integer, Car> wrapWithPartialIndex(final SortedKeyStatisticsAttributeIndex<Integer, Car> mockedBackingIndex) {
return new PartialSortedKeyStatisticsAttributeIndex<Integer, Car>(Car.CAR_ID, QueryFactory.between(Car.CAR_ID, 2, 5)) {
@Override
protected SortedKeyStatisticsAttributeIndex<Integer, Car> createBackingIndex() {
return mockedBackingIndex;
}
};
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() {
return mock(SortedKeyStatisticsAttributeIndex.class);
}
}
|
Java
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.common.policy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.lang.Validate;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordLifeTimeType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
*
* @author mamut
*
*/
public class PasswordPolicyUtils {
private static final transient Trace LOGGER = TraceManager.getTrace(PasswordPolicyUtils.class);
private static final String DOT_CLASS = PasswordPolicyUtils.class.getName() + ".";
private static final String OPERATION_PASSWORD_VALIDATION = DOT_CLASS + "passwordValidation";
/**
* add defined default values
*
* @param pp
* @return
*/
public static void normalize(ValuePolicyType pp) {
if (null == pp) {
throw new IllegalArgumentException("Password policy cannot be null");
}
if (null == pp.getStringPolicy()) {
StringPolicyType sp = new StringPolicyType();
pp.setStringPolicy(StringPolicyUtils.normalize(sp));
} else {
pp.setStringPolicy(StringPolicyUtils.normalize(pp.getStringPolicy()));
}
if (null == pp.getLifetime()) {
PasswordLifeTimeType lt = new PasswordLifeTimeType();
lt.setExpiration(-1);
lt.setWarnBeforeExpiration(0);
lt.setLockAfterExpiration(0);
lt.setMinPasswordAge(0);
lt.setPasswordHistoryLength(0);
}
return;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param policies
* - Password List of policies used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, List <ValuePolicyType> policies, OperationResult result) {
boolean ret=true;
//iterate through policies
for (ValuePolicyType pp: policies) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(String password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password, pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(ProtectedStringType password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password.getClearValue(), pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, ValuePolicyType pp, OperationResult result) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
return op.isSuccess();
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used
* @return - Operation result of this validation
*/
public static OperationResult validatePassword(String password, ValuePolicyType pp) {
// check input params
// if (null == pp) {
// throw new IllegalArgumentException("No policy provided: NULL");
// }
//
// if (null == password) {
// throw new IllegalArgumentException("Password for validaiton is null.");
// }
Validate.notNull(pp, "Password policy must not be null.");
Validate.notNull(password, "Password to validate must not be null.");
OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
ret.addParam("policyName", pp.getName());
normalize(pp);
LimitationsType lims = pp.getStringPolicy().getLimitations();
StringBuilder message = new StringBuilder();
// Test minimal length
if (lims.getMinLength() == null){
lims.setMinLength(0);
}
if (lims.getMinLength() > password.length()) {
String msg = "Required minimal size (" + lims.getMinLength() + ") of password is not met (password length: "
+ password.length() + ")";
ret.addSubresult(new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal length
if (lims.getMaxLength() != null) {
if (lims.getMaxLength() < password.length()) {
String msg = "Required maximal size (" + lims.getMaxLength()
+ ") of password was exceeded (password length: " + password.length() + ").";
ret.addSubresult(new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// Test uniqueness criteria
HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
if (lims.getMinUniqueChars() != null) {
if (lims.getMinUniqueChars() > tmp.size()) {
String msg = "Required minimal count of unique characters ("
+ lims.getMinUniqueChars()
+ ") in password are not met (unique characters in password " + tmp.size() + ")";
ret.addSubresult(new OperationResult("Check minimal count of unique chars",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult(
// "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// check limitation
HashSet<String> allValidChars = new HashSet<String>(128);
ArrayList<String> validChars = null;
ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);
if (lims.getLimit() == null || lims.getLimit().isEmpty()){
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
for (StringLimitType l : lims.getLimit()) {
OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
if (null != l.getCharacterClass().getValue()) {
validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
} else {
validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(pp
.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
}
// memorize validChars
allValidChars.addAll(validChars);
// Count how many character for this limitation are there
int count = 0;
for (String s : passwd) {
if (validChars.contains(s)) {
count++;
}
}
// Test minimal occurrence
if (l.getMinOccurs() == null){
l.setMinOccurs(0);
}
if (l.getMinOccurs() > count) {
String msg = "Required minimal occurrence (" + l.getMinOccurs()
+ ") of characters ("+l.getDescription()+") in password is not met (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal occurrence
if (l.getMaxOccurs() != null) {
if (l.getMaxOccurs() < count) {
String msg = "Required maximal occurrence (" + l.getMaxOccurs()
+ ") of characters ("+l.getDescription()+") in password was exceeded (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult(
// "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
// "PASSED"));
// }
}
// test if first character is valid
if (l.isMustBeFirst() == null){
l.setMustBeFirst(false);
}
if (l.isMustBeFirst() && !validChars.contains(password.substring(0, 1))) {
String msg = "First character is not from allowed set. Allowed set: "
+ validChars.toString();
limitResult.addSubresult(new OperationResult("Check valid first char",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
limitResult.computeStatus();
ret.addSubresult(limitResult);
}
// Check if there is no invalid character
StringBuilder sb = new StringBuilder();
for (String s : passwd) {
if (!allValidChars.contains(s)) {
// memorize all invalid characters
sb.append(s);
}
}
if (sb.length() > 0) {
String msg = "Characters [ " + sb
+ " ] are not allowed to be use in password";
ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
}
|
Java
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Manifest, type: :model do
let(:monograph) do
create(:public_monograph) do |m|
m.ordered_members << file_set
m.save!
m
end
end
let(:file_set) do
create(:public_file_set) do |f|
f.original_file = original_file
f.save!
f
end
end
let(:original_file) do
Hydra::PCDM::File.new do |f|
f.content = File.open(File.join(fixture_path, 'kitty.tif'))
f.original_name = 'kitty.tif'
f.mime_type = 'image/tiff'
f.file_size = File.size(File.join(fixture_path, 'kitty.tif'))
f.width = 200
f.height = 150
end
end
let(:current_user) { create(:platform_admin) }
# NOTE: #create is dependent on Carrierwave and was not tested.
before do
allow($stdout).to receive(:puts) # Don't print status messages during specs
end
it 'no csv file' do
implicit = described_class.from_monograph(monograph.id)
expect(implicit.id).to eq monograph.id
expect(implicit.persisted?).to be false
expect(implicit.filename).to be nil
explicit = described_class.from_monograph_manifest(monograph.id)
expect(explicit.id).to eq monograph.id
expect(explicit.persisted?).to be false
expect(explicit.filename).to be nil
expect(implicit == explicit).to be false
end
it 'csv file' do
implicit = described_class.from_monograph(monograph.id)
file_dir = implicit.csv.store_dir
FileUtils.mkdir_p(file_dir) unless Dir.exist?(file_dir)
FileUtils.rm_rf(Dir.glob("#{file_dir}/*"))
file_name = "#{monograph.id}.csv"
file_path = File.join(file_dir, file_name)
file = File.new(file_path, "w")
exporter = Export::Exporter.new(monograph.id)
file.write(exporter.export)
file.close
expect(implicit.persisted?).to be true
expect(implicit.filename).to eq file_name
explicit = described_class.from_monograph_manifest(monograph.id)
expect(explicit.persisted?).to be true
expect(explicit.filename).to eq file_name
expect(implicit == explicit).to be true
expect(explicit.table_rows.count).to eq 2
expect(explicit.table_rows[0].count).to eq 4
expect(explicit.table_rows[0][3]["title"].first).to eq monograph.title.first
explicit.table_rows[0][3]["title"] = ["NEW TITLE"]
expect(implicit == explicit).to be false
explicit.destroy(current_user)
expect(implicit.id).to eq monograph.id
expect(implicit.persisted?).to be false
expect(implicit.filename).to be nil
expect(explicit.id).to eq monograph.id
expect(explicit.persisted?).to be false
expect(explicit.filename).to be nil
end
end
|
Java
|
/* Copyright 2018 The TensorFlow 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.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.linalg;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.family.TType;
/**
* Returns the batched diagonal part of a batched tensor.
* Returns a tensor with the {@code k[0]}-th to {@code k[1]}-th diagonals of the batched
* {@code input}.
* <p>Assume {@code input} has {@code r} dimensions {@code [I, J, ..., L, M, N]}.
* Let {@code max_diag_len} be the maximum length among all diagonals to be extracted,
* {@code max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))}
* Let {@code num_diags} be the number of diagonals to extract,
* {@code num_diags = k[1] - k[0] + 1}.
* <p>If {@code num_diags == 1}, the output tensor is of rank {@code r - 1} with shape
* {@code [I, J, ..., L, max_diag_len]} and values:
* <pre>
* diagonal[i, j, ..., l, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code y = max(-k[1], 0)}, {@code x = max(k[1], 0)}.
* <p>Otherwise, the output tensor has rank {@code r} with dimensions
* {@code [I, J, ..., L, num_diags, max_diag_len]} with values:
* <pre>
* diagonal[i, j, ..., l, m, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code d = k[1] - m}, {@code y = max(-d, 0)}, and {@code x = max(d, 0)}.
* <p>The input must be at least a matrix.
* <p>For example:
* <pre>
* input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)
* [5, 6, 7, 8],
* [9, 8, 7, 6]],
* [[5, 4, 3, 2],
* [1, 2, 3, 4],
* [5, 6, 7, 8]]])
*
* # A main diagonal from each batch.
* tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)
* [5, 2, 7]]
*
* # A superdiagonal from each batch.
* tf.matrix_diag_part(input, k = 1)
* ==> [[2, 7, 6], # Output shape: (2, 3)
* [4, 3, 8]]
*
* # A tridiagonal band from each batch.
* tf.matrix_diag_part(input, k = (-1, 1))
* ==> [[[2, 7, 6], # Output shape: (2, 3, 3)
* [1, 6, 7],
* [5, 8, 0]],
* [[4, 3, 8],
* [5, 2, 7],
* [1, 6, 0]]]
*
* # Padding value = 9
* tf.matrix_diag_part(input, k = (1, 3), padding_value = 9)
* ==> [[[4, 9, 9], # Output shape: (2, 3, 3)
* [3, 8, 9],
* [2, 7, 6]],
* [[2, 9, 9],
* [3, 4, 9],
* [4, 3, 8]]]
* </pre>
*
* @param <T> data type for {@code diagonal} output
*/
@OpMetadata(
opType = MatrixDiagPart.OP_NAME,
inputsClass = MatrixDiagPart.Inputs.class
)
@Operator(
group = "linalg"
)
public final class MatrixDiagPart<T extends TType> extends RawOp implements Operand<T> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "MatrixDiagPartV2";
private Output<T> diagonal;
public MatrixDiagPart(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
diagonal = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new MatrixDiagPartV2 operation.
*
* @param scope current scope
* @param input Rank {@code r} tensor where {@code r >= 2}.
* @param k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
* @param paddingValue The value to fill the area outside the specified diagonal band with.
* Default is 0.
* @param <T> data type for {@code MatrixDiagPartV2} output and operands
* @return a new instance of MatrixDiagPart
*/
@Endpoint(
describeByClass = true
)
public static <T extends TType> MatrixDiagPart<T> create(Scope scope, Operand<T> input,
Operand<TInt32> k, Operand<T> paddingValue) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "MatrixDiagPart");
opBuilder.addInput(input.asOutput());
opBuilder.addInput(k.asOutput());
opBuilder.addInput(paddingValue.asOutput());
return new MatrixDiagPart<>(opBuilder.build());
}
/**
* Gets diagonal.
* The extracted diagonal(s).
* @return diagonal.
*/
public Output<T> diagonal() {
return diagonal;
}
@Override
public Output<T> asOutput() {
return diagonal;
}
@OpInputsMetadata(
outputsClass = MatrixDiagPart.class
)
public static class Inputs<T extends TType> extends RawOpInputs<MatrixDiagPart<T>> {
/**
* Rank {@code r} tensor where {@code r >= 2}.
*/
public final Operand<T> input;
/**
* Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
*/
public final Operand<TInt32> k;
/**
* The value to fill the area outside the specified diagonal band with.
* Default is 0.
*/
public final Operand<T> paddingValue;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new MatrixDiagPart<>(op), op, Arrays.asList("T"));
int inputIndex = 0;
input = (Operand<T>) op.input(inputIndex++);
k = (Operand<TInt32>) op.input(inputIndex++);
paddingValue = (Operand<T>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
}
}
}
|
Java
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP Development Team
*
* 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.zaproxy.zap.control;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.junit.jupiter.api.Test;
import org.zaproxy.zap.control.AddOn.BundleData;
import org.zaproxy.zap.control.AddOn.HelpSetData;
import org.zaproxy.zap.control.AddOn.ValidationResult;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
/** Unit test for {@link AddOn}. */
class AddOnUnitTest extends AddOnTestUtils {
private static final File ZAP_VERSIONS_XML =
getResourcePath("ZapVersions-deps.xml", AddOnUnitTest.class).toFile();
@Test
void testAlpha2UpdatesAlpha1() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnA1));
}
@Test
void testAlpha1DoesNotUpdateAlpha2() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "1"));
assertFalse(addOnA1.isUpdateTo(addOnA2));
}
@Test
void testAlpha2UpdatesBeta1() throws Exception {
AddOn addOnB1 = new AddOn(createAddOnFile("test-beta-1.zap", "beta", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnB1));
}
@Test
void testAlpha2DoesNotUpdateTestyAlpha1() throws Exception {
// Given
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("testy-alpha-2.zap", "alpha", "1"));
// When
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> addOnA2.isUpdateTo(addOnA1));
// Then
assertThat(e.getMessage(), containsString("Different addons"));
}
@Test
void shouldBeUpdateIfSameVersionWithHigherStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOnHigherStatus.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfSameVersionWithLowerStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOn.isUpdateTo(addOnHigherStatus);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfFileIsNewerWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = newestAddOn.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfFileIsOlderWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = addOn.isUpdateTo(newestAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfOtherAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOn.isUpdateTo(addOnWithoutFile);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfCurrentAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOnWithoutFile.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void testCanLoadAddOnNotBefore() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertFalse(ao.canLoadInVersion("1.4.0"));
assertFalse(ao.canLoadInVersion("2.0.alpha"));
}
@Test
void testCanLoadAddOnNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
ao.setNotFromVersion("2.8.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.8.0"));
assertFalse(ao.canLoadInVersion("2.8.0.1"));
assertFalse(ao.canLoadInVersion("2.9.0"));
}
@Test
void testCanLoadAddOnNotBeforeNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotFromVersion("2.7.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.6.0"));
assertFalse(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.7.0.1"));
assertFalse(ao.canLoadInVersion("2.8.0"));
}
@Test
void shouldNotBeAddOnFileNameIfNull() throws Exception {
// Given
String fileName = null;
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnFileNameIfNotEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.txt";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldBeAddOnFileNameIfEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.zap";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldBeAddOnFileNameEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
String fileName = "addon.ZAP";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldNotBeAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfFileNameNotEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.txt", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfAddOnDoesNotHaveManifestFile() throws Exception {
// Given
Path file = createEmptyAddOnFile("addon.zap");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldBeAddOnIfPathEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldBeAddOnEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
Path file = createAddOnFile("addon.ZAP", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfPathHasNoFileName() throws Exception {
// Given
Path file = Paths.get("/");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfFileDoesNotHaveZapExtension() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zip"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_FILE_NAME)));
}
@Test
void shouldNotBeValidAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNotReadable() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
assumeTrue(
Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class),
"Test requires support for POSIX file attributes.");
Set<PosixFilePermission> perms =
Files.readAttributes(file, PosixFileAttributes.class).permissions();
perms.remove(PosixFilePermission.OWNER_READ);
Files.setPosixFilePermissions(file, perms);
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfNotZipFile() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(
result.getValidity(), is(equalTo(ValidationResult.Validity.UNREADABLE_ZIP_FILE)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfItHasNoManifest() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry("Not a manifest"));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.MISSING_MANIFEST)));
}
@Test
void shouldNotBeValidAddOnIfManifestIsMalformed() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry(AddOn.MANIFEST_FILE_NAME));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_MANIFEST)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfHasMissingLib() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>missing.jar</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldNotBeValidAddOnIfHasLibWithMissingName() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>dir/</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldBeValidAddOnIfValid() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.VALID)));
assertThat(result.getManifest(), is(notNullValue()));
}
@Test
void shouldFailToCreateAddOnFromNullFile() {
// Given
Path file = null;
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_PATH.name()));
}
@Test
void shouldFailToCreateAddOnFromFileWithInvalidFileName() throws Exception {
// Given
String invalidFileName = "addon.txt";
Path file = createAddOnFile(invalidFileName, "alpha", "1");
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_FILE_NAME.name()));
}
@Test
@SuppressWarnings("deprecation")
void shouldCreateAddOnFromFileAndUseManifestData() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "beta", "1.6.7");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.beta)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.6.7")));
assertThat(addOn.getFileVersion(), is(equalTo(1)));
}
@Test
void shouldCreateAddOnWithDotsInId() throws Exception {
// Given
Path file = createAddOnFile("addon.x.zap", "release", "1.0.0");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon.x")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.0.0")));
}
@Test
void shouldIgnoreStatusInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha.zap", "release", "1");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
}
@Test
@SuppressWarnings("deprecation")
void shouldIgnoreVersionInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha-2.zap", "alpha", "3.2.10");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getVersion().toString(), is(equalTo("3.2.10")));
assertThat(addOn.getFileVersion(), is(equalTo(3)));
}
@Test
void shouldReturnNormalisedFileName() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "2.8.1");
AddOn addOn = new AddOn(file);
// When
String normalisedFileName = addOn.getNormalisedFileName();
// Then
assertThat(normalisedFileName, is(equalTo("addon-2.8.1.zap")));
}
@Test
void shouldHaveNoReleaseDate() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
String releaseDate = addOn.getReleaseDate();
// Then
assertThat(releaseDate, is(nullValue()));
}
@Test
void shouldHaveCorrectSize() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
long size = addOn.getSize();
// Then
assertThat(size, is(equalTo(189L)));
}
@Test
void shouldHaveEmptyBundleByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(true)));
assertThat(bundleData.getBaseName(), is(equalTo("")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundle() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle>")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundleWithPrefix() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle prefix=\"msgs\">")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("msgs")));
}
@Test
void shouldHaveEmptyHelpSetByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(true)));
assertThat(helpSetData.getBaseName(), is(equalTo("")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSet() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset>")
.append("org.zaproxy.help.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSetWithLocaleToken() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset localetoken=\"%LC%\">")
.append("org.zaproxy.help%LC%.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help%LC%.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("%LC%")));
}
@Test
void shouldDependOnDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(dependency);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDependIfNoDependencies() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("AddOn-release-1.zap", "release", "1"));
AddOn nonDependency = createAddOn("AddOn3", createZapVersionsXml());
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDirectDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnItSelf() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn sameAddOn = createAddOn("AddOn1", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(sameAddOn);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldDependOnDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, dependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, nonDirectDependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency1 = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency2 = createAddOn("AddOn9", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency1, nonDependency2});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldBeUpdateToOlderVersionIfNewer() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = newerAddOn.isUpdateTo(olderAddOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateToNewerVersionIfOlder() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = olderAddOn.isUpdateTo(newerAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeAbleToRunIfItHasNoMinimumJavaVersion() throws Exception {
// Given
String minimumJavaVersion = null;
String runningJavaVersion = "1.8";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MajorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MinorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldNotBeAbleToRunInJava9MajorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldNotBeAbleToRunInJava9MinorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldReturnLibsInManifest() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "dir/lib2.jar";
Path file = createAddOnWithLibs(lib1, lib2);
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getLibs(), contains(new AddOn.Lib(lib1), new AddOn.Lib(lib2)));
}
@Test
void shouldNotBeRunnableIfLibsAreNotInFileSystem() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnWithLibs("lib1.jar", "lib2.jar"));
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(false)));
assertThat(reqs.hasMissingLibs(), is(equalTo(true)));
assertThat(reqs.getAddOnMissingLibs(), is(equalTo(addOn)));
}
@Test
void shouldBeRunnableIfLibsAreInFileSystem() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "lib2.jar";
AddOn addOn = new AddOn(createAddOnWithLibs(lib1, lib2));
Path libsDir = newTempDir("libsDir");
addOn.getLibs().get(0).setFileSystemUrl(libsDir.resolve(lib1).toUri().toURL());
addOn.getLibs().get(1).setFileSystemUrl(libsDir.resolve(lib2).toUri().toURL());
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(true)));
assertThat(reqs.hasMissingLibs(), is(equalTo(false)));
assertThat(reqs.getAddOnMissingLibs(), is(nullValue()));
}
@Test
void shouldCreateAddOnLibFromRootJarPath() throws Exception {
// Given
String jarPath = "lib.jar";
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(jarPath)));
}
@Test
void shouldCreateAddOnLibFromNonRootJarPath() throws Exception {
// Given
String name = "lib.jar";
String jarPath = "dir/" + name;
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(name)));
}
@Test
void shouldNotHaveFileSystemUrlInAddOnLibByDefault() throws Exception {
// Given / When
AddOn.Lib lib = new AddOn.Lib("lib.jar");
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
@Test
void shouldSetFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
URL fsUrl = new URL("file:///some/path");
// When
lib.setFileSystemUrl(fsUrl);
// Then
assertThat(lib.getFileSystemUrl(), is(equalTo(fsUrl)));
}
@Test
void shouldSetNullFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
lib.setFileSystemUrl(new URL("file:///some/path"));
// When
lib.setFileSystemUrl(null);
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
private static ZapXmlConfiguration createZapVersionsXml() throws Exception {
ZapXmlConfiguration zapVersionsXml = new ZapXmlConfiguration(ZAP_VERSIONS_XML);
zapVersionsXml.setExpressionEngine(new XPathExpressionEngine());
return zapVersionsXml;
}
}
|
Java
|
package com.qinyadan.monitor.network.util;
import java.util.Map;
import com.qinyadan.monitor.network.control.ControlMessageDecoder;
import com.qinyadan.monitor.network.control.ControlMessageEncoder;
import com.qinyadan.monitor.network.control.ProtocolException;
public final class ControlMessageEncodingUtils {
private static final ControlMessageEncoder encoder = new ControlMessageEncoder();
private static final ControlMessageDecoder decoder = new ControlMessageDecoder();
private ControlMessageEncodingUtils() {
}
public static byte[] encode(Map<String, Object> value) throws ProtocolException {
return encoder.encode(value);
}
public static Object decode(byte[] in) throws ProtocolException {
return decoder.decode(in);
}
}
|
Java
|
<h2>Ask a question:</h2>
<div class="question-form">
<mat-form-field>
<mat-label>Your question:</mat-label>
<textarea
maxlength="280"
style="height: 120px;"
required
matInput
#q
(keydown.control.enter)="addQuestion(q)"
(keydown.command.enter)="addQuestion(q)"
></textarea>
</mat-form-field>
<button
mat-raised-button
[disabled]="q.value.trim() === ''"
(click)="addQuestion(q)"
>
Submit
</button>
</div>
<ng-container *ngIf="questionsService.requireApproval$ | async">
<ng-container
*ngIf="questionsService.myUnapprovedQuestions$ | async as unapproved"
>
<mat-expansion-panel *ngIf="unapproved.length">
<mat-expansion-panel-header>
<mat-panel-title>
Your questions pending approval: {{ unapproved.length }}
</mat-panel-title>
</mat-expansion-panel-header>
<ng-container *ngFor="let question of unapproved">
<codelab-question
[question]="question"
[showControls]="false"
></codelab-question>
</ng-container>
</mat-expansion-panel>
</ng-container>
</ng-container>
<ng-container *ngIf="questionsService.publicQuestions$ | async as questions">
<ng-container *ngIf="questions.length">
<h2>All questions:</h2>
<codelab-question
*ngIf="questionsService.starredQuestion$ | async as question"
tabindex="0"
[question]="question"
class="starred"
></codelab-question>
<codelab-question-list [questions]="questions"></codelab-question-list>
</ng-container>
</ng-container>
|
Java
|
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone;
Alloy.Globals.steps = 0;
Alloy.Globals.capacity = 0;
Alloy.Globals.basketImage = "";
Alloy.Globals.fruitCount = 0;
Alloy.createController("index");
|
Java
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.specificmodels.tests.testsourcemodel.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import de.hub.specificmodels.tests.testsourcemodel.ClassWithListFeatures;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass1;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass2;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass3;
import de.hub.specificmodels.tests.testsourcemodel.RootClass;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelFactory;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class TestSourceModelPackageImpl extends EPackageImpl implements TestSourceModelPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass rootClassEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass classWithListFeaturesEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass1EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass2EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass3EClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage#eNS_URI
* @see #init()
* @generated
*/
private TestSourceModelPackageImpl() {
super(eNS_URI, TestSourceModelFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link TestSourceModelPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static TestSourceModelPackage init() {
if (isInited) return (TestSourceModelPackage)EPackage.Registry.INSTANCE.getEPackage(TestSourceModelPackage.eNS_URI);
// Obtain or create and register package
TestSourceModelPackageImpl theTestSourceModelPackage = (TestSourceModelPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof TestSourceModelPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new TestSourceModelPackageImpl());
isInited = true;
// Create package meta-data objects
theTestSourceModelPackage.createPackageContents();
// Initialize created meta-data
theTestSourceModelPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theTestSourceModelPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(TestSourceModelPackage.eNS_URI, theTestSourceModelPackage);
return theTestSourceModelPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRootClass() {
return rootClassEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_AnAttribute1() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NormalReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_Any() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NonManyReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getClassWithListFeatures() {
return classWithListFeaturesEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature1() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature2() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getClassWithListFeatures_AnAttribute1() {
return (EAttribute)classWithListFeaturesEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass1() {
return listFeatureElementClass1EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Name() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getListFeatureElementClass1_ListFeature3() {
return (EReference)listFeatureElementClass1EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_AnAttributeOfFeatureClass1() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Any() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass2() {
return listFeatureElementClass2EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_Name() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_AnAttributeOfFeatureClass2() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass3() {
return listFeatureElementClass3EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_Name() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_AnAttributeOfFeatureClass3() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TestSourceModelFactory getTestSourceModelFactory() {
return (TestSourceModelFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
rootClassEClass = createEClass(ROOT_CLASS);
createEAttribute(rootClassEClass, ROOT_CLASS__AN_ATTRIBUTE1);
createEReference(rootClassEClass, ROOT_CLASS__NORMAL_REFERENCE);
createEAttribute(rootClassEClass, ROOT_CLASS__ANY);
createEReference(rootClassEClass, ROOT_CLASS__NON_MANY_REFERENCE);
classWithListFeaturesEClass = createEClass(CLASS_WITH_LIST_FEATURES);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE1);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE2);
createEAttribute(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__AN_ATTRIBUTE1);
listFeatureElementClass1EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__NAME);
createEReference(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__LIST_FEATURE3);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__AN_ATTRIBUTE_OF_FEATURE_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__ANY);
listFeatureElementClass2EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS2);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__NAME);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__AN_ATTRIBUTE_OF_FEATURE_CLASS2);
listFeatureElementClass3EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS3);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__NAME);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__AN_ATTRIBUTE_OF_FEATURE_CLASS3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
// Initialize classes and features; add operations and parameters
initEClass(rootClassEClass, RootClass.class, "RootClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getRootClass_AnAttribute1(), ecorePackage.getEString(), "anAttribute1", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NormalReference(), this.getClassWithListFeatures(), null, "normalReference", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRootClass_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NonManyReference(), this.getClassWithListFeatures(), null, "nonManyReference", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(classWithListFeaturesEClass, ClassWithListFeatures.class, "ClassWithListFeatures", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getClassWithListFeatures_ListFeature1(), this.getListFeatureElementClass1(), null, "listFeature1", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getClassWithListFeatures_ListFeature2(), this.getListFeatureElementClass2(), null, "listFeature2", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getClassWithListFeatures_AnAttribute1(), ecorePackage.getEInt(), "anAttribute1", null, 0, 1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass1EClass, ListFeatureElementClass1.class, "ListFeatureElementClass1", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass1_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getListFeatureElementClass1_ListFeature3(), this.getListFeatureElementClass3(), null, "listFeature3", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_AnAttributeOfFeatureClass1(), ecorePackage.getEString(), "anAttributeOfFeatureClass1", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass2EClass, ListFeatureElementClass2.class, "ListFeatureElementClass2", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass2_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass2_AnAttributeOfFeatureClass2(), ecorePackage.getEString(), "anAttributeOfFeatureClass2", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass3EClass, ListFeatureElementClass3.class, "ListFeatureElementClass3", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass3_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass3_AnAttributeOfFeatureClass3(), ecorePackage.getEString(), "anAttributeOfFeatureClass3", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create resource
createResource(eNS_URI);
// Create annotations
// http:///org/eclipse/emf/ecore/util/ExtendedMetaData
createExtendedMetaDataAnnotations();
}
/**
* Initializes the annotations for <b>http:///org/eclipse/emf/ecore/util/ExtendedMetaData</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void createExtendedMetaDataAnnotations() {
String source = "http:///org/eclipse/emf/ecore/util/ExtendedMetaData";
addAnnotation
(getRootClass_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
addAnnotation
(getListFeatureElementClass1_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
}
} //TestSourceModelPackageImpl
|
Java
|
/*
* Copyright 2000-2009 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.refactoring.typeCook.deductive.util;
import com.intellij.psi.*;
import com.intellij.refactoring.typeCook.Settings;
import com.intellij.refactoring.typeCook.Util;
import java.util.HashSet;
/**
* @author db
*/
public class VictimCollector extends Visitor {
final HashSet<PsiElement> myVictims = new HashSet<PsiElement>();
final PsiElement[] myElements;
final Settings mySettings;
public VictimCollector(final PsiElement[] elements, final Settings settings) {
myElements = elements;
mySettings = settings;
}
private void testNAdd(final PsiElement element, final PsiType t) {
if (Util.isRaw(t, mySettings)) {
if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){
return;
}
myVictims.add(element);
}
}
@Override public void visitLocalVariable(final PsiLocalVariable variable) {
testNAdd(variable, variable.getType());
super.visitLocalVariable(variable);
}
@Override public void visitForeachStatement(final PsiForeachStatement statement) {
super.visitForeachStatement(statement);
final PsiParameter parameter = statement.getIterationParameter();
testNAdd(parameter, parameter.getType());
}
@Override public void visitField(final PsiField field) {
testNAdd(field, field.getType());
super.visitField(field);
}
@Override public void visitMethod(final PsiMethod method) {
final PsiParameter[] parms = method.getParameterList().getParameters();
for (PsiParameter parm : parms) {
testNAdd(parm, parm.getType());
}
if (Util.isRaw(method.getReturnType(), mySettings)) {
myVictims.add(method);
}
final PsiCodeBlock body = method.getBody();
if (body != null) {
body.accept(this);
}
}
@Override public void visitNewExpression(final PsiNewExpression expression) {
if (expression.getClassReference() != null) {
testNAdd(expression, expression.getType());
}
super.visitNewExpression(expression);
}
@Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){
final PsiTypeElement typeElement = cast.getCastType();
if (typeElement != null) {
testNAdd(cast, typeElement.getType());
}
super.visitTypeCastExpression(cast);
}
@Override public void visitReferenceExpression(final PsiReferenceExpression expression) {
}
@Override public void visitFile(PsiFile file) {
if (file instanceof PsiJavaFile) {
super.visitFile(file);
}
}
public HashSet<PsiElement> getVictims() {
for (PsiElement element : myElements) {
element.accept(this);
}
return myVictims;
}
}
|
Java
|
// Generated from /POI/java/org/apache/poi/hssf/usermodel/HSSFName.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <org/apache/poi/hssf/usermodel/fwd-POI.hpp>
#include <org/apache/poi/ss/formula/ptg/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <org/apache/poi/ss/usermodel/Name.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace ss
{
namespace formula
{
namespace ptg
{
typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray;
} // ptg
} // formula
} // ss
} // poi
struct default_init_tag;
class poi::hssf::usermodel::HSSFName final
: public virtual ::java::lang::Object
, public ::poi::ss::usermodel::Name
{
public:
typedef ::java::lang::Object super;
private:
HSSFWorkbook* _book { };
::poi::hssf::record::NameRecord* _definedNameRec { };
::poi::hssf::record::NameCommentRecord* _commentRec { };
protected:
void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name);
void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment);
public:
::java::lang::String* getSheetName() override;
::java::lang::String* getNameName() override;
void setNameName(::java::lang::String* nameName) override;
private:
static void validateName(::java::lang::String* name);
public:
void setRefersToFormula(::java::lang::String* formulaText) override;
::java::lang::String* getRefersToFormula() override;
public: /* package */
void setNameDefinition(::poi::ss::formula::ptg::PtgArray* ptgs);
public:
bool isDeleted() override;
bool isFunctionName() override;
::java::lang::String* toString() override;
void setSheetIndex(int32_t index) override;
int32_t getSheetIndex() override;
::java::lang::String* getComment() override;
void setComment(::java::lang::String* comment) override;
void setFunction(bool value) override;
// Generated
public: /* package */
HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name);
HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment);
protected:
HSSFName(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
|
Java
|
Ext.namespace("Ext.haode");
Ext.haode.Control = function(args){
Ext.apply(this, args);
this.init();
};
Ext.haode.Control.prototype = {
userName : '',
version : '',
app_name : '',
copyright : '',
viewport : null,
cn : 1,
init : function() {
this.viewport = this.getViewport();
},
getViewport : function() {
var viewport;
if (this.viewport) {
viewport = this.viewport;
} else {
var centerPanel = this.getCenterPanel();
viewport = new Ext.Viewport({
layout: 'fit',
items: [centerPanel]
});
}
return viewport;
},
getCenterPanel : function() {
var panel;
if (this.viewport) {
panel = this.getViewport().items[0];
} else {
var n = new Ext.Button({
id : 'tsb',
text : '发放任务',
align : 'right',
width : 80,
menu : [{
text : '常规任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
timeout : 1000000,
url : 'task.do?action=normal',
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
// }, {
// text : '个别任务',
// handler : function() {
// if (!Ext.getCmp('form').getForm().isValid()) {
// alert('请正确填写表单');
// return;
// }
//
// var sm = new Ext.grid.CheckboxSelectionModel();
// var store1 = new Ext.data.Store({
// proxy : new Ext.data.HttpProxy({
// url : 'customerManager.do?action=queryAll'
// }),
// reader : new Ext.data.JsonReader({
// root : 'rows',
// totalProperty : 'total',
// id : 'id',
// fields : ['id', 'name', 'username']
// })
// });
//
// var paging = new Ext.PagingToolbar({
// pageSize : 20,
// store : store1,
// displayInfo : true,
// displayMsg : '当前显示数据 {0} - {1} of {2}',
// emptyMsg : '没有数据'
// });
//
// var win = new Ext.Window({
// title : '客户经理',
// id : 'bind',
// layout : 'fit',
// border : false,
// modal : true,
// width : 500,
// height : 400,
// items : [new Ext.grid.GridPanel({
// id : 'grid1',
// loadMask : true,
//// tbar : [{
//// xtype : 'textfield',
//// id : 'searchName',
//// emptyText : '请输入客户经理名称...',
//// width : 150
//// }, {
//// text : '搜索',
//// width : 45,
//// xtype : 'button',
//// handler : function() {
////
//// }
//// }],
// store : store1,
// sm : sm,
// cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
// header : '客户经理名称',
// width : 200,
// dataIndex : 'name',
// align : 'center'
// }, {
// header : '客户经理用户名',
// width : 230,
// dataIndex : 'username',
// align : 'center'
// }]),
// bbar : paging
// })],
// buttons : [{
// text : '确定',
// handler : function() {
// var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
// if (mrecords.length < 1) {
// alert('请选择要做任务的客户经理!');
// return;
// }
// var mids = '';
// for (var j = 0; j < mrecords.length; j++) {
// mids += ',' + mrecords[j].get('id');
// }
//
// Ext.getCmp('bind').close();
// Ext.getCmp('form').getForm().submit({
// waitTitle : '提示',
// waitMsg : '正在提交数据请稍后...',
// url : 'task.do?action=indevi',
// params : {
// mids : mids
// },
// method : 'post',
// success : function(form, action) {
// alert(action.result.myHashMap.msg);
// },
// failure : function(form, action) {
// alert(action.result.myHashMap.msg);
// }
// });
//
// }
// }, {
// text : '取消',
// handler : function() {
// Ext.getCmp('bind').close();
// }
// }]
// });
// win.show(Ext.getBody());
// store1.load({
// params : {
// start : 0,
// limit : 20
// }
// });
//
// }
}, {
text : '分组任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var sm = new Ext.grid.CheckboxSelectionModel();
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customerGroup.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var win = new Ext.Window({
title : '客户分组',
id : 'bind',
layout : 'fit',
border : false,
modal : true,
width : 500,
height : 400,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户分组名称',
width : 200,
dataIndex : 'name',
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (grecords.length < 1) {
alert('请选择客户分组!');
return;
}
var gids = '';
for (var j = 0; j < grecords.length; j++) {
gids += ',' + grecords[j].get('id');
}
Ext.getCmp('bind').close();
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=group',
params : {
gids : gids
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('bind').close();
}
}]
});
win.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20,
all : 0
}
});
}
}, {
text : '客户任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customer.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager',
'backup_number', 'address', 'order_type', 'gps', 'last_visit_time']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var sm = new Ext.grid.CheckboxSelectionModel();
var win1 = new Ext.Window({
title : '选择客户',
id : 'chooseCustomer',
layout : 'fit',
border : false,
modal : true,
width : 800,
height : 600,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户名称',
width : 100,
dataIndex : 'name',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户编号',
width : 130,
dataIndex : 'number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '专卖证号',
width : 130,
dataIndex : 'sell_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '店铺名称',
width : 200,
dataIndex : 'store_name',
sortable : true,
remoteSort : true,
align : 'left'
}, {
header : '客户级别',
width : 90,
dataIndex : 'level',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '电话号码',
width : 100,
dataIndex : 'phone_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户经理',
width : 120,
dataIndex : 'manager',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '备用号码',
width : 100,
dataIndex : 'backup_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '经营地址',
width : 240,
dataIndex : 'address',
sortable : true,
remoteSort : true,
align : 'left',
renderer : function(value, meta) {
meta.attr = 'title="' + value + '"';
return value;
}
}, {
header : '订货类型',
width : 60,
dataIndex : 'order_type',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : 'GPS(经度,纬度)',
width : 150,
dataIndex : 'gps',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '最近一次拜访时间',
width : 180,
dataIndex : 'last_visit_time',
sortable : true,
remoteSort : true,
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (crecords.length < 1) {
alert('请选择要拜访的客户!');
return;
}
var size = crecords.length;
var cids = "";
for (var i = 0; i < size; i++) {
cids += ',' + crecords[i].get('id');
}
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=customerTask',
params : {
cids : cids
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
Ext.getCmp('chooseCustomer').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('chooseCustomer').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}, {
text : '自定义任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var cids = '';
var mid = '';
var win = new Ext.Window({
title : '自定义任务',
id : 'editWin',
layout : 'fit',
border : false,
modal : true,
width : 500,
height : 250,
items : [new Ext.form.FormPanel({
id : 'editForm',
frame : true,
bodyStyle : 'padding : 30px; 20px;',
defaults : {
msgTarget : 'under'
},
height : 'auto',
labelWidth : 80,
labelAlign : 'right',
items : [{
xtype : 'compositefield',
width : 500,
items : [{
fieldLabel : '客户名称',
xtype : 'textfield',
id : 'customer',
allowBlank : false,
width : 300
}, {
text : '浏览…',
xtype : 'button',
handler : function() {
// 选择客户
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customer.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager',
'backup_number', 'address', 'order_type', 'gps', 'last_visit_time']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var sm = new Ext.grid.CheckboxSelectionModel();
var win1 = new Ext.Window({
title : '选择客户',
id : 'chooseCustomer',
layout : 'fit',
border : false,
modal : true,
width : 800,
height : 600,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户名称',
width : 100,
dataIndex : 'name',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户编号',
width : 130,
dataIndex : 'number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '专卖证号',
width : 130,
dataIndex : 'sell_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '店铺名称',
width : 200,
dataIndex : 'store_name',
sortable : true,
remoteSort : true,
align : 'left'
}, {
header : '客户级别',
width : 90,
dataIndex : 'level',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '电话号码',
width : 100,
dataIndex : 'phone_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户经理',
width : 120,
dataIndex : 'manager',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '备用号码',
width : 100,
dataIndex : 'backup_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '经营地址',
width : 240,
dataIndex : 'address',
sortable : true,
remoteSort : true,
align : 'left',
renderer : function(value, meta) {
meta.attr = 'title="' + value + '"';
return value;
}
}, {
header : '订货类型',
width : 60,
dataIndex : 'order_type',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : 'GPS(经度,纬度)',
width : 150,
dataIndex : 'gps',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '最近一次拜访时间',
width : 180,
dataIndex : 'last_visit_time',
sortable : true,
remoteSort : true,
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (crecords.length < 1) {
alert('请选择要拜访的客户!');
return;
}
var size = crecords.length;
var cnames = '';
for (var i = 0; i < size; i++) {
cids += ',' + crecords[i].get('id');
cnames += ',' + crecords[i].get('name');
}
Ext.getCmp('customer').setValue(cnames.substring(1));
Ext.getCmp('chooseCustomer').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('chooseCustomer').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}]
}, {
xtype : 'compositefield',
width : 500,
items : [{
fieldLabel : '客户经理',
xtype : 'textfield',
id : 'manager',
allowBlank : false,
width : 300
}, {
text : '浏览…',
xtype : 'button',
handler : function() {
// 选择客户经理
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customerManager.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'username', 'department', 'area']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var win1 = new Ext.Window({
title : '选择客户经理',
id : 'bind',
layout : 'fit',
border : false,
modal : true,
width : 600,
height : 400,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), {
header : '客户经理名称',
width : 130,
dataIndex : 'name',
align : 'center'
}, {
header : '用户名',
width : 130,
dataIndex : 'username',
align : 'center'
}, {
header : '部门',
width : 130,
dataIndex : 'department',
align : 'center'
}, {
header : '片区',
width : 130,
dataIndex : 'area',
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (mrecords.length < 1) {
alert('请选择客户经理!');
return;
}
mid = mrecords[0].get('id');
var manager = mrecords[0].get('name');
if (mrecords[0].get('department') != "") {
manager = manager + "-" + mrecords[0].get('department');
}
if (mrecords[0].get('area') != "") {
manager = manager + "-" + mrecords[0].get('area');
}
Ext.getCmp('manager').setValue(manager);
Ext.getCmp('bind').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('bind').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}]
}],
buttons : [{
text : '确定',
handler : function() {
Ext.getCmp('editWin').close();
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=newCustomerTask',
params : {
mid : mid,
cids : cids,
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('editWin').close();
}
}]
})]
});
win.show(Ext.getBody());
}
}]
});
panel = new Ext.form.FormPanel({
id : 'form',
defaults : {
width : 250,
msgTarget : 'under'
},
bodyStyle : 'padding : 50px; 150px;',
labelWidth : 80,
labelAlign : 'right',
tbar : [{
xtype : 'button',
id : 'ad',
iconCls : 'add',
text : '增加内容',
align : 'right',
width : 80,
handler : function() {
this.cn = this.cn + 1;
var f = Ext.getCmp('form');
var a = Ext.getCmp('ad');
var t = Ext.getCmp('tsb');
var c = new Ext.form.TextField({
fieldLabel : '任务内容' + this.cn,
allowBlank : false,
name : 'content' + this.cn,
id : 'content' + this.cn,
xtype : 'textfield'
});
f.remove(t);
f.add(c);
f.add(n);
f.doLayout();
},
scope : this
}],
items : [{
fieldLabel : '任务起始时间',
allowBlank : false,
editable : false,
name : 'start',
id : 'start',
xtype : 'datefield'
}, {
fieldLabel : '任务完成时间',
allowBlank : false,
editable : false,
name : 'end',
id : 'end',
xtype : 'datefield'
}, {
fieldLabel : '任务标题',
allowBlank : false,
name : 'content',
id : 'content',
xtype : 'textfield'
}, {
fieldLabel : '任务内容' + this.cn,
allowBlank : false,
name : 'content' + this.cn,
id : 'content' + this.cn,
xtype : 'textfield'
}, {
xtype : 'button',
id : 'tsb',
text : '发放任务',
align : 'right',
width : 80,
menu : [{
text : '常规任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=normal',
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
// }, {
// text : '个别任务',
// handler : function() {
// if (!Ext.getCmp('form').getForm().isValid()) {
// alert('请正确填写表单');
// return;
// }
//
//
// var sm = new Ext.grid.CheckboxSelectionModel();
// var store1 = new Ext.data.Store({
// proxy : new Ext.data.HttpProxy({
// url : 'customerManager.do?action=queryAll'
// }),
// reader : new Ext.data.JsonReader({
// root : 'rows',
// totalProperty : 'total',
// id : 'id',
// fields : ['id', 'name', 'username']
// })
// });
//
// var paging = new Ext.PagingToolbar({
// pageSize : 20,
// store : store1,
// displayInfo : true,
// displayMsg : '当前显示数据 {0} - {1} of {2}',
// emptyMsg : '没有数据'
// });
//
// var win = new Ext.Window({
// title : '客户经理',
// id : 'bind',
// layout : 'fit',
// border : false,
// modal : true,
// width : 500,
// height : 400,
// items : [new Ext.grid.GridPanel({
// id : 'grid1',
// loadMask : true,
//// tbar : [{
//// xtype : 'textfield',
//// id : 'searchName',
//// emptyText : '请输入客户经理名称...',
//// width : 150
//// }, {
//// text : '搜索',
//// width : 45,
//// xtype : 'button',
//// handler : function() {
////
//// }
//// }],
// store : store1,
// sm : sm,
// cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
// header : '客户经理名称',
// width : 200,
// dataIndex : 'name',
// align : 'center'
// }, {
// header : '客户经理用户名',
// width : 230,
// dataIndex : 'username',
// align : 'center'
// }]),
// bbar : paging
// })],
// buttons : [{
// text : '确定',
// handler : function() {
// var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
// if (mrecords.length < 1) {
// alert('请选择要做任务的客户经理!');
// return;
// }
// var mids = '';
// for (var j = 0; j < mrecords.length; j++) {
// mids += ',' + mrecords[j].get('id');
// }
//
// Ext.getCmp('bind').close();
// Ext.getCmp('form').getForm().submit({
// waitTitle : '提示',
// waitMsg : '正在提交数据请稍后...',
// url : 'task.do?action=indevi',
// params : {
// mids : mids
// },
// method : 'post',
// success : function(form, action) {
// alert(action.result.myHashMap.msg);
// },
// failure : function(form, action) {
// alert(action.result.myHashMap.msg);
// }
// });
//
// }
// }, {
// text : '取消',
// handler : function() {
// Ext.getCmp('bind').close();
// }
// }]
// });
// win.show(Ext.getBody());
// store1.load({
// params : {
// start : 0,
// limit : 20
// }
// });
//
// }
}, {
text : '分组任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var sm = new Ext.grid.CheckboxSelectionModel();
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customerGroup.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var win = new Ext.Window({
title : '客户分组',
id : 'bind',
layout : 'fit',
border : false,
modal : true,
width : 500,
height : 400,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户分组名称',
width : 200,
dataIndex : 'name',
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (grecords.length < 1) {
alert('请选择客户分组!');
return;
}
var gids = '';
for (var j = 0; j < grecords.length; j++) {
gids += ',' + grecords[j].get('id');
}
Ext.getCmp('bind').close();
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=group',
params : {
gids : gids
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('bind').close();
}
}]
});
win.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20,
all : 0
}
});
}
}, {
text : '客户任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customer.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager',
'backup_number', 'address', 'order_type', 'gps', 'last_visit_time']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var sm = new Ext.grid.CheckboxSelectionModel();
var win1 = new Ext.Window({
title : '选择客户',
id : 'chooseCustomer',
layout : 'fit',
border : false,
modal : true,
width : 800,
height : 600,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户名称',
width : 100,
dataIndex : 'name',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户编号',
width : 130,
dataIndex : 'number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '专卖证号',
width : 130,
dataIndex : 'sell_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '店铺名称',
width : 200,
dataIndex : 'store_name',
sortable : true,
remoteSort : true,
align : 'left'
}, {
header : '客户级别',
width : 90,
dataIndex : 'level',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '电话号码',
width : 100,
dataIndex : 'phone_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户经理',
width : 120,
dataIndex : 'manager',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '备用号码',
width : 100,
dataIndex : 'backup_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '经营地址',
width : 240,
dataIndex : 'address',
sortable : true,
remoteSort : true,
align : 'left',
renderer : function(value, meta) {
meta.attr = 'title="' + value + '"';
return value;
}
}, {
header : '订货类型',
width : 60,
dataIndex : 'order_type',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : 'GPS(经度,纬度)',
width : 150,
dataIndex : 'gps',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '最近一次拜访时间',
width : 180,
dataIndex : 'last_visit_time',
sortable : true,
remoteSort : true,
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (crecords.length < 1) {
alert('请选择要拜访的客户!');
return;
}
var size = crecords.length;
var cids = "";
for (var i = 0; i < size; i++) {
cids += ',' + crecords[i].get('id');
}
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=customerTask',
params : {
cids : cids
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
Ext.getCmp('chooseCustomer').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('chooseCustomer').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}, {
text : '自定义任务',
handler : function() {
if (!Ext.getCmp('form').getForm().isValid()) {
alert('请正确填写表单');
return;
}
var cids = '';
var mid = '';
var win = new Ext.Window({
title : '自定义任务',
id : 'editWin',
layout : 'fit',
border : false,
modal : true,
width : 500,
height : 250,
items : [new Ext.form.FormPanel({
id : 'editForm',
frame : true,
bodyStyle : 'padding : 30px; 20px;',
defaults : {
msgTarget : 'under'
},
height : 'auto',
labelWidth : 80,
labelAlign : 'right',
items : [{
xtype : 'compositefield',
width : 500,
items : [{
fieldLabel : '客户名称',
xtype : 'textfield',
id : 'customer',
allowBlank : false,
width : 300
}, {
text : '浏览…',
xtype : 'button',
handler : function() {
// 选择客户
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customer.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager',
'backup_number', 'address', 'order_type', 'gps', 'last_visit_time']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var sm = new Ext.grid.CheckboxSelectionModel();
var win1 = new Ext.Window({
title : '选择客户',
id : 'chooseCustomer',
layout : 'fit',
border : false,
modal : true,
width : 800,
height : 600,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
sm : sm,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, {
header : '客户名称',
width : 100,
dataIndex : 'name',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户编号',
width : 130,
dataIndex : 'number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '专卖证号',
width : 130,
dataIndex : 'sell_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '店铺名称',
width : 200,
dataIndex : 'store_name',
sortable : true,
remoteSort : true,
align : 'left'
}, {
header : '客户级别',
width : 90,
dataIndex : 'level',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '电话号码',
width : 100,
dataIndex : 'phone_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '客户经理',
width : 120,
dataIndex : 'manager',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '备用号码',
width : 100,
dataIndex : 'backup_number',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '经营地址',
width : 240,
dataIndex : 'address',
sortable : true,
remoteSort : true,
align : 'left',
renderer : function(value, meta) {
meta.attr = 'title="' + value + '"';
return value;
}
}, {
header : '订货类型',
width : 60,
dataIndex : 'order_type',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : 'GPS(经度,纬度)',
width : 150,
dataIndex : 'gps',
sortable : true,
remoteSort : true,
align : 'center'
}, {
header : '最近一次拜访时间',
width : 180,
dataIndex : 'last_visit_time',
sortable : true,
remoteSort : true,
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (crecords.length < 1) {
alert('请选择要拜访的客户!');
return;
}
var size = crecords.length;
var cnames = '';
for (var i = 0; i < size; i++) {
cids += ',' + crecords[i].get('id');
cnames += ',' + crecords[i].get('name');
}
Ext.getCmp('customer').setValue(cnames.substring(1));
Ext.getCmp('chooseCustomer').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('chooseCustomer').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}]
}, {
xtype : 'compositefield',
width : 500,
items : [{
fieldLabel : '客户经理',
xtype : 'textfield',
id : 'manager',
allowBlank : false,
width : 300
}, {
text : '浏览…',
xtype : 'button',
handler : function() {
// 选择客户经理
var store1 = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'customerManager.do?action=queryAll'
}),
reader : new Ext.data.JsonReader({
root : 'rows',
totalProperty : 'total',
id : 'id',
fields : ['id', 'name', 'username', 'department', 'area']
})
});
var paging = new Ext.PagingToolbar({
pageSize : 20,
store : store1,
displayInfo : true,
displayMsg : '当前显示数据 {0} - {1} of {2}',
emptyMsg : '没有数据'
});
var win1 = new Ext.Window({
title : '选择客户经理',
id : 'bind',
layout : 'fit',
border : false,
modal : true,
width : 600,
height : 400,
items : [new Ext.grid.GridPanel({
id : 'grid1',
loadMask : true,
store : store1,
cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), {
header : '客户经理名称',
width : 130,
dataIndex : 'name',
align : 'center'
}, {
header : '用户名',
width : 130,
dataIndex : 'username',
align : 'center'
}, {
header : '部门',
width : 130,
dataIndex : 'department',
align : 'center'
}, {
header : '片区',
width : 130,
dataIndex : 'area',
align : 'center'
}]),
bbar : paging
})],
buttons : [{
text : '确定',
handler : function() {
var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections();
if (mrecords.length < 1) {
alert('请选择客户经理!');
return;
}
mid = mrecords[0].get('id');
var manager = mrecords[0].get('name');
if (mrecords[0].get('department') != "") {
manager = manager + "-" + mrecords[0].get('department');
}
if (mrecords[0].get('area') != "") {
manager = manager + "-" + mrecords[0].get('area');
}
Ext.getCmp('manager').setValue(manager);
Ext.getCmp('bind').close();
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('bind').close();
}
}]
});
win1.show(Ext.getBody());
store1.load({
params : {
start : 0,
limit : 20
}
});
}
}]
}],
buttons : [{
text : '确定',
handler : function() {
Ext.getCmp('editWin').close();
Ext.getCmp('form').getForm().submit({
waitTitle : '提示',
waitMsg : '正在提交数据请稍后...',
url : 'task.do?action=newCustomerTask',
params : {
mid : mid,
cids : cids,
},
method : 'post',
success : function(form, action) {
alert(action.result.myHashMap.msg);
},
failure : function(form, action) {
alert(action.result.myHashMap.msg);
}
});
}
}, {
text : '取消',
handler : function() {
Ext.getCmp('editWin').close();
}
}]
})]
});
win.show(Ext.getBody());
}
}]
}]
});
}
return panel;
}
};
|
Java
|
<?php
namespace App\Presenters;
use Nette;
class ContactPresenter extends Nette\Application\UI\Presenter
{
}
|
Java
|
/**
* Copyright 2002-2016 xiaoyuepeng
*
* 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.
*
*
* @author xiaoyuepeng <xyp260466@163.com>
*/
package com.xyp260466.dubbo.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by xyp on 16-5-9.
*/
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Documented
public @interface Consumer {
String value() default "";
}
|
Java
|
<?php
namespace Test\Controllers;
use Test\Models\EmailConfirmations;
use Test\Models\ResetPasswords;
/**
* UserControlController
* Provides help to users to confirm their passwords or reset them
*/
class UserControlController extends ControllerBase
{
public function initialize()
{
if ($this->session->has('auth-identity')) {
$this->view->setTemplateBefore('private');
}
}
public function indexAction()
{
}
/**
* Confirms an e-mail, if the user must change thier password then changes it
*/
public function confirmEmailAction()
{
$code = $this->dispatcher->getParam('code');
$confirmation = EmailConfirmations::findFirstByCode($code);
if (!$confirmation) {
return $this->dispatcher->forward([
'controller' => 'index',
'action' => 'index'
]);
}
if ($confirmation->confirmed != 'N') {
return $this->dispatcher->forward([
'controller' => 'session',
'action' => 'login'
]);
}
$confirmation->confirmed = 'Y';
$confirmation->user->active = 'Y';
/**
* Change the confirmation to 'confirmed' and update the user to 'active'
*/
if (!$confirmation->save()) {
foreach ($confirmation->getMessages() as $message) {
$this->flash->error($message);
}
return $this->dispatcher->forward([
'controller' => 'index',
'action' => 'index'
]);
}
/**
* Identify the user in the application
*/
$this->auth->authUserById($confirmation->user->id);
/**
* Check if the user must change his/her password
*/
if ($confirmation->user->mustChangePassword == 'Y') {
$this->flash->success('The email was successfully confirmed. Now you must change your password');
return $this->dispatcher->forward([
'controller' => 'users',
'action' => 'changePassword'
]);
}
$this->flash->success('The email was successfully confirmed');
return $this->dispatcher->forward([
'controller' => 'users',
'action' => 'index'
]);
}
public function resetPasswordAction()
{
$code = $this->dispatcher->getParam('code');
$resetPassword = ResetPasswords::findFirstByCode($code);
if (!$resetPassword) {
return $this->dispatcher->forward([
'controller' => 'index',
'action' => 'index'
]);
}
if ($resetPassword->reset != 'N') {
return $this->dispatcher->forward([
'controller' => 'session',
'action' => 'login'
]);
}
$resetPassword->reset = 'Y';
/**
* Change the confirmation to 'reset'
*/
if (!$resetPassword->save()) {
foreach ($resetPassword->getMessages() as $message) {
$this->flash->error($message);
}
return $this->dispatcher->forward([
'controller' => 'index',
'action' => 'index'
]);
}
/**
* Identify the user in the application
*/
$this->auth->authUserById($resetPassword->usersId);
$this->flash->success('Please reset your password');
return $this->dispatcher->forward([
'controller' => 'users',
'action' => 'changePassword'
]);
}
}
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import org.apache.commons.logging.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.ipc.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.net.NetUtils;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode. The Secondary is
* responsible for supporting periodic checkpoints of the HDFS metadata. The
* current design allows only one Secondary NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes up (determined by
* the schedule specified in the configuration), triggers a periodic checkpoint
* and then goes back to sleep. The Secondary NameNode uses the ClientProtocol
* to talk to the primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
public static final Log LOG = LogFactory.getLog(SecondaryNameNode.class
.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if (simulation == null)
return false;
assert (index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch (IOException e) {
shutdown();
throw e;
}
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(Configuration conf) throws IOException {
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode = (NamenodeProtocol) RPC.waitForProxy(
NamenodeProtocol.class, NamenodeProtocol.versionID,
nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
infoBindAddress = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
infoServer.setAttribute("name.system.image", checkpointImage);
this.infoServer.setAttribute("name.conf", conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class);
infoServer.start();
// The web-server port can be ephemeral... ensure we have the correct
// info
infoPort = infoServer.getPort();
conf
.set("dfs.secondary.http.address", infoBindAddress + ":"
+ infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":"
+ infoPort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "("
+ checkpointPeriod / 60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "("
+ checkpointSize / 1024 + " KB)");
}
/**
* Shut down this instance of the datanode. Returns only after shutdown is
* complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null)
infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null)
checkpointImage.close();
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
//
// The main work loop
//
public void run() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize
|| now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code> files from the
* name-node.
*
* @throws IOException
*/
private void downloadCheckpointFiles(CheckpointSignature sig)
throws IOException {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + infoPort + "&machine="
+ InetAddress.getLocalHost().getHostAddress() + "&token="
+ sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[]) null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
return NetUtils.getServerAddress(conf, "dfs.info.bindAddress",
"dfs.info.port", "dfs.http.address");
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 "
+ "after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 "
+ "after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into current
* storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem = new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv
* The parameters passed to this program.
* @exception Exception
* if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize || argv.length == 2
&& "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is "
+ "smaller than configured checkpoint " + "size "
+ checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": " + content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
*
* @param cmd
* The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode "
+ "[-checkpoint [force]] " + "[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
*
* @param argv
* Command line parameters.
* @exception Exception
* if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories. Create directories if they do not
* exist. Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs, Collection<File> editsDirs)
throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if (!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch (SecurityException se) {
isAccessible = false;
}
if (!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd
.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch (curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are
// inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current
// and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code> and
* recreate <code>current</code>.
*
* @throws IOException
*/
void startCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File curDir = sd.getCurrentDir();
File tmpCkptDir = sd.getLastCheckpointTmp();
assert !tmpCkptDir.exists() : tmpCkptDir.getName()
+ " directory must not exist.";
if (curDir.exists()) {
// rename current to tmp
rename(curDir, tmpCkptDir);
}
if (!curDir.mkdir())
throw new IOException("Cannot create directory " + curDir);
}
}
void endCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File tmpCkptDir = sd.getLastCheckpointTmp();
File prevCkptDir = sd.getPreviousCheckpoint();
// delete previous dir
if (prevCkptDir.exists())
deleteDir(prevCkptDir);
// rename tmp to previous
if (tmpCkptDir.exists())
rename(tmpCkptDir, prevCkptDir);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveFSImage();
}
}
}
|
Java
|
"""Custom Exception Classes for Phylotyper Module
"""
class PhylotyperError(Exception):
"""Basic exception for errors raised by Phylotyper modules"""
def __init__(self, subtype, msg=None):
if msg is None:
msg = "An error occured for subtype {}".format(subtype)
super(PhylotyperError, self).__init__(msg)
self.subtype = subtype
class ValuesError(PhylotyperError):
"""Unknown subtype"""
def __init__(self, subtype, msg=None):
super(PhylotyperError, self).__init__(
subtype, msg="Unrecognized subtype {}".format(subtype))
class DatabaseError(PhylotyperError):
"""Missing data in Database"""
def __init__(self, subtype, data, msg=None):
m = "Database is missing data {} for {}".format(data, subtype)
super(PhylotyperError, self).__init__(subtype, m)
self.data = data
|
Java
|
<span class="boolfield">
<i class="{{ type.color }} {{ type.icon }}" aria-hidden="true"></i>
{{ bool }}
</span>
|
Java
|
% Date Picker
## About
A Date Picker is a control used for selecting a date.
## API Reference
[moon.DatePicker]($api/#/kind/moon.DatePicker)
## Behavior
When closed, the first title line should inform the user of the picker's
function. The second line of text shows the currently selected value.
When the picker is open, all content below is pushed downwards to make room for
the entire height of the picker control in its open state.
After selections have been made, pressing Enter/OK on the picker title will
close the control. Once the picker is closed, the selected value(s) appear
beneath the title.
### States
* **Closed**
* **Focused (hover)**
* **Open**
### Sizing
The width of the control will automatically scale to fit the area containing the
control.
## Illustration
### Closed and Open

|
Java
|
maintainer "Belly, Inc."
maintainer_email "sysops@bellycard.com"
license "Apache v2.0"
description "Installs/Configures Google Go"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.0"
# Operating systems supported
%w{ debian ubuntu }.each do |os|
supports os
end
|
Java
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if (STATIC_BUILD)
include_regular_expression("^.*$")
set(OPENJPEG_VERSION_MAJOR 2)
set(OPENJPEG_VERSION_MINOR 3)
set(OPENJPEG_VERSION_BUILD 0)
set(OPENJPEG_VERSION
"${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")
set(PACKAGE_VERSION
"${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")
set(OPENJPEG_NAME openjpeg-2.3.0)
set(OPENJPEG_SOURCES_DIR ${CMAKE_BINARY_DIR}/${OPENJPEG_NAME})
#"https://github.com/uclouvain/openjpeg/archive/v2.3.0.tar.gz"
include_directories(
${OPENJPEG_SOURCES_DIR}/src/lib/openjp3d
)
set(OPENJPEG_SOURCES_DIR ${OPENJPEG_SOURCES_DIR}/src/lib/openjp2)
include (${CMAKE_ROOT}/Modules/CheckIncludeFile.cmake)
macro(ensure_file_include INCLUDE_FILENAME VARIABLE_NAME MANDATORY_STATUS)
CHECK_INCLUDE_FILE(${INCLUDE_FILENAME} ${VARIABLE_NAME})
if (NOT ${${VARIABLE_NAME}})
if (${MANDATORY_STATUS})
message(FATAL_ERROR "The file ${INCLUDE_FILENAME} is mandatory but not found on your system")
endif()
endif()
endmacro()
ensure_file_include("stdint.h" OPJ_HAVE_STDINT_H YES)
ensure_file_include("inttypes.h" OPJ_HAVE_INTTYPES_H YES)
configure_file(
${OPENJPEG_SOURCES_DIR}/opj_config.h.cmake.in
${OPENJPEG_SOURCES_DIR}/opj_config.h
@ONLY
)
message(${CMAKE_CURRENT_BINARY_DIR})
configure_file(
${OPENJPEG_SOURCES_DIR}/opj_config_private.h.cmake.in
${OPENJPEG_SOURCES_DIR}/opj_config_private.h
@ONLY
)
include_directories(
${CMAKE_BINARY_DIR}
)
include_directories(
${OPENJPEG_SOURCES_DIR}
)
set(OPENJPEG_SRCS
${OPENJPEG_SOURCES_DIR}/thread.c
${OPENJPEG_SOURCES_DIR}/thread.h
${OPENJPEG_SOURCES_DIR}/bio.c
${OPENJPEG_SOURCES_DIR}/bio.h
${OPENJPEG_SOURCES_DIR}/cio.c
${OPENJPEG_SOURCES_DIR}/cio.h
${OPENJPEG_SOURCES_DIR}/dwt.c
${OPENJPEG_SOURCES_DIR}/dwt.h
${OPENJPEG_SOURCES_DIR}/event.c
${OPENJPEG_SOURCES_DIR}/event.h
${OPENJPEG_SOURCES_DIR}/image.c
${OPENJPEG_SOURCES_DIR}/image.h
${OPENJPEG_SOURCES_DIR}/invert.c
${OPENJPEG_SOURCES_DIR}/invert.h
${OPENJPEG_SOURCES_DIR}/j2k.c
${OPENJPEG_SOURCES_DIR}/j2k.h
${OPENJPEG_SOURCES_DIR}/jp2.c
${OPENJPEG_SOURCES_DIR}/jp2.h
${OPENJPEG_SOURCES_DIR}/mct.c
${OPENJPEG_SOURCES_DIR}/mct.h
${OPENJPEG_SOURCES_DIR}/mqc.c
${OPENJPEG_SOURCES_DIR}/mqc.h
${OPENJPEG_SOURCES_DIR}/mqc_inl.h
${OPENJPEG_SOURCES_DIR}/openjpeg.c
${OPENJPEG_SOURCES_DIR}/openjpeg.h
${OPENJPEG_SOURCES_DIR}/opj_clock.c
${OPENJPEG_SOURCES_DIR}/opj_clock.h
${OPENJPEG_SOURCES_DIR}/pi.c
${OPENJPEG_SOURCES_DIR}/pi.h
${OPENJPEG_SOURCES_DIR}/t1.c
${OPENJPEG_SOURCES_DIR}/t1.h
${OPENJPEG_SOURCES_DIR}/t2.c
${OPENJPEG_SOURCES_DIR}/t2.h
${OPENJPEG_SOURCES_DIR}/tcd.c
${OPENJPEG_SOURCES_DIR}/tcd.h
${OPENJPEG_SOURCES_DIR}/tgt.c
${OPENJPEG_SOURCES_DIR}/tgt.h
${OPENJPEG_SOURCES_DIR}/function_list.c
${OPENJPEG_SOURCES_DIR}/function_list.h
${OPENJPEG_SOURCES_DIR}/opj_codec.h
${OPENJPEG_SOURCES_DIR}/opj_includes.h
${OPENJPEG_SOURCES_DIR}/opj_intmath.h
${OPENJPEG_SOURCES_DIR}/opj_malloc.c
${OPENJPEG_SOURCES_DIR}/opj_malloc.h
${OPENJPEG_SOURCES_DIR}/opj_stdint.h
${OPENJPEG_SOURCES_DIR}/sparse_array.c
${OPENJPEG_SOURCES_DIR}/sparse_array.h
)
if(BUILD_JPIP)
add_definitions(-DUSE_JPIP)
set(OPENJPEG_SRCS
${OPENJPEG_SRCS}
${OPENJPEG_SOURCES_DIR}/cidx_manager.c
${OPENJPEG_SOURCES_DIR}/cidx_manager.h
${OPENJPEG_SOURCES_DIR}/phix_manager.c
${OPENJPEG_SOURCES_DIR}/ppix_manager.c
${OPENJPEG_SOURCES_DIR}/thix_manager.c
${OPENJPEG_SOURCES_DIR}/tpix_manager.c
${OPENJPEG_SOURCES_DIR}/indexbox_manager.h
)
endif()
else()
find_package(OpenJPEG REQUIRED)
include_directories(${OPENJPEG_INCLUDE_DIRS})
include_directories(${OPENJPEG_INCLUDE_DIRS}/openjpeg-2.3/)
link_libraries(${OPENJPEG_LIBRARIES})
endif()
|
Java
|
<?php
$curdir = dirname(__FILE__);
require_once($curdir.'/Db.php');
class LoanStatus extends Db {
protected static $table_name = "loanstatus";
protected static $db_fields = array("id", "name", "description");
public function findById($id){
$result = $this->getrec(self::$table_name, "id=".$id, "");
return !empty($result) ? $result:false;
}
public function findAll(){
$result_array = $this->getarray(self::$table_name, "", "", "");
return !empty($result_array) ? $result_array : false;
}
public function findLoanStatus($id){
$result = $this->getfrec(self::$table_name, "name", "id=".$id, "", "");
return !empty($result) ? $result['name'] : false;
}
public function addLoanStatus($data){
$fields = self::$db_fields;
if($this->add(self::$table_name, $fields, $this->generateAddFields($fields, $data))){
return true;
}
return false;
}
public function updateLoanStatus($data){
$fields = array_slice(1, self::$db_fields);
$id = $data['id'];
unset($data['id']);
if($this->update(self::$table_name, $fields, $this->generateAddFields($fields, $data), "id=".$id)){
return true;
}
return false;
}
}
?>
|
Java
|
<?php
/**
* DBDelTree action message.
*
* PHP Version 5
*
* @category PHPAMI
* @package Message
* @subpackage Action
* @author Jaime Ziga <jaime.ziga@gmail.com>
* @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0
* @version SVN: $Id$
* @link http://github.com/Adrian0350/PHP-AMI/
*
* Copyright 2011 Marcelo Gornstein <marcelog@gmail.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.
*
*/
require_once dirname(__FILE__) . '/ActionMessage.php';
/**
* DBDelTree action message.
*
* PHP Version 5
*
* @category PHPAMI
* @package Message
* @subpackage Action
* @author Jaime Ziga <jaime.ziga@gmail.com>
* @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0
* @link http://github.com/Adrian0350/PHP-AMI/
*/
class DBDelTreeAction extends ActionMessage
{
/**
* Constructor.
*
* @param string $family Family.
* @param string $key Name (optional)
*
* @return void
*/
public function __construct($family, $key = false)
{
parent::__construct('DBDelTree');
$this->setKey('Family', $family);
if ($key != false) {
$this->setKey('Key', $key);
}
}
}
|
Java
|
/*
~ Copyright (c) 2014 George Norman.
~ Licensed under the Apache License, Version 2.0 (the "License");
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ --------------------------------------------------------------
~ Renders <css-lab-about> tags - sharable among all projects.
~ --------------------------------------------------------------
*/
/**
* The <css-lab-about> tag renders a common introduction, displayed across all of the
* CSS Lab projects and pages. There can be only one Introduction section per page.
*<p>
* Example:
* <pre style="background:#eee; padding:6px;">
* <css-lab-about style="margin-top:12px;"/>
* </pre>
*
* @module cssLabAboutTag
*/
var cssLabAboutTag = (function(tzDomHelper, tzCustomTagHelper) {
"use strict";
// http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript
var template =
['This page contains example code used for the <a href="http://www.thruzero.com/jcat3/apps/resources/resources.jsf?rid=css.overview">CSS Summary</a>',
'at <a href="http://www.thruzero.com/">ThruZero</a>. ',
'The example code (e.g., CSS and HTML) is defined with inline-templates and then rendered live, so it will always match the rendered example. '
].join('\n');
return {
getTagName: function() {
return "css-lab-about";
},
/**
* Render the first <css-lab-about> tag on the page - only one tag per page is supported.
*/
renderAll: function() {
tzCustomTagHelper.renderFirst(this);
},
/**
* Render the <css-lab-about> tag identified by the given tagId.
*
* @param tagId ID of the tag to render.
*/
renderTagById: function(tagId) {
tzCustomTagHelper.renderTagById(this, tagId);
},
/**
* Render the given aboutTagNode.
*
* @param aboutTagNode the node to retrieve the attributes from and then render the result to.
*/
renderTag: function(aboutTagNode) {
this.render(aboutTagNode);
},
/**
* Render the 'About Application' HTML, into the given containerNode.
*
* @param containerNode where to render the result.
*/
render: function(containerNode) {
containerNode.style.display = 'block';
//var template = tzCustomTagHelper.getTemplate(this.getTagName() + "Template"); // @-@:p1(geo) Experimental
tzCustomTagHelper.renderTagFromTemplate(containerNode, template, {});
}
}
}(tzDomHelperModule, tzCustomTagHelperModule));
|
Java
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>快查网-chrome插件</title>
<script type="text/javascript" src="../js/jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="../js/benchmark.js" charset="utf-8"></script>
<script type="text/javascript" src="../js/show_desktop.js" charset="utf-8"></script>
<script type="text/javascript" src="../js/test.js" charset="utf-8"></script>
</head>
<body>
<div id="test1" style="cursor:hand;">good</div>
</body>
</html>
|
Java
|
---
result: pass
---
Webpack preserves live bindings in modules. This remains true in cases where source modules are intentionally duplicated across bundles, since only a single _instance_ of each module is ever created.
|
Java
|
package me.soulmachine;
import org.jruby.embed.ScriptingContainer;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* A simple JRuby example to execute Python scripts from Java.
*/
final class JRubyExample {
private JRubyExample() {}
/**
* Main entrypoint.
*
* @param args arguments
* @throws ScriptException ScriptException
*/
public static void main(final String[] args) throws ScriptException {
listEngines();
final String rubyHelloWord = "puts 'Hello World from JRuby!'";
// First way: Use built-in ScriptEngine from JDK
{
final ScriptEngineManager mgr = new ScriptEngineManager();
final ScriptEngine pyEngine = mgr.getEngineByName("ruby");
try {
pyEngine.eval(rubyHelloWord);
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
// Second way: Use ScriptingContainer() from JRuby
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
scriptingContainer.runScriptlet(rubyHelloWord);
}
// Call Ruby Methods from Java
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
final String rubyMethod = "def myAdd(a,b)\n\treturn a+b\nend";
final Object receiver = scriptingContainer.runScriptlet(rubyMethod);
final Object[] arguments = new Object[2];
arguments[0] = Integer.valueOf(6);
arguments[1] = Integer.valueOf(4);
final Integer result = scriptingContainer.callMethod(receiver, "myAdd",
arguments, Integer.class);
System.out.println("Result: " + result);
}
}
/**
* Display all script engines.
*/
public static void listEngines() {
final ScriptEngineManager mgr = new ScriptEngineManager();
final List<ScriptEngineFactory> factories =
mgr.getEngineFactories();
for (final ScriptEngineFactory factory: factories) {
System.out.println("ScriptEngineFactory Info");
final String engName = factory.getEngineName();
final String engVersion = factory.getEngineVersion();
final String langName = factory.getLanguageName();
final String langVersion = factory.getLanguageVersion();
System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);
final List<String> engNames = factory.getNames();
for (final String name: engNames) {
System.out.printf("\tEngine Alias: %s\n", name);
}
System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
}
}
}
|
Java
|
package com.arthurb.iterator.dinermergergery;
import java.util.Iterator;
/**
* Created by Blackwood on 07.03.2016 18:16.
*/
public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu() {
menuItems = new MenuItem[MAX_ITEMS];
addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 2.99);
addItem("Hotdog", "A got dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99);
addItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89);
}
private void addItem(String name, String description, boolean vegetarian, double price) {
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS) { // Ограничиваем размер меню, чтобы не запоминать слишком много рецептов
System.err.println("Sorry, menu is full! Can't add item to menu");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}
public Iterator createIterator() {
return new DinerMenuIterator(menuItems);
}
}
|
Java
|
/* eslint-disable local/html-template */
const documentModes = require('./document-modes');
const {AmpState, ampStateKey} = require('./amphtml-helpers');
const {html, joinFragments} = require('./html');
const jsModes = [
{
value: 'default',
description: `Unminified AMP JavaScript is served from the local server. For
local development you will usually want to serve unminified JS to test your
changes.`,
},
{
value: 'minified',
description: html`
Minified AMP JavaScript is served from the local server. This is only
available after running <code>amp dist --fortesting</code>
`,
},
{
value: 'cdn',
description: 'Minified AMP JavaScript is served from the AMP Project CDN.',
},
];
const stateId = 'settings';
const htmlEnvelopePrefixStateKey = 'htmlEnvelopePrefix';
const jsModeStateKey = 'jsMode';
const panelStateKey = 'panel';
const htmlEnvelopePrefixKey = ampStateKey(stateId, htmlEnvelopePrefixStateKey);
const panelKey = ampStateKey(stateId, panelStateKey);
const PanelSelectorButton = ({expression, type, value}) =>
html`
<button
class="settings-panel-button"
[class]="'settings-panel-button' + (${panelKey} != '${type}' ? '' : ' open')"
data-type="${type}"
tabindex="0"
on="tap: AMP.setState({
${stateId}: {
${panelStateKey}: (${panelKey} != '${type}' ? '${type}' : null),
}
})"
>
<span>${type}</span> <strong [text]="${expression}">${value}</strong>
</button>
`;
const PanelSelector = ({children, compact = false, key, name = null}) => html`
<amp-selector
layout="container"
name="${name || key}"
class="${compact ? 'compact ' : ''}"
on="select: AMP.setState({
${stateId}: {
${panelStateKey}: null,
${key}: event.targetOption,
}
})"
>
${joinFragments(children)}
</amp-selector>
`;
const PanelSelectorBlock = ({children, id, selected, value}) => html`
<div
class="selector-block"
${selected ? ' selected' : ''}
id="${id}"
option="${value}"
>
<div class="check-icon icon"></div>
${children}
</div>
`;
const HtmlEnvelopeSelector = ({htmlEnvelopePrefix}) =>
PanelSelector({
compact: true,
key: htmlEnvelopePrefixStateKey,
children: Object.entries(documentModes).map(([prefix, name]) =>
PanelSelectorBlock({
id: `select-html-mode-${name}`,
value: prefix,
selected: htmlEnvelopePrefix === prefix,
children: html`<strong>${name}</strong>`,
})
),
});
const JsModeSelector = ({jsMode}) =>
PanelSelector({
key: jsModeStateKey,
name: 'mode',
children: jsModes.map(({description, value}) =>
PanelSelectorBlock({
id: `serve-mode-${value}`,
value,
selected: jsMode === value,
children: html`
<strong>${value}</strong>
<p>${description}</p>
`,
})
),
});
const SettingsPanelButtons = ({htmlEnvelopePrefix, jsMode}) => html`
<div style="flex: 1">
<div class="settings-panel-button-container">
${PanelSelectorButton({
type: 'HTML',
expression: `${stateId}.documentModes[${htmlEnvelopePrefixKey}]`,
value: documentModes[htmlEnvelopePrefix],
})}
${PanelSelectorButton({
type: 'JS',
expression: `${stateId}.${jsModeStateKey}`,
value: jsMode,
})}
</div>
${SettingsPanel({htmlEnvelopePrefix, jsMode})}
</div>
`;
const SettingsSubpanel = ({children, type}) => html`
<div hidden [hidden]="${panelKey} != '${type}'">${children}</div>
`;
const SettingsPanel = ({htmlEnvelopePrefix, jsMode}) => html`
<div class="settings-panel" hidden [hidden]="${panelKey} == null">
${AmpState(stateId, {
documentModes,
[panelStateKey]: null,
[htmlEnvelopePrefixStateKey]: htmlEnvelopePrefix,
[jsModeStateKey]: jsMode,
})}
${SettingsSubpanel({
type: 'HTML',
children: html`
<h4>Select an envelope to serve HTML documents.</h4>
${HtmlEnvelopeSelector({htmlEnvelopePrefix})}
`,
})}
${SettingsSubpanel({
type: 'JS',
children: html`
<h4>Select the JavaScript binaries to use in served documents.</h4>
<form
action="/serve_mode_change"
action-xhr="/serve_mode_change"
target="_blank"
id="serve-mode-form"
>
${JsModeSelector({jsMode})}
</form>
`,
})}
</div>
`;
module.exports = {
SettingsPanel,
SettingsPanelButtons,
htmlEnvelopePrefixKey,
};
|
Java
|
package org.apache.helix.controller.rebalancer.waged.model;
/*
* 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.
*/
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.helix.HelixException;
import org.apache.helix.controller.rebalancer.util.WagedValidationUtil;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents a possible allocation of the replication.
* Note that any usage updates to the AssignableNode are not thread safe.
*/
public class AssignableNode implements Comparable<AssignableNode> {
private static final Logger LOG = LoggerFactory.getLogger(AssignableNode.class.getName());
// Immutable Instance Properties
private final String _instanceName;
private final String _faultZone;
// maximum number of the partitions that can be assigned to the instance.
private final int _maxPartition;
private final ImmutableSet<String> _instanceTags;
private final ImmutableMap<String, List<String>> _disabledPartitionsMap;
private final ImmutableMap<String, Integer> _maxAllowedCapacity;
// Mutable (Dynamic) Instance Properties
// A map of <resource name, <partition name, replica>> that tracks the replicas assigned to the
// node.
private Map<String, Map<String, AssignableReplica>> _currentAssignedReplicaMap;
// A map of <capacity key, capacity value> that tracks the current available node capacity
private Map<String, Integer> _remainingCapacity;
/**
* Update the node with a ClusterDataCache. This resets the current assignment and recalculates
* currentCapacity.
* NOTE: While this is required to be used in the constructor, this can also be used when the
* clusterCache needs to be
* refreshed. This is under the assumption that the capacity mappings of InstanceConfig and
* ResourceConfig could
* subject to change. If the assumption is no longer true, this function should become private.
*/
AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) {
_instanceName = instanceName;
Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig);
_faultZone = computeFaultZone(clusterConfig, instanceConfig);
_instanceTags = ImmutableSet.copyOf(instanceConfig.getTags());
_disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap());
// make a copy of max capacity
_maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity);
_remainingCapacity = new HashMap<>(instanceCapacity);
_maxPartition = clusterConfig.getMaxPartitionsPerInstance();
_currentAssignedReplicaMap = new HashMap<>();
}
/**
* This function should only be used to assign a set of new partitions that are not allocated on
* this node. It's because the any exception could occur at the middle of batch assignment and the
* previous finished assignment cannot be reverted
* Using this function avoids the overhead of updating capacity repeatedly.
*/
void assignInitBatch(Collection<AssignableReplica> replicas) {
Map<String, Integer> totalPartitionCapacity = new HashMap<>();
for (AssignableReplica replica : replicas) {
// TODO: the exception could occur in the middle of for loop and the previous added records cannot be reverted
addToAssignmentRecord(replica);
// increment the capacity requirement according to partition's capacity configuration.
for (Map.Entry<String, Integer> capacity : replica.getCapacity().entrySet()) {
totalPartitionCapacity.compute(capacity.getKey(),
(key, totalValue) -> (totalValue == null) ? capacity.getValue()
: totalValue + capacity.getValue());
}
}
// Update the global state after all single replications' calculation is done.
for (String capacityKey : totalPartitionCapacity.keySet()) {
updateRemainingCapacity(capacityKey, totalPartitionCapacity.get(capacityKey));
}
}
/**
* Assign a replica to the node.
* @param assignableReplica - the replica to be assigned
*/
void assign(AssignableReplica assignableReplica) {
addToAssignmentRecord(assignableReplica);
assignableReplica.getCapacity().entrySet().stream()
.forEach(capacity -> updateRemainingCapacity(capacity.getKey(), capacity.getValue()));
}
/**
* Release a replica from the node.
* If the replication is not on this node, the assignable node is not updated.
* @param replica - the replica to be released
*/
void release(AssignableReplica replica)
throws IllegalArgumentException {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
// Check if the release is necessary
if (!_currentAssignedReplicaMap.containsKey(resourceName)) {
LOG.warn("Resource {} is not on node {}. Ignore the release call.", resourceName,
getInstanceName());
return;
}
Map<String, AssignableReplica> partitionMap = _currentAssignedReplicaMap.get(resourceName);
if (!partitionMap.containsKey(partitionName) || !partitionMap.get(partitionName)
.equals(replica)) {
LOG.warn("Replica {} is not assigned to node {}. Ignore the release call.",
replica.toString(), getInstanceName());
return;
}
AssignableReplica removedReplica = partitionMap.remove(partitionName);
removedReplica.getCapacity().entrySet().stream()
.forEach(entry -> updateRemainingCapacity(entry.getKey(), -1 * entry.getValue()));
}
/**
* @return A set of all assigned replicas on the node.
*/
Set<AssignableReplica> getAssignedReplicas() {
return _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream()).collect(Collectors.toSet());
}
/**
* @return The current assignment in a map of <resource name, set of partition names>
*/
Map<String, Set<String>> getAssignedPartitionsMap() {
Map<String, Set<String>> assignmentMap = new HashMap<>();
for (String resourceName : _currentAssignedReplicaMap.keySet()) {
assignmentMap.put(resourceName, _currentAssignedReplicaMap.get(resourceName).keySet());
}
return assignmentMap;
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names in the specified resource.
*/
public Set<String> getAssignedPartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).keySet();
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names with the top state in the
* specified resource.
*/
Set<String> getAssignedTopStatePartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).entrySet()
.stream().filter(partitionEntry -> partitionEntry.getValue().isReplicaTopState())
.map(partitionEntry -> partitionEntry.getKey()).collect(Collectors.toSet());
}
/**
* @return The total count of assigned top state partitions.
*/
public int getAssignedTopStatePartitionsCount() {
return (int) _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream())
.filter(AssignableReplica::isReplicaTopState).count();
}
/**
* @return The total count of assigned replicas.
*/
public int getAssignedReplicaCount() {
return _currentAssignedReplicaMap.values().stream().mapToInt(Map::size).sum();
}
/**
* @return The current available capacity.
*/
public Map<String, Integer> getRemainingCapacity() {
return _remainingCapacity;
}
/**
* @return A map of <capacity category, capacity number> that describes the max capacity of the
* node.
*/
public Map<String, Integer> getMaxCapacity() {
return _maxAllowedCapacity;
}
/**
* Return the most concerning capacity utilization number for evenly partition assignment.
* The method dynamically calculates the projected highest utilization number among all the
* capacity categories assuming the new capacity usage is added to the node.
* For example, if the current node usage is {CPU: 0.9, MEM: 0.4, DISK: 0.6}. Then this call shall
* return 0.9.
* @param newUsage the proposed new additional capacity usage.
* @return The highest utilization number of the node among all the capacity category.
*/
public float getProjectedHighestUtilization(Map<String, Integer> newUsage) {
float highestCapacityUtilization = 0;
for (String capacityKey : _maxAllowedCapacity.keySet()) {
float capacityValue = _maxAllowedCapacity.get(capacityKey);
float utilization = (capacityValue - _remainingCapacity.get(capacityKey) + newUsage
.getOrDefault(capacityKey, 0)) / capacityValue;
highestCapacityUtilization = Math.max(highestCapacityUtilization, utilization);
}
return highestCapacityUtilization;
}
public String getInstanceName() {
return _instanceName;
}
public Set<String> getInstanceTags() {
return _instanceTags;
}
public String getFaultZone() {
return _faultZone;
}
public boolean hasFaultZone() {
return _faultZone != null;
}
/**
* @return A map of <resource name, set of partition names> contains all the partitions that are
* disabled on the node.
*/
public Map<String, List<String>> getDisabledPartitionsMap() {
return _disabledPartitionsMap;
}
/**
* @return The max partition count that are allowed to be allocated on the node.
*/
public int getMaxPartition() {
return _maxPartition;
}
/**
* Computes the fault zone id based on the domain and fault zone type when topology is enabled.
* For example, when
* the domain is "zone=2, instance=testInstance" and the fault zone type is "zone", this function
* returns "2".
* If cannot find the fault zone type, this function leaves the fault zone id as the instance name.
* Note the WAGED rebalancer does not require full topology tree to be created. So this logic is
* simpler than the CRUSH based rebalancer.
*/
private String computeFaultZone(ClusterConfig clusterConfig, InstanceConfig instanceConfig) {
if (!clusterConfig.isTopologyAwareEnabled()) {
// Instance name is the default fault zone if topology awareness is false.
return instanceConfig.getInstanceName();
}
String topologyStr = clusterConfig.getTopology();
String faultZoneType = clusterConfig.getFaultZoneType();
if (topologyStr == null || faultZoneType == null) {
LOG.debug("Topology configuration is not complete. Topology define: {}, Fault Zone Type: {}",
topologyStr, faultZoneType);
// Use the instance name, or the deprecated ZoneId field (if exists) as the default fault
// zone.
String zoneId = instanceConfig.getZoneId();
return zoneId == null ? instanceConfig.getInstanceName() : zoneId;
} else {
// Get the fault zone information from the complete topology definition.
String[] topologyKeys = topologyStr.trim().split("/");
if (topologyKeys.length == 0 || Arrays.stream(topologyKeys)
.noneMatch(type -> type.equals(faultZoneType))) {
throw new HelixException(
"The configured topology definition is empty or does not contain the fault zone type.");
}
Map<String, String> domainAsMap = instanceConfig.getDomainAsMap();
StringBuilder faultZoneStringBuilder = new StringBuilder();
for (String key : topologyKeys) {
if (!key.isEmpty()) {
// if a key does not exist in the instance domain config, apply the default domain value.
faultZoneStringBuilder.append(domainAsMap.getOrDefault(key, "Default_" + key));
if (key.equals(faultZoneType)) {
break;
} else {
faultZoneStringBuilder.append('/');
}
}
}
return faultZoneStringBuilder.toString();
}
}
/**
* @throws HelixException if the replica has already been assigned to the node.
*/
private void addToAssignmentRecord(AssignableReplica replica) {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
if (_currentAssignedReplicaMap.containsKey(resourceName) && _currentAssignedReplicaMap
.get(resourceName).containsKey(partitionName)) {
throw new HelixException(String
.format("Resource %s already has a replica with state %s from partition %s on node %s",
replica.getResourceName(), replica.getReplicaState(), replica.getPartitionName(),
getInstanceName()));
} else {
_currentAssignedReplicaMap.computeIfAbsent(resourceName, key -> new HashMap<>())
.put(partitionName, replica);
}
}
private void updateRemainingCapacity(String capacityKey, int usage) {
if (!_remainingCapacity.containsKey(capacityKey)) {
//if the capacityKey belongs to replicas does not exist in the instance's capacity,
// it will be treated as if it has unlimited capacity of that capacityKey
return;
}
_remainingCapacity.put(capacityKey, _remainingCapacity.get(capacityKey) - usage);
}
/**
* Get and validate the instance capacity from instance config.
* @throws HelixException if any required capacity key is not configured in the instance config.
*/
private Map<String, Integer> fetchInstanceCapacity(ClusterConfig clusterConfig,
InstanceConfig instanceConfig) {
Map<String, Integer> instanceCapacity =
WagedValidationUtil.validateAndGetInstanceCapacity(clusterConfig, instanceConfig);
// Remove all the non-required capacity items from the map.
instanceCapacity.keySet().retainAll(clusterConfig.getInstanceCapacityKeys());
return instanceCapacity;
}
@Override
public int hashCode() {
return _instanceName.hashCode();
}
@Override
public int compareTo(AssignableNode o) {
return _instanceName.compareTo(o.getInstanceName());
}
@Override
public String toString() {
return _instanceName;
}
}
|
Java
|
select "${session_uuid}"
|
Java
|
//**************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// FILE: gfx.h
// DESCRIPTION: main graphics system include file.
// AUTHOR: Don Brittain
// HISTORY:
//**************************************************************************/
#if !defined(_GFX_H_)
#define _GFX_H_
#include "maxheap.h"
#include "geomlib.h"
#include "export.h"
#include "tab.h"
#include "mtl.h"
#include "BaseInterface.h"
#include "HWMesh.h"
typedef Tab<DWORD> DWTab;
typedef unsigned short MtlID;
class VertexBuffer: public MaxHeapOperators {
public:
Point3 position;
DWORD color;
};
class LineBuffer: public MaxHeapOperators {
public:
Point3 position;
DWORD color;
};
// strip-related stuff
class Strip: public MaxHeapOperators {
public:
MtlID mID;
DWORD smGrp;
DWTab v;
DWTab n;
DWTab tv;
void AddVert(DWORD vtx) { v.Append(1, &vtx); }
void AddVert(DWORD vtx, DWORD tvtx) { v.Append(1, &vtx); tv.Append(1, &tvtx); }
void AddVertN(DWORD vtx, DWORD nor) { v.Append(1, &vtx); n.Append(1, &nor); }
void AddVertN(DWORD vtx, DWORD tvtx, DWORD nor) { v.Append(1, &vtx); tv.Append(1, &tvtx); n.Append(1, &nor); }
};
typedef Strip *StripPtr;
typedef Tab<StripPtr> StripTab;
// Face Flags: (moved from mesh.h)
// 3 LSBs hold the edge visibility flags
// Bit 3 indicates the presence of texture verticies
// if bit is 1, edge is visible
#define EDGE_VIS 1
#define EDGE_INVIS 0
// first edge-visibility bit field
#define VIS_BIT 0x0001
#define VIS_MASK 0x0007
#define EDGE_A (1<<0)
#define EDGE_B (1<<1)
#define EDGE_C (1<<2)
#define EDGE_ALL (EDGE_A|EDGE_B|EDGE_C)
#define FACE_HIDDEN (1<<3)
#define HAS_TVERTS (1<<4) // DO NOT USE: This flag is obselete.
#define FACE_WORK (1<<5) // used in various algorithms
#define FACE_STRIP (1<<6)
// flags to indicate that face normal is used because no smoothing group
// normal is found
#define FACE_NORM_A (1<<8)
#define FACE_NORM_B (1<<9)
#define FACE_NORM_C (1<<10)
#define FACE_NORM_MASK 0x0700
#define FACE_INFOREGROUND (1<<11) //watje this is used to track faces that are in the foreground we should not draw thes but they are hitested against
#define FACE_BACKFACING (1<<12) //watje this is used to track which faces are back faacing this is a temporary flag
// The mat ID is stored in the HIWORD of the face flags
#define FACE_MATID_SHIFT 16
#define FACE_MATID_MASK 0xFFFF
class GWFace: public MaxHeapOperators {
public:
DWORD v[3]; // indexed references to the vertex array
DWORD flags; // see face flags description above
};
/*! \defgroup patchDisplayFlags Patch Display Flags
For processWireFaces and general mesh class use */
//@{
#define DISP_VERTTICKS (1<<0) //!< Display vertices as tick marks
#define DISP_SELVERTS (1<<10) //!< Display selected vertices.
#define DISP_SELFACES (1<<11) //!< Display selected faces.
#define DISP_SELEDGES (1<<12) //!< Display selected edges.
#define DISP_SELPOLYS (1<<13) //!< Display selected polygons.
#define DISP_OBJSELECTED (1<<8) //!< Mimics COMP_OBJSELECTED in mesh.h
//@}
// General definitions
#define WM_SHUTDOWN (WM_USER+2001)
#define WM_INIT_COMPLETE (WM_USER+2002)
#define GW_MAX_FILE_LEN 128
#define GW_MAX_CAPTION_LEN 128
#define GW_MAX_VERTS 32
#define GFX_MAX_STRIP 100
#define GFX_MAX_TEXTURES 8
typedef BOOL (*HitFunc)(int, int, void *);
// Rendering modes
#define GW_NO_ATTS 0x0000000
#define GW_WIREFRAME 0x0000001
#define GW_ILLUM 0x0000002
#define GW_FLAT 0x0000004
#define GW_SPECULAR 0x0000008
#define GW_TEXTURE 0x0000010
#define GW_Z_BUFFER 0x0000020
#define GW_PERSP_CORRECT 0x0000040
#define GW_POLY_EDGES 0x0000080
#define GW_BACKCULL 0x0000100
#define GW_TWO_SIDED 0x0000200
#define GW_COLOR_VERTS 0x0000400
#define GW_SHADE_CVERTS 0x0000800
#define GW_PICK 0x0001000
#define GW_BOX_MODE 0x0002000
#define GW_ALL_EDGES 0x0004000
#define GW_VERT_TICKS 0x0008000
#define GW_SHADE_SEL_FACES 0x0010000
#define GW_TRANSPARENCY 0x0020000
#define GW_TRANSPARENT_PASS 0x0040000
#define GW_EMISSIVE_VERTS 0x0080000
#define GW_ALL_OPAQUE 0x0100000
#define GW_EDGES_ONLY 0x0200000
#define GW_CONSTANT 0x0400000
#define GW_HIDDENLINE 0x0800000 //this is the same as constant but the shade color will the color of the background
#define GW_BLENDING 0x1000000
#define GW_DEPTHWRITE_DISABLE 0x2000000 //disable writing into the depth buffer
#define GW_LIGHTING (GW_ILLUM | GW_SPECULAR)
// spotlight shapes
#define GW_SHAPE_RECT 0
#define GW_SHAPE_CIRCULAR 1
// texture tiling
#define GW_TEX_NO_TILING 0
#define GW_TEX_REPEAT 1
#define GW_TEX_MIRROR 2
// texture operations
#define GW_TEX_LEAVE 0 // Use the source pixel value
#define GW_TEX_REPLACE 1 // Use the texture pixel value
#define GW_TEX_MODULATE 2 // Multiply the source with the texture
#define GW_TEX_ADD 3 // Add the source and texture
#define GW_TEX_ADD_SIGNED 4 // Add the source and texture with an 0.5 subtraction
#define GW_TEX_SUBTRACT 5 // Subtract the source from the texture
#define GW_TEX_ADD_SMOOTH 6 // Add the source and the texture then subtract their product
#define GW_TEX_ALPHA_BLEND 7 // Alpha blend the texture with the source
#define GW_TEX_PREMULT_ALPHA_BLEND 8 // Alpha blend the the source with a premultiplied alpha texture
#define GW_TEX_ALPHA_BLEND2 9 // Alpha blend the the source with a premultiplied alpha texture with GL_MODULATE as the tex env instead of GL_DECAL.
// texture scale factors
#define GW_TEX_SCALE_1X 0 // Multiply the tex op result by 1
#define GW_TEX_SCALE_2X 1 // Multiply the tex op result by 2
#define GW_TEX_SCALE_4X 2 // Multiply the tex op result by 4
// texture alpha sources
#define GW_TEX_ZERO 0 // Use no alpha value
#define GW_TEX_SOURCE 1 // Use the source alpha
#define GW_TEX_TEXTURE 2 // Use the texture alpha
#define GW_TEX_CONSTANT 3 // Use a constant BGRA color as an alpha
#define GW_TEX_PREVIOUS 4 // Use the previous texture stage alpha
// View volume clip flags
#define GW_LEFT_PLANE 0x0100
#define GW_RIGHT_PLANE 0x0200
#define GW_BOTTOM_PLANE 0x0400
#define GW_TOP_PLANE 0x0800
#define GW_FRONT_PLANE 0x1000
#define GW_BACK_PLANE 0x2000
#define GW_PLANE_MASK 0x3f00
// edge styles
#define GW_EDGE_SKIP 0
#define GW_EDGE_VIS 1
#define GW_EDGE_INVIS 2
// buffer types (for dual-plane stuff)
#define BUF_F_BUFFER 0
#define BUF_Z_BUFFER 1
// support method return values
#define GW_DOES_SUPPORT TRUE
#define GW_DOES_NOT_SUPPORT FALSE
// support queries
#define GW_SPT_TXT_CORRECT 0 // allow persp correction to be toggled?
#define GW_SPT_GEOM_ACCEL 1 // do 3D xforms, clipping, lighting thru driver?
#define GW_SPT_TRI_STRIPS 2 // send down strips instead of individual triangles?
#define GW_SPT_DUAL_PLANES 3 // allow dual planes to be used?
#define GW_SPT_SWAP_MODEL 4 // update viewports with complete redraw on WM_PAINT?
#define GW_SPT_INCR_UPDATE 5 // redraw only damaged areas on object move?
#define GW_SPT_1_PASS_DECAL 6 // do decaling with only one pass?
#define GW_SPT_DRIVER_CONFIG 7 // allow driver config dialog box?
#define GW_SPT_TEXTURED_BKG 8 // is viewport background a texture?
#define GW_SPT_VIRTUAL_VPTS 9 // are viewports bigger than the window allowed?
#define GW_SPT_PAINT_DOES_BLIT 10 // does WM_PAINT cause a backbuffer blit?
#define GW_SPT_WIREFRAME_STRIPS 11 // if true, wireframe objects are sent as tristrips
#define GW_SPT_ORG_UPPER_LEFT 12 // true if device origin is at upper left, false o/w
#define GW_SPT_ARRAY_PROCESSING 13 // true if the driver can handle vertex array data
#define GW_SPT_NUM_LIGHTS 14 // number of lights supported
#define GW_SPT_NUM_TEXTURES 15 // number of multitexture stages supported
#define GW_SPT_WIRE_FACES 16 // support for wireframe faces with visibility flags
#define GW_SPT_TOTAL 17 // always the max number of spt queries
// display state of the graphics window
#define GW_DISPLAY_MAXIMIZED 1
#define GW_DISPLAY_WINDOWED 2
#define GW_DISPLAY_INVISIBLE 3
// multi-pass rendering
#define GW_PASS_ONE 0
#define GW_PASS_TWO 1
// light types
enum LightType { OMNI_LGT, SPOT_LGT, DIRECT_LGT, AMBIENT_LGT };
// Light attenuation types -- not fully implemented
#define GW_ATTEN_NONE 0x0000
#define GW_ATTEN_START 0x0001
#define GW_ATTEN_END 0x0002
#define GW_ATTEN_LINEAR 0x0010
#define GW_ATTEN_QUAD 0x0020
// General 3D light structure
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data
Types</a>.\n\n
\par Description:
This class describes the lights used in the interactive renderer. All methods
of this class are implemented by the system. */
class Light : public BaseInterfaceServer {
public:
/*! \remarks Class constructor. Sets the default values of the light.\n\n
<b>type = OMNI_LGT;</b>\n\n
<b>attenType = NO_ATTEN;</b>\n\n
<b>atten = (float)0.0;</b>\n\n
<b>intensity = (float)1.0;</b>\n\n
<b>angle = (float)30.0;</b>\n\n
<b>color[0] = (float)1.0;</b>\n\n
<b>color[1] = (float)1.0;</b>\n\n
<b>color[2] = (float)1.0;</b>
\par Data Members:
<b>LightType type;</b>\n\n
One of the following values:\n\n
<b>OMNI_LGT</b>\n\n
Omni-directional.\n\n
<b>SPOT_LGT</b>\n\n
Spot light.\n\n
<b>DIRECT_LGT</b>\n\n
Directional light.\n\n
<b>AMBIENT_LGT</b>\n\n
Ambient light - global illumination.\n\n
<b>Point3 color;</b>\n\n
The color of the light. Individual values are from 0.0 to 1.0 with 1.0 as
white.\n\n
<b>Attenuation attenType;</b>\n\n
Attenuation is not currently implemented. A developer should pass
<b>NO_ATTEN</b>.\n\n
<b>float atten;</b>\n\n
Note: Attenuation is not currently implemented.\n\n
Light attenuation factor.\n\n
<b>float intensity;</b>\n\n
Light multiplier factor.\n\n
<b>float angle;</b>\n\n
Angle of cone for spot and cone lights in degrees.\n\n
<b>int shape;</b>\n\n
One of the following values:\n\n
<b>GW_SHAPE_RECT</b> - Rectangular spotlights.\n\n
<b>GW_SHAPE_CIRCULAR</b> - Circular spotlights.\n\n
<b>float aspect;</b>\n\n
The aspect ratio of the light.\n\n
<b>int overshoot;</b>\n\n
Nonzero indicates the light supports overshoot; otherwise 0.\n\n
<b>BOOL affectDiffuse;</b>\n\n
This data member is available in release 2.0 and later only.\n\n
This defaults to TRUE, but if the user set it to FALSE in the light
modifier panel, then the\n\n
light is not supposed to illuminate the diffuse component of an object's
material.\n\n
<b>BOOL affectSpecular;</b>\n\n
This data member is available in release 2.0 and later only.\n\n
This defaults to TRUE, but if the user set it to FALSE in the light
modifier panel, then the\n\n
light is not supposed to illuminate the specular component of an object's
material. */
DllExport Light();
LightType type;
Point3 color;
int attenType;
float attenStart;
float attenEnd;
float intensity;
float hotSpotAngle;
float fallOffAngle;
int shape;
float aspect;
int overshoot;
BOOL affectDiffuse;
BOOL affectSpecular;
};
enum CameraType { PERSP_CAM, ORTHO_CAM };
// General camera structure
class Camera : public BaseInterfaceServer {
public:
DllExport Camera();
void setPersp(float f, float asp)
{ type = PERSP_CAM; persp.fov = f;
persp.aspect = asp; makeMatrix(); }
void setOrtho(float l, float t, float r, float b)
{ type = ORTHO_CAM; ortho.left = l; ortho.top = t;
ortho.right = r; ortho.bottom = b; makeMatrix(); }
void setClip(float h, float y)
{ hither = h; yon = y; makeMatrix(); }
CameraType getType(void) { return type; }
float getHither(void) { return hither; }
float getYon(void) { return yon; }
DllExport void reset();
DllExport void getProj(float mat[4][4]);
private:
DllExport void makeMatrix();
float proj[4][4];
CameraType type;
union {
struct : public MaxHeapOperators {
float fov;
float aspect;
} persp;
struct : public MaxHeapOperators {
float left;
float right;
float bottom;
float top;
} ortho;
};
float hither;
float yon;
};
const double pi = 3.141592653589793;
const double piOver180 = 3.141592653589793 / 180.0;
// Color types (used by setColor)
enum ColorType { LINE_COLOR, FILL_COLOR, TEXT_COLOR, CLEAR_COLOR };
// Marker types
enum MarkerType { POINT_MRKR, HOLLOW_BOX_MRKR, PLUS_SIGN_MRKR,
ASTERISK_MRKR, X_MRKR, BIG_BOX_MRKR,
CIRCLE_MRKR, TRIANGLE_MRKR, DIAMOND_MRKR,
SM_HOLLOW_BOX_MRKR, SM_CIRCLE_MRKR,
SM_TRIANGLE_MRKR, SM_DIAMOND_MRKR,
DOT_MRKR, SM_DOT_MRKR,
BOX2_MRKR, BOX3_MRKR, BOX4_MRKR, BOX5_MRKR,
BOX6_MRKR, BOX7_MRKR,
DOT2_MRKR, DOT3_MRKR, DOT4_MRKR, DOT5_MRKR,
DOT6_MRKR, DOT7_MRKR
};
#define AC_DIR_RL_CROSS 0 // right->left => crossing (AutoCAD compatible)
#define AC_DIR_LR_CROSS 1 // left->right => crossing (ACAD incompatible)
DllExport void setAutoCross(int onOff);
DllExport int getAutoCross();
DllExport void setAutoCrossDir(int dir);
DllExport int getAutoCrossDir();
// Region types (for built-in hit-testing)
#define POINT_RGN 0x0001
#define RECT_RGN 0x0002
#define CIRCLE_RGN 0x0004
#define FENCE_RGN 0x0008
// region directions (left or right)
#define RGN_DIR_UNDEF -1
#define RGN_DIR_RIGHT 0
#define RGN_DIR_LEFT 1
struct CIRCLE: public MaxHeapOperators
{
LONG x;
LONG y;
LONG r;
};
/*! \sa <a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data
Types</a>.\n\n
\par Description:
This class describes the properties of a region used for built-in hit testing
of items in the interactive renderer.
\par Data Members:
<b>int type;</b>\n\n
The region type. One of the following values:\n\n
<b>POINT_RGN</b>\n\n
A single point.\n\n
<b>RECT_RGN</b>\n\n
A rectangular region.\n\n
<b>CIRCLE_RGN</b>\n\n
A circular region.\n\n
<b>FENCE_RGN</b>\n\n
An arbitrary multi-point polygon region.\n\n
<b>int crossing;</b>\n\n
If nonzero, elements that are contained within <b>or cross</b> the region
boundary are hit. If zero, only those elements <b>entirely within</b> the
boundary are hit. This is not used for point hit testing.\n\n
<b>int epsilon;</b>\n\n
Specifies the distance in pixels outside the pick point within which elements
may be and still be hit. This is not used for rect or circle testing, is sometimes used with fence hit
testing, where it doubles the size of the region, especially when selecting subobject edges or vertices
and is always used for point hit testing.\n\n
<b>union {</b>\n\n
<b>POINT pt;</b>\n\n
<b>RECT rect;</b>\n\n
<b>CIRCLE circle;</b>\n\n
<b>POINT *pts;</b>\n\n
<b>};</b>\n\n
The storage for the region. */
class HitRegion: public MaxHeapOperators {
DWORD size;
public:
int type;
int dir; // region direction
int crossing; // not used for point
int epsilon; // not used for rect or circle
union {
POINT pt;
RECT rect;
CIRCLE circle;
POINT * pts;
};
HitRegion() { dir = RGN_DIR_UNDEF; size = sizeof(HitRegion);}
};
inline int ABS(const int x) { return (x > 0) ? x : -x; }
typedef void (*GFX_ESCAPE_FN)(void *);
// driver types for getDriver() method
#define GW_DRV_RENDERER 0
#define GW_DRV_DEVICE 1
// for possible future implementation
#define GW_HEIDI 0
#define GW_OPENGL 1
#define GW_DIRECT3D 2
#define GW_HEIDI3D 3
#define GW_NULL 4
#define GW_CUSTOM 5
// graphics window setup structure
/*! \sa Class GraphicsWindow.\n\n
\par Description:
This class is the graphics window setup structure. An instance of this class is
passed to the function <b>createGW()</b> to create a new graphics window.\n\n
Note: This is no longer available for use by plug-ins in 3ds Max 2.0 and later.
*/
class GWinSetup: public MaxHeapOperators {
public:
DllExport GWinSetup();
MCHAR caption[GW_MAX_CAPTION_LEN];
MCHAR renderer[GW_MAX_FILE_LEN];
MCHAR device[GW_MAX_FILE_LEN];
DWORD winStyle;
POINT size;
POINT place;
INT_PTR id;
// WIN64 Cleanup: Shuler
int type;
bool quietMode;
};
// abstract graphics window class
/*! \sa Class InteractiveRenderer for Graphics Window,
Class GWinSetup, Class HitRegion, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>,
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">List of Rendering Limits</a>,
Class Point3, Class IPoint3, Class Matrix3, Class Interface, Class ViewExp.\n\n
\par Description:
The abstract graphics window class. The methods here provide low-level access
to 3ds Max's graphics system. These methods are available for plug-ins to do
any graphics work not possible using the standard high-level graphics methods
of 3ds Max.\n\n
These methods are for use in the existing 3ds Max viewports. Note that these
APIs are not for casual use, as they are not intended to be a high level
graphics library. For example, many steps are required to display a single lit
polygon. These APIs are optimized for speed, and not at all for plug-in
programmer ease of use.\n\n
These methods are provided, however, so that developers can do things that are
otherwise impossible using the high-level methods.\n\n
<b>Developers should use these methods with an understanding of exactly what
they are doing since it's quite easy to crash 3ds Max when inappropriate
arguments are supplied. The calls are specifically optimized for exactly the
way 3ds Max uses them. In no way should the calls in GraphicsWindow be
considered an "ordinary" 2D/3D API. (That's what OpenGL, D3D, and HEIDI are
for.)</b>\n\n
One final note of warning: most graphics windows methods execute in a separate
thread (or in multiple separate threads) that are owned by the graphics window.
Thus, due to thread scheduling, when a bad argument or incorrect sequencing of
graphics windows calls causes 3ds Max to crash, it is not at all easy to figure
out where the problem is. In particular, the location of the main 3ds Max
thread is not relevant.\n\n
All the methods of this class are implemented by the system.
\par Method Groups:
See <a href="class_graphics_window_groups.html">Method Groups for Class GraphicsWindow</a>.
*/
class GraphicsWindow : public InterfaceServer {
public:
virtual ~GraphicsWindow() {}
/*! \remarks This is called after all four GraphicsWindows used by 3ds Max are created.
SDK users shouldn't need this call */
virtual void postCreate(int ct, GraphicsWindow **gw) = 0;
/*! \remarks This is used to tell the driver that it is shutting down. */
virtual void shutdown() = 0;
/*! \remarks This returns "0x200" to indicate R2.0 */
virtual int getVersion() = 0;
/*! \remarks This identifies the driver (and includes manufacturer info if available) */
virtual MCHAR * getDriverString(void) = 0;
/*! \remarks This is called to put up the config dialog if the driver supports
GW_SPT_CAN_CONFIG
\par Parameters:
<b>HWND hWnd</b>\n\n
The parent window handle for the dialog. */
virtual void config(HWND hWnd) = 0;
/*! \remarks Determines if the driver supports the specified feature.
\par Parameters:
<b>int what</b>\n\n
One of the following values:\n\n
<b>GW_SPT_TXT_CORRECT</b>\n\n
This is used to enable or gray-out the perspective correction right-click
viewport menu option.\n\n
<b>GW_SPT_GEOM_ACCEL</b>\n\n
This is used to indicate to 3ds Max (and the mesh class in particular) that
the driver wants to handle all of the 3D data natively. In this case,
meshes are rendered by passing 3D world space data and letting the driver
transform, clip, and light the vertices. If this returns FALSE, then the
mesh class handles all xforms/clip/lighting calculations (using a lazy
evaluation algorithm) and then calls the hPolygon or hPolyline 2 1/2D calls
for the driver to rasterize. (Primitives that are actually clipped are
still sent to the polygon/polyline methods.)\n\n
Right now, only the OpenGL driver returns TRUE to this query, but other
drivers have been developed that return TRUE, and the HEIDI and D3D drivers
may change in the future.\n\n
<b>GW_SPT_TRI_STRIPS</b>\n\n
If this returns TRUE, then 3ds Max will try to stripify meshes before
calling the rendering methods. Right now, the drivers just return the user
preference that is set in the driver config dialog. It defaults to
TRUE.\n\n
<b>GW_SPT_DUAL_PLANES</b>\n\n
If a driver has dual-planes support it returns TRUE. Our OpenGL display
driver only returns TRUE for this if the underlying display driver has
implemented a custom OpenGL extension that allows us to handle this
efficiently.\n\n
<b>GW_SPT_SWAP_MODEL</b>\n\n
This returns TRUE if 3ds Max has to redraw the whole scene any time the
viewports are exposed.\n\n
<b>GW_SPT_INCR_UPDATE</b>\n\n
This returns TRUE if the driver can update a rectangular subset of the
viewport without trashing the image outside that rectangle. This is TRUE
for most drivers that blit the viewport region and FALSE for those that do
page-flipping in the hardware. For OpenGL, this is TRUE if the display
driver implements the Microsoft glSwapRectHintWIN extension.\n\n
<b>GW_SPT_1_PASS_DECAL</b>\n\n
This is TRUE if the driver can handle decalling with only one pass. Right
now, this is TRUE for OpenGL, but FALSE for HEIDI and D3D. (And as with all
of these options, it may change in a given driver anytime in the
future.)\n\n
<b>GW_SPT_DRIVER_CONFIG</b>\n\n
This is TRUE if the driver has a configuration dialog box. This is TRUE for
all three of our standard drivers.\n\n
<b>GW_SPT_TEXTURED_BKG</b>\n\n
This is TRUE if the viewport background is implemented as a textured
rectangle, and FALSE if it is a blitted bitmap.\n\n
<b>GW_SPT_VIRTUAL_VPTS</b>\n\n
This is TRUE if the driver allows viewports to be made larger than the
physical window they are attached to. Right now this is ony TRUE for
OGL.\n\n
<b>GW_SPT_PAINT_DOES_BLIT</b>\n\n
This is TRUE if WM_PAINT messages result in a blit of the backbuffer (as
opposed to a page-flipping swap). This allows 3ds Max to do quick damage
region repair, and works together with the GW_SPT_SWAP_MODEL flag.\n\n
<b>GW_SPT_WIREFRAME_STRIPS</b>\n\n
This is TRUE if the driver wants 3ds Max to send down wireframe models
using triangle strips instead of a bundle of 2-pt segments. This is only
used by the OGL driver, and it is there as a user-choosable
performance-accuracy tradeoff (since the strips are faster and are
back-culled, but they displayhidden edges as though they are visible). */
virtual int querySupport(int what) = 0;
/*! \remarks This returns the "output" window handle. (Input goes to an invisible window
above the viewport. The invisible window is owned by 3ds Max.) */
virtual HWND getHWnd(void) = 0;
/*! \remarks Sets the size and position of the GraphicsWindow. The
coordinates are all Windows coordinates in the space of the
GraphicsWindows' parent window. (The origin is the upper left.)
\par Parameters:
<b>int x</b>\n\n
Window x origin.\n\n
<b>int y</b>\n\n
Window y origin.\n\n
<b>int w</b>\n\n
Window width.\n\n
<b>int h</b>\n\n
Window height. */
virtual void setPos(int x, int y, int w, int h) = 0;
/*! \remarks The specified value may be sent to the driver to indicate the display state
of the viewport window controlled by the driver.
\par Parameters:
<b>int s</b>\n\n
The display state to set. One of the following values:\n\n
<b>GW_DISPLAY_MAXIMIZED</b>\n\n
<b>GW_DISPLAY_WINDOWED</b>\n\n
<b>GW_DISPLAY_INVISIBLE</b> */
virtual void setDisplayState(int s) = 0;
/*! \remarks This method returns the current state. One of the following values:\n\n
<b>GW_DISPLAY_MAXIMIZED</b>\n\n
<b>GW_DISPLAY_WINDOWED</b>\n\n
<b>GW_DISPLAY_INVISIBLE</b> */
virtual int getDisplayState() = 0;
/*! \remarks This method gets the current window size in X. */
virtual int getWinSizeX() = 0;
/*! \remarks This method gets the current window size in Y. */
virtual int getWinSizeY() = 0;
/*! \remarks This method returns the z-buffer depth (in bits) */
virtual DWORD getWinDepth(void) = 0;
/*! \remarks This method returns the largest device Z value. */
virtual DWORD getHitherCoord(void) = 0;
/*! \remarks This method returns the smallest device Z value. */
virtual DWORD getYonCoord(void) = 0;
/*! \remarks This method returns the size (in pixels) that the specified text string
will occupy
\par Parameters:
<b>MCHAR *text</b>\n\n
The string to check.\n\n
<b>SIZE *sp</b>\n\n
The size is returned here. See
<a href="ms-its:3dsmaxsdk.chm::/start_data_types.html">Data Types</a>. */
virtual void getTextExtents(MCHAR *text, SIZE *sp) = 0;
/*! \remarks This method returns the largest number of triangles that can be in a strip
*/
virtual int getMaxStripLength() { return GFX_MAX_STRIP; }
virtual void setFlags(DWORD f) = 0;
virtual DWORD getFlags() = 0;
/*! \remarks This method resets the update rectangle. The update rectangle
is the region of the screen that needs to be updated to reflect items that
have changed. When the system is done rendering items, the goal is to only
update the region that has actually been altered. This method sets the
update rectangle (the region that will be blitted to the display) to
invalid. In this way when <b>enlargeUpdateRect()</b> is later called, the
RECT passed will be used as the region. */
virtual void resetUpdateRect() = 0;
/*! \remarks This method enlarges the update rectangle to include the RECT
passed. If <b>rp</b> is NULL, then the whole window will later be updated.
\par Parameters:
<b>RECT *rp</b>\n\n
Pointer to a rectangle (or NULL). */
virtual void enlargeUpdateRect(RECT *rp) = 0;
/*! \remarks This method retrieves the current update rectangle.
\par Parameters:
<b>RECT *rp</b>\n\n
The current update rectangle.
\return Zero if the update rectangle is invalid; otherwise nonzero. */
virtual int getUpdateRect(RECT *rp) = 0;
/*! \remarks This method is used internally and should not be called by
plug-in developers. */
virtual void updateScreen() = 0;
/*! \remarks This method is used internally. Most drivers control two
image buffers. One is displayed on the screen, and the other is used to
rasterize geometric primitives. When rasterization of a complete frame is
done, the off-screen buffer is blitted onto the display screen. This is
referred to as dual-plane mode. This method will turn dual-plane mode on or
off. This is used internally by the File/Preferences... Viewport page Use
Dual Planes toggle.
\par Parameters:
<b>int which</b>\n\n
Specifies which buffer should use dual-planes.\n\n
<b>BUF_F_BUFFER</b>\n\n
The image (Framebuffer) buffer.\n\n
<b>BUF_Z_BUFFER</b>\n\n
The Z buffer.\n\n
<b>int b</b>\n\n
Nonzero to enable access (toggle on); 0 to toggle off.
\return TRUE if the graphics window has access to the specified buffer;
otherwise FALSE. */
virtual BOOL setBufAccess(int which, int b) = 0;
/*! \remarks This method is used internally. It returns a boolean value
indicating if dual plane mode is on or off for the specified buffer.
\par Parameters:
The buffer whose dual-planes setting will be returned.\n\n
<b>int which</b>\n\n
The buffer whose dual-planes setting will be returned. One of the following
values:\n\n
<b>BUF_F_BUFFER</b>\n\n
The Framebuffer.\n\n
<b>BUF_Z_BUFFER</b>\n\n
The Z buffer.
\return TRUE if the dual-plane mode is on; otherwise FALSE. */
virtual BOOL getBufAccess(int which) = 0;
/*! \remarks This method is used internally. It retrieves the size of the
specified buffer in bytes.
\par Parameters:
<b>int which</b>\n\n
One of the following values:\n\n
<b>int *size</b>\n\n
The size of the buffer in bytes.\n\n
Note the following concerning the HEIDI driver. For HEIDI getBufSize()
always returns 10 if dual-planes are on (and 0 otherwise). This is because
HEIDI actually never returns the image - it keeps its own copy stored away.
Thus the "logical" way to think is that we actually get a copy of the
buffer by calling getBuf, and that we give it back by calling setBuf. But
in reality (with the HEIDI driver) getBuf and setBuf only tell HEIDI to do
some internal buffer manipulation.
\return TRUE if the size was returned; otherwise FALSE. */
virtual BOOL getBufSize(int which, int *size) = 0;
/*! \remarks This method is used internally. It retrieves the specified
buffer.
\par Parameters:
<b>int which</b>\n\n
The buffer to retrieve. One of the following values:\n\n
<b>BUF_F_BUFFER -</b> The image Framebuffer.\n\n
<b>BUF_Z_BUFFER -</b> The Z buffer.\n\n
<b>int size</b>\n\n
The number of bytes to retrieve. This must be at least the size returned
from <b>getBufSize()</b>.\n\n
<b>void *buf</b>\n\n
Storage for the buffer data.
\return TRUE if the buffer was retrieved; otherwise FALSE. */
virtual BOOL getBuf(int which, int size, void *buf) = 0;
/*! \remarks Stores the specified buffer.
\par Parameters:
<b>int which</b>\n\n
The buffer to store. One of the following values:\n\n
<b>BUF_F_BUFFER -</b> The image Framebuffer.\n\n
<b>BUF_Z_BUFFER -</b> The Z buffer.\n\n
<b>int size</b>\n\n
The number of bytes to store.\n\n
<b>void *buf</b>\n\n
The buffer data.\n\n
<b>RECT *rp</b>\n\n
This allows only a subset of the saved image rect to be blitted back to the
screen.
\return TRUE if the buffer was stored; otherwise FALSE. */
virtual BOOL setBuf(int which, int size, void *buf, RECT *rp) = 0;
/*! \remarks This method returns the viewport image of this graphics
window in a packed DIB format. A packed DIB is the standard BMI header
followed immediately by all the data bytes (pixels) that make up the image.
This is the standard way in Windows to pass a DIB around. See the sample
code below for an example of this call in use. Note how it is called twice:
once to get the size, once to get the DIB.
\par Parameters:
<b>BITMAPINFO *bmi</b>\n\n
The BITMAPINFO structure defines the dimensions and color information for a
Windows device-independent bitmap (DIB). Note that if this parameter is
NULL, then only the size value is returned.\n\n
<b>int *size</b>\n\n
The size of the image in bytes.
\return TRUE if the image was returned; otherwise FALSE.
\par Sample Code:
The following sample code saves the current 3ds Max viewport to a user
specified file.\n\n
\code
void TestGetDIB(IObjParam *ip)
{
BITMAPINFO *bmi = NULL;
BITMAPINFOHEADER *bmih;
BitmapInfo biFile;
Bitmap *map;
int size;
TheManager->SelectFileOutput(\&biFile,
ip->GetMAXHWnd(), _M("Testing"));
if(!biFile.Name()[0])
return;
ViewExp *vpt = ip->GetActiveViewport();
vpt->getGW()->getDIB(NULL, \&size);
bmi = (BITMAPINFO *)malloc(size);
bmih = (BITMAPINFOHEADER *)bmi;
vpt->getGW()->getDIB(bmi, \&size);
biFile.SetWidth((WORD)bmih->biWidth);
biFile.SetHeight((WORD)bmih->biHeight);
biFile.SetType(BMM_TRUE_32);
map = TheManager->Create(\&biFile);
map->OpenOutput(\&biFile);
map->FromDib(bmi);
map->Write(\&biFile);
map->Close(\&biFile);
if(bmi)
free(bmi);
ip->ReleaseViewport(vpt);
}
\endcode */
virtual BOOL getDIB(BITMAPINFO *bmi, int *size) = 0;
/*! \remarks This method is used internally to zoom the viewport. */
virtual BOOL setBackgroundDIB(int width, int height, BITMAPINFO *bmi) = 0;
/*! \remarks This method is used internally to pan the viewport. */
virtual void setBackgroundOffset(int x, int y) = 0;
virtual int useClosestTextureSize(int bkg=FALSE) = 0;
/*! \remarks This method returns the size of the texture bitmap that the driver wants
sent in to the <b>getTextureHandle()</b> call (if bkg is FALSE). If bkg is
TRUE, this returns the size of the texture that 3ds Max shoud send to the
<b>setBackgroundDIB()</b> call. In general, the return value needs to be a
power of 2, though that could be driver-specific
\par Parameters:
<b>int bkg=FALSE</b>\n\n
TRUE to get the size for <b>setBackgroundDIB()</b>; FALSE to get the size
for <b>getTextureHandle()</b>. */
virtual int getTextureSize(int bkg=FALSE) = 0;
/*! \remarks This method returns a handle for the specified texture bitmap.
This handle is then used with the <b>setTextureByHandle()</b> method (there is
only one current texture active at any time). The texture dimensions must be a
power of 2.\n\n
When a material is on an object, and the material has a texture map, and when
the button used to display the texture map is pressed, 3ds Max calls this
method to get the texture handle. This basically loads the texture into the
hardware RAM (if available). When this mapped object gets displayed the method
<b>setTextureHanel()</b> is called. When the material is deleted, or the
dispaly in viewport button is turned off, <b>freeTextureHandle()</b> is called.
\par Parameters:
<b>BITMAPINFO *bmi</b>\n\n
The DIB image to use as a texture.
\return The texture handle. */
virtual DWORD_PTR getTextureHandle(BITMAPINFO *bmi) = 0;
/*! \remarks When you are finished with the texture handle, call this method
to free it.
\par Parameters:
<b>DWORD_PTR handle</b>\n\n
The texture handle to free.
\return TRUE if the texture was set; otherwise FALSE. */
virtual void freeTextureHandle(DWORD_PTR handle) = 0;
/*! \remarks This sets the current texture to the image whose handle is passed
(see <b>getTextureHandle()</b>). The texture dimensions must be a power of 2.
\par Parameters:
<b>DWORD_PTR handle</b>\n\n
The handle of the texture to make current. */
virtual BOOL setTextureByHandle(DWORD_PTR handle, int texStage=0) = 0;
// WIN64 Cleanup: Shuler
virtual void setTextureColorOp(int texStage=0, int texOp=GW_TEX_MODULATE, int texAlphaSource=GW_TEX_TEXTURE, int texScale=GW_TEX_SCALE_1X) = 0;
virtual void setTextureAlphaOp(int texStage=0, int texOp=GW_TEX_MODULATE, int texAlphaSource=GW_TEX_TEXTURE, int texScale=GW_TEX_SCALE_1X) = 0;
/*! \remarks Sets the way in which textures are tiled across the surface of
the object.
\par Parameters:
The following parameters may use one of these values:\n\n
<b>GW_TEX_NO_TILING</b>\n\n
The texture clamped - Any UVW that is bigger than 1 is interpreted as being
1.\n\n
<b>GW_TEX_REPEAT</b>\n\n
As the UVW numbers keep getting larger than 1 the image is repeated.\n\n
<b>GW_TEX_MIRROR</b>\n\n
If UVW goes beyond 1, the numbers are interpreted as going backwards. So if you
had 0 to 2 it would actually go 0 to 1 then 1 down to 0.\n\n
<b>int u</b>\n\n
The type of texturing in the U direction.\n\n
<b>int v</b>\n\n
The type of texturing in the V direction.\n\n
<b>int w=GW_TEX_NO_TILING</b>\n\n
The type of texturing in the W direction.
\return TRUE if the tiling mode was set; otherwise FALSE. */
virtual BOOL setTextureTiling(int u, int v, int w=GW_TEX_NO_TILING, int texStage=0) = 0;
/*! \remarks Returns the type of texture tiling set for the particular
direction.\n\n
For example, if <b>setTextureTiling(GW_TEX_NO_TILING, GW_TEX_REPEAT,
GW_TEX_MIRROR)</b> were called first, then\n\n
<b>getTextureTiling(0)</b> would yield <b>GW_TEX_NO_TILING</b>, and\n\n
<b>getTextureTiling(1)</b> would yield <b>GW_TEX_REPEAT</b>.
\par Parameters:
<b>int which</b>\n\n
This value is 0 or 1 and it represents the U or V direction respectively. The
value 2 is not yet implemented.
\return <b>GW_TEX_NO_TILING</b>\n\n
The texture clamped - Any UVW that is bigger than 1 is interpreted as being
1.\n\n
<b>GW_TEX_REPEAT</b>\n\n
As the UVW numbers keep getting larger than 1 the image is repeated.\n\n
<b>GW_TEX_MIRROR</b>\n\n
If UVW goes beyond 1, the numbers are interpreted as going backwards. So if you
had 0 to 2 it would actually go 0 to 1 then 1 down to 0. */
virtual int getTextureTiling(int which, int texStage=0) = 0;
/*! \remarks If a developer is working with an existing 3ds Max instance
of GraphicsWindow (one of 3ds Max's viewports) this method should NOT be
called. */
virtual void beginFrame() = 0;
/*! \remarks As above, if a developer is working with an existing 3ds Max
instance of GraphicsWindow (one of 3ds Max's viewports) this method should
NOT be called. */
virtual void endFrame() = 0;
/*! \remarks This method sets the clipping boundaries within a viewport
within the graphics window. This allows more than one viewport to appear
within a single graphics window. It has the side-effect of building a 4x4
viewport matrix. This routine should be called anytime the graphics window
is resized, or else rendering will still occur to the old window size. (And
since most drivers do not do range-checking since it is too time-costly,
this could cause a system crash.)
\par Parameters:
Note: all coordinates are in Windows format, with the origin in the upper
left\n\n
<b>int x</b>\n\n
Specifies the left viewport origin.\n\n
<b>int y</b>\n\n
Specifies the top viewport origin.\n\n
<b>int w</b>\n\n
Specifies the viewport width.\n\n
<b>int h</b>\n\n
Specifies the viewport height. */
virtual void setViewport(int x, int y, int w, int h) = 0;
/*! \remarks This method is used to setup a virtual viewport. Note that this is a no-op
unless <b>GW_SPT_VIRTUAL_VPTS</b> is TRUE. Plug-in developers should not
call this method -- it's for internal use only. */
virtual void setVirtualViewportParams(float zoom, float xOffset, float yOffset) = 0;
/*! \remarks This method is used to set a virtual viewport as active. Note that this is
a no-op unless <b>GW_SPT_VIRTUAL_VPTS</b> is TRUE. Plug-in developers
should not call this method -- it's for internal use only.
\par Parameters:
<b>int onOff</b>\n\n
TRUE to set the virtual viewport active; FALSE to make it inactive. */
virtual void setUseVirtualViewport(int onOff) = 0;
/*! \remarks Clears the specified rectangular region of the screen.
\par Parameters:
<b>RECT *rp</b>\n\n
Specifies the rectangular region to clear.\n\n
<b>int useBkg = FALSE</b>\n\n
Specifies if the background should be used to fill the cleared area.
Nonzero indicate the background should be used; 0 indicates the 'clear'
color should be used (see <b>setColor()</b> above). */
virtual void clearScreen(RECT *rp, int useBkg = FALSE) = 0;
/*! \remarks Sets the current transformation matrix, and updates the
modeling coordinates to normalized projection coordinates matrix. This
routine also back-transforms each light and the eye point (so that lighting
can be done in modeling coordinates).\n\n
This method may be used to set a matrix that transforms the point passed to
the drawing methods (like <b>text(), marker(), polyline()</b> or
<b>polygon()</b>). Normally these methods expect world coordinates. However
if this matrix is set to an objects transformation matrix you can pass
objects space coordinates and they will be transformed into world space
(and then put into screen space when they are drawn). If however this is
set to the identity matrix you would pass world space coordinates. You can
set this matrix to the objects matrix using the following code:\n\n
<b>gw-\>setTransform(inode-\>GetObjectTM(t));</b>\n\n
Note: For world-to-screen space conversions by the methods <b>text(),
marker(), polyline()</b>, <b>polygon()</b>, etc, a developer must
explicitly set this matrix to the identity. This is because the
<b>GraphicsWindow</b>transform may have a non-identity matrix already in
place from a previous operation.
\par Parameters:
<b>const Matrix3 \&m</b>\n\n
The new current transformation matrix. */
virtual void setTransform(const Matrix3 &m) = 0;
virtual Matrix3 getTransform(void) = 0;
virtual void multiplePass(int pass, BOOL onOff, float scaleFact = 1.005f) = 0;
/*! \remarks Sets the current transparency flags for the current pass.\n\n
\par Parameters:
<b>DWORD settings</b>\n\n
This can be a combination if GW_TRANSPARENCY and GW_TRANSPARENT_PASS See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. You
also use these settings in the Render limits as well. */
virtual void setTransparency(DWORD settings) = 0;
/*! \remarks This method allows one to put an affine transformation on a
texture. This allows you to translate, rotate or scale a texture on an object.
\par Parameters:
<b>const Matrix3 \&m</b>\n\n
The texture transformation matrix. */
virtual void setTexTransform(const Matrix3 &m, int texStage=0) = 0;
/*! \remarks This is used internally. It returns if the determinant of the
current transform is positive or negative. If it's positive 0 is returned;
if it's negative 1 is returned. */
virtual BOOL getFlipped(void)=0;
/*! \remarks Sets the number of triangles skipped when the viewport is set
as a 'Fast View Display' viewport. To disable fastview, specify 1. Note
that the GraphicsWindow class doesn't actually do anything with this number
other than store it. Since triangles are handed down to GFX one at a time,
it is up to the code that feeds triangles to the GraphicsWindow to skip the
specified number of triangles. The mesh rendering in 3ds Max uses the skip
count in this way.
\par Parameters:
<b>int n</b>\n\n
Specifies that every 'n-th' triangle should be drawn. If set to 2, every
other triangle should be drawn. */
virtual void setSkipCount(int c) = 0;
/*! \remarks Returns the current skip count setting. */
virtual int getSkipCount(void) = 0;
virtual void setViewportLimits(DWORD l) = 0;
virtual DWORD getViewportLimits(void) = 0;
/*! \remarks Sets the rendering limits used by primitive calls.\n\n
Note: Setting the rendering limits is used in communication between the
various parts of 3ds Max that handle the display of objects. For example,
setting this limit to <b>GW_POLY_EDGES</b> and then drawing a polygon won't
result in a polygon drawn with edges. It only sets a flag that indicates
the edge should be drawn.\n\n
What happens is as follows. Inside the upper level 3ds Max, part of the
code knows that polygon edges have been turned on. However this is not
related through the object oriented architecture to the part of 3ds Max
that does the actual drawing. When 3ds Max goes to draw objects it will see
that the polygon edge flag is on. This tells it to do two drawing passed --
one to do the polygon, then it calls <b>outlinePass()</b> call with TRUE,
draws a bunch of edges, then calls <b>outline Pass()</b> with FALSE. Thus,
the drawing routine is responsible for looking at the flags and drawing
appropriately. This method is only responsible setting the limit which can
later be checked.
\par Parameters:
<b>DWORD l</b>\n\n
Specifies the rendering limit used by the viewport. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */
virtual void setRndLimits(DWORD l) = 0;
/*! \remarks Retrieves the rendering limits used by primitive calls. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */
virtual DWORD getRndLimits(void) = 0;
/*! \remarks Returns the current rendering mode used by the viewport. This
is a subset of the rendering limit, in that any limits imposed by the
rendering limit are forced onto the current mode. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_rendering_limits.html">Rendering Limits</a>. */
virtual DWORD getRndMode(void) = 0;
/*! \remarks Returns the maximum number of lights that may be used by the
interactive renderer. */
virtual int getMaxLights(void) = 0;
/*! \remarks Turns a light on or off, and sets the light parameters. The
light's position is set through the current transformation matrix at the
time of this call. A particular light is specified by its light number (-1
through <b>getMaxLights()-1</b>). Light number -1 is reserved for ambient
light. If a particular field in the Light class is not needed for a
particular type of light, that field's value is ignored (for example, only
the color field is used for ambient light.)
\par Parameters:
<b>int num</b>\n\n
The light number of the light to set. This is a value in the range -1 to
<b>getMaxLights()-1</b>.\n\n
<b>const Light *l</b>\n\n
The light class instance used to set the light parameters. If this is NULL,
the light is turned off. */
virtual void setLight(int num, const Light *l) = 0;
/*! \remarks This allows a developer to control if a light is used to
render an object. There is one bit per light (bits 0 through
<b>getMaxLights()</b>). If the bit is set the light is NOT used to render
the object. If the bit is off, the light IS used. This method allows you to
set the exclusion vector controlling the lights.
\par Parameters:
<b>DWORD exclVec</b>\n\n
The exclusion vector controlling the lights. */
virtual void setLightExclusion(DWORD exclVec) = 0;
/*! \remarks This method is no longer used. */
virtual void setCamera(const Camera &c) = 0;
/*! \remarks Sets the properties of the current camera used by the
GraphicsWindow.
\par Parameters:
<b>float mat[4][4]</b>\n\n
The transformation matrix times the projection matrix.\n\n
<b>Matrix3 *invTM</b>\n\n
This is the inverse of the affine part of the camera transformation matrix
(not the inverse of the projection part).\n\n
<b>int persp</b>\n\n
Nonzero indicates this is a perspective view; 0 is orthogonal.\n\n
<b>float hither</b>\n\n
Near clip value.\n\n
<b>float yon</b>\n\n
Far clip value. */
virtual void setCameraMatrix(float mat[4][4], Matrix3 *invTM, int persp, float hither, float yon) = 0;
/*! \remarks Retrieves the properties of the current camera.
\par Parameters:
<b>float mat[4][4]</b>\n\n
The transformation matrix times the projection matrix.\n\n
<b>Matrix3 *invTM</b>\n\n
This is the inverse of the affine part of the camera transformation matrix
(not the inverse of the projection part).\n\n
<b>int *persp</b>\n\n
Nonzero indicates this is a perspective view; 0 is orthogonal.\n\n
<b>float *hither</b>\n\n
Near clip value.\n\n
<b>float *yon</b>\n\n
Far clip value. */
virtual void getCameraMatrix(float mat[4][4], Matrix3 *invTM, int *persp, float *hither, float *yon) = 0;
/*! \remarks Sets the RGB color used for the specified drawing type (line,
fill, text, clear).
\par Parameters:
<b>ColorType t</b>\n\n
One of the following values:\n\n
<b>LINE_COLOR</b>\n\n
Line drawing color.\n\n
<b>FILL_COLOR</b>\n\n
Polygon fill color.\n\n
<b>TEXT_COLOR</b>\n\n
Text drawing color.\n\n
<b>CLEAR_COLOR</b>\n\n
The color that the viewport is cleared to when you call
<b>clearScreen()</b>.\n\n
<b>float r</b>\n\n
Specifies the red amount 0.0 - 1.0.\n\n
<b>float g</b>\n\n
Specifies the green amount 0.0 - 1.0.\n\n
<b>float b</b>\n\n
Specifies the blue amount 0.0 - 1.0. */
virtual void setColor(ColorType t, float r, float g, float b) = 0;
void setColor(ColorType t, Point3 clr) { setColor(t,clr.x,clr.y,clr.z); }
/*! \remarks Sets the current rendering material, and modifies the
rendering mode parameter for controlling the rasterizer driver. Note: You
must have your rendering limit set BEFORE you set the material because the
material setting may lower the rendering mode based on the material limits.
\par Parameters:
<b>const Material \&m</b>\n\n
The new material to instantiate\n\n
<b>int index=0</b>\n\n
Indicates which material index refers to the material which gets set. */
virtual void setMaterial(const Material &m, int index=0) = 0;
/*! \remarks Returns the current rendering material.\n\n
*/
virtual Material *getMaterial(void) = 0;
virtual int getMaxTextures(void) = 0;
/*! \remarks This method converts coordinates to "<b>h</b>" format device coordinates.
Note: This method maps points from the GraphicsWindow's current transform
to device space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>const Point3 *in</b>\n\n
The input point.\n\n
<b>IPoint3 *out</b>\n\n
The output point in integer format values in the native device coords for
the device. For HEIDI and OpenGL the origin at the lower left. For Direct3D
the origin is at the upper left.
\return DWORD containing the clipping flags for the point. If a flag is
set it indicates the transformed point lies outside the view volume. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */
virtual DWORD hTransPoint(const Point3 *in, IPoint3 *out) = 0;
/*! \remarks This method is used to convert coordinates to "<b>w</b>" format device
coordinates. Note: This method maps points from the GraphicsWindow's
current transform to device space. If the GraphicsWindow's transform is set
to the identity matrix then the mapping is done from points specified in
world space. Otherwise the points given are transformed by the
GraphicsWindow transform, and are <b>then</b> considered to be in world
space. Thus, to get a world-space to screen-space conversion, you need to
set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.\n\n
\par Parameters:
<b>const Point3 *in</b>\n\n
The input point.\n\n
<b>IPoint3 *out</b>\n\n
The output point in integer format with the origin at the upper left.
\return DWORD containing the clipping flags for the point. If a flag is
set it indicates the transformed point lies outside the view volume. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */
virtual DWORD wTransPoint(const Point3 *in, IPoint3 *out) = 0;
/*! \remarks This method is used to convert coordinates to "<b>h</b>" <b>floating
point</b> coordinates. This is just a helper routine to avoid building up
round-off error. 3ds Max uses it just for IK. Note: This method maps points
from the GraphicsWindow's current transform to device space. If the
GraphicsWindow's transform is set to the identity matrix then the mapping
is done from points specified in world space. Otherwise the points given
are transformed by the GraphicsWindow transform, and are <b>then</b>
considered to be in world space. Thus, to get a world-space to screen-space
conversion, you need to set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>const Point3 *in</b>\n\n
The input point.\n\n
<b>Point3 *out</b>\n\n
The output point in floating point format with the origin at the lower
left.
\return DWORD containing the clipping flags for the point. If a flag is
set it indicates the transformed point lies outside the view volume. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_clip_flags.html">List of Clip Flags</a>. */
virtual DWORD transPoint(const Point3 *in, Point3 *out) = 0;
/*! \remarks Lights a vertex, using all the current lights. The vertex
appears to be transformed using the current transformation matrix, although
actually the calculations are done using back-transformed light coordinates
(for speed). The vertex position and normal are passed in, and a color is
returned. The rendering uses the current material.
\par Parameters:
<b>const Point3 \&pos</b>\n\n
Vertex position.\n\n
<b>const Point3 \&nor</b>\n\n
Vertex normal.\n\n
<b>Point3 \&rgb</b>\n\n
Returned color. */
virtual void lightVertex(const Point3 &pos, const Point3 &nor, Point3 &rgb) = 0;
/*! \remarks Draws 2D fixed font annotation text to the specified location. Note: This
routine DOES perform clipping of the text if it is off the screen.
\par Parameters:
<b>IPoint3 *xyz</b>\n\n
This is the device coordinate for the text. The origin of the text is at
the lower left corner.\n\n
<b>MCHAR *s</b>\n\n
The text to display. */
virtual void hText(IPoint3 *xyz, MCHAR *s) = 0;
/*! \remarks Draws a marker at the specified location.
\par Parameters:
<b>IPoint3 *xyz</b>\n\n
This is the device coordinate for the marker (with the origin at the lower
left).\n\n
<b>MarkerType type</b>\n\n
See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */
virtual void hMarker(IPoint3 *xyz, MarkerType type) = 0;
/*! \remarks This method draws a multi-segment polyline.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points that may
be used in drawing a polyline is 32.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at the lower
left.\n\n
<b>Point3 *rgb</b>\n\n
If the shade mode is set to smooth and these colors for the vertices are
specified the polyline will be drawn Gourand shaded. This is how 3ds Max
draws lit wireframes for instance. If you simply want ordinary lines (drawn
using the line color) pass NULL.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The
rgb values are ignored. Only the current material is taken into
consideration. (This is how OpenGL works.)\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th' edge is one
of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that the edges
are all solid. */
virtual void hPolyline(int ct, IPoint3 *xyz, Point3 *rgb, int closed, int *es) = 0;
/*! \remarks This method is available in release 2.0 and later
only.\n\n
This method draws a multi-segment polyline.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points
that may be used in drawing a polyline is 32.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at
the lower left.\n\n
<b>Point3 *rgb</b>\n\n
If the shade mode is set to smooth and these colors for the
vertices are specified the polyline will be drawn Gourand shaded.
This is how 3ds Max draws lit wireframes for instance. If you
simply want ordinary lines (drawn using the line color) pass
NULL.\n\n
Note: The use of these colors is not supported under the OpenGL
driver. The rgb values are ignored. Only the current material is
taken into consideration. (This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
This is not currently used. Pass NULL.\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th'
edge is one of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that
the edges are all solid. */
void hPolyline(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es)
{ hPolyline(ct, xyz, rgb, closed, es); }
/*! \remarks This method draws a multi-point polygon.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polygon.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at the lower
left.\n\n
<b>Point3 *rgb</b>\n\n
The color values at the vertices. The rendering mode must include
<b>GW_ILLUM</b> for these values to be used.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for
these values to be used. */
virtual void hPolygon(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It
takes a count of 3 or more, and builds triangles in a strip. This sends a lot
less data and the underlying graphics library has to set up a lot less data
since it can use the previous information to start the rasterization. This
results in a significant speed increase.\n\n
Note that this routine does no clipping so all the points passed must be within
view.
\par Parameters:
<b>int ct</b>\n\n
The total number of points. After the first two points, each new point is used
to create a new triangle.\n\n
<b>IPoint3 *xyz</b>\n\n
The point data with the origin at the lower left. For instance, to draw a quad,
the first three points specify the first triangle and the next one is combined
with the previous two to complete the square.\n\n
The order for these points follows the 'standard' conventions for stripping
used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n
<b>Point3 *rgb</b>\n\n
The colors for the vertices.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW texture coordinates for the vertices. */
virtual void hTriStrip(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks Draws 2D fixed font annotation text to the specified location. Note: This
routine DOES perform clipping of the text if it is off the screen.
\par Parameters:
<b>IPoint3 *xyz</b>\n\n
This is the device coordinate for the text. The origin of the text is at
the upper left corner.\n\n
<b>MCHAR *s</b>\n\n
The text to display. */
virtual void wText(IPoint3 *xyz, MCHAR *s) = 0;
/*! \remarks Draws a marker at the specified location.
\par Parameters:
<b>IPoint3 *xyz</b>\n\n
This is the device coordinate for the marker.\n\n
<b>MarkerType type</b>\n\n
See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */
virtual void wMarker(IPoint3 *xyz, MarkerType type) = 0;
/*! \remarks This method draws a multi-segment polyline.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points that may
be used in drawing a polyline is 32.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at the upper
left.\n\n
<b>Point3 *rgb</b>\n\n
If the shade mode is set to smooth and these colors for the vertices are
specified the polyline will be drawn Gourand shaded. This is how 3ds Max
draws lit wireframes for instance. If you simply want ordinary lines (drawn
using the line color) pass NULL.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The
rgb values are ignored. Only the current material is taken into
consideration. (This is how OpenGL works.)\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th' edge is one
of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that the edges
are all solid. */
virtual void wPolyline(int ct, IPoint3 *xyz, Point3 *rgb, int closed, int *es) = 0;
/*! \remarks This method is available in release 2.0 and later
only.\n\n
This method draws a multi-segment polyline.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points
that may be used in drawing a polyline is 32.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at
the upper left.\n\n
<b>Point3 *rgb</b>\n\n
If the shade mode is set to smooth and these colors for the
vertices are specified the polyline will be drawn Gourand shaded.
This is how 3ds Max draws lit wireframes for instance. If you
simply want ordinary lines (drawn using the line color) pass
NULL.\n\n
Note: The use of these colors is not supported under the OpenGL
driver. The rgb values are ignored. Only the current material is
taken into consideration. (This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
This is not currently used. Pass NULL.\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th'
edge is one of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that
the edges are all solid. */
void wPolyline(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es)
{ wPolyline(ct, xyz, rgb, closed, es); }
/*! \remarks This method draws a multi-point polygon.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polygon.\n\n
<b>IPoint3 *xyz</b>\n\n
Array of points. These are device coordinates with the origin at the upper
left.\n\n
<b>Point3 *rgb</b>\n\n
The color values at the vertices. The rendering mode must include
<b>GW_ILLUM</b> for these values to be used.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for
these values to be used. */
virtual void wPolygon(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It
takes a count of 3 or more, and builds triangles in a strip. This sends a lot
less data and the underlying graphics library has to set up a lot less data
since it can use the previous information to start the rasterization. This
results in a significant speed increase.\n\n
Note that this routine does no clipping so all the points passed must be within
view.
\par Parameters:
<b>int ct</b>\n\n
The total number of points. After the first two points, each new point is used
to create a new triangle.\n\n
<b>IPoint3 *xyz</b>\n\n
The point data with the origin at the upper left. For instance, to draw a quad,
the first three points specify the first triangle and the next one is combined
with the previous two to complete the square.\n\n
The order for these points follows the 'standard' conventions for stripping
used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n
<b>Point3 *rgb</b>\n\n
The colors for the vertices.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW texture coordinates for the vertices. */
virtual void wTriStrip(int ct, IPoint3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks Draws 2D fixed font annotation text to the specified
location. This method does perform clipping.\n\n
Note: This method maps points from the GraphicsWindow's current transform
to screen space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
This is the coordinate for the text.\n\n
<b>MCHAR *s</b>\n\n
The text to display. Note: This routine DOES perform clipping of the text
if it is off the screen. */
virtual void text(Point3 *xyz, MCHAR *s) = 0;
virtual void startMarkers() = 0;
/*! \remarks Draws a marker at the specified location in world space. This
method does perform clipping.\n\n
Note: This method maps points from the GraphicsWindow's current transform
to screen space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
This is the coordinate for the marker.\n\n
<b>MarkerType type</b>\n\n
See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_marker_types.html">List of Marker Types</a>. */
virtual void marker(Point3 *xyz, MarkerType type) = 0;
virtual void endMarkers() = 0;
virtual void polyline(int ct, Point3 *xyz, Point3 *rgb, int closed, int *es) = 0;
/*! \remarks Draws a multi-segment polyline with the coordinates
specified in world space. This method does perform clipping.\n\n
Note: The arrays of points and vertex related data all must be at
least one element larger than the <b>ct</b> parameter that is
passed in. The 3D clipper will use the "extra" space to clip as
efficiently as possible. If room for the extra element is not
provided, 3ds Max may crash.\n\n
Note: This method maps points from the GraphicsWindow's current
transform to screen space. If the GraphicsWindow's transform is set
to the identity matrix then the mapping is done from points
specified in world space. Otherwise the points given are
transformed by the GraphicsWindow transform, and are <b>then</b>
considered to be in world space. Thus, to get a world-space to
screen-space conversion, you need to set the transform to the
identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points
that may be used in drawing a polyline is 32.\n\n
<b>Point3 *xyz</b>\n\n
Array of points. This array must be at least one element larger
than the <b>ct</b> parameter that is passed in. The 3D clipper will
use the "extra" space to clip as efficiently as possible. If room
for the extra element is not provided, 3ds Max will crash.\n\n
<b>Point3 *rgb</b>\n\n
If the shade mode is set to smooth and these colors for the
vertices are specified the polyline will be drawn Gourand shaded.
This is how 3ds Max draws lit wireframes for instance. If you
simply want ordinary lines (drawn using the line color) pass
NULL.\n\n
Note: The use of these colors is not supported under the OpenGL
driver. The rgb values are ignored. Only the current material is
taken into consideration. (This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
This is not currently used. Pass NULL.\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th'
edge is one of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that
the edges are all solid. */
void polyline(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int closed, int *es)
{ polyline(ct, xyz, rgb, closed, es); }
/*! \remarks Draws a multi-segment polyline with the coordinates specified in world
space. This method takes a polyline with a normal for each vertex. This is
used for hardware accelerated lit wireframes (when <b>GW_SPT_GEOM_ACCEL</b>
is TRUE).\n\n
Note: The arrays of points and vertex related data all must be at least one
element larger than the <b>ct</b> parameter that is passed in. The 3D
clipper will use the "extra" space to clip as efficiently as possible. If
room for the extra element is not provided, 3ds Max may crash.\n\n
This method does perform clipping.\n\n
Note: This method maps points from the GraphicsWindow's current transform
to screen space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polyline. The maximum number of points that may
be used in drawing a polyline is 32.\n\n
<b>Point3 *xyz</b>\n\n
Array of points. This array must be at least one element larger than the
<b>ct</b> parameter that is passed in. The 3D clipper will use the "extra"
space to clip as efficiently as possible. If room for the extra element is
not provided, 3ds Max will crash.\n\n
<b>Point3 *nor</b>\n\n
The normal values at the vertices, one for each vertex.\n\n
<b>int closed</b>\n\n
If nonzero the first point is connected to the last point, i.e. the
polyline is closed.\n\n
<b>int *es</b>\n\n
Edge state array. This is an array that Indicates if the 'i-th' edge is one
of three state:\n\n
<b>GW_EDGE_SKIP</b>\n\n
Nonexistent - totally invisible.\n\n
<b>GW_EDGE_VIS</b>\n\n
Exists and is solid.\n\n
<b>GW_EDGE_INVIS</b>\n\n
Exists and is hidden - shown as a dotted line.\n\n
You may pass NULL for this array and the method will assume that the edges
are all solid. */
virtual void polylineN(int ct, Point3 *xyz, Point3 *nor, int closed, int *es) = 0;
/*! \remarks This method is used to begin efficiently sending a lot of 3D line segments.
First call this method, then call <b>segment()</b> many times (with two
points), then call <b>endSegments()</b>. */
virtual void startSegments() = 0;
/*! \remarks This method draws a single 3D line segment between the specified points.
Call <b>startSegments()</b> once before calling this method.
\par Parameters:
<b>Point3 *xyz</b>\n\n
Points to the two line endpoints in world space.\n\n
<b>int vis</b>\n\n
Nonzero for the segment to be visible; zero for invisible. */
virtual void segment(Point3 *xyz, int vis) = 0;
/*! \remarks Call this method after sending 3D line segments with <b>segment()</b>. */
virtual void endSegments() = 0;
/*! \remarks Draws a multi-point polygon. Note: All arrays (<b>xyz, rgb,
uvw</b>) must be at least one element larger than the <b>ct</b> parameter that
is passed in. The 3D clipper will use the "extra" space to clip as efficiently
as possible. If room for the extra element is not provided, 3ds Max may
crash.\n\n
Note: This method maps points from the GraphicsWindow's current transform to
screen space. If the GraphicsWindow's transform is set to the identity matrix
then the mapping is done from points specified in world space. Otherwise the
points given are transformed by the GraphicsWindow transform, and are
<b>then</b> considered to be in world space. Thus, to get a world-space to
screen-space conversion, you need to set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polygon.\n\n
<b>Point3 *xyz</b>\n\n
Array of points.\n\n
<b>Point3 *rgb</b>\n\n
The color values at the vertices. The rendering mode must include
<b>GW_ILLUM</b> for these values to be used.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for
these values to be used. */
virtual void polygon(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks Draws a multi-point polygon. Note: All arrays (<b>xyz, nor, uvw</b>) must be at
least one element larger than the <b>ct</b> parameter that is passed in. The 3D
clipper will use the "extra" space to clip as efficiently as possible. If room
for the extra element is not provided, 3ds Max will crash.\n\n
This method sends in normal vectors instead of color for 3D accelerated
rendering (when <b>GW_SPT_GEOM_ACCEL</b> is TRUE)\n\n
Note: This method maps points from the GraphicsWindow's current transform to
screen space. If the GraphicsWindow's transform is set to the identity matrix
then the mapping is done from points specified in world space. Otherwise the
points given are transformed by the GraphicsWindow transform, and are
<b>then</b> considered to be in world space. Thus, to get a world-space to
screen-space conversion, you need to set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>int ct</b>\n\n
The number of points in the polygon.\n\n
<b>Point3 *xyz</b>\n\n
Array of points.\n\n
<b>Point3 *nor</b>\n\n
The normal values at the vertices, one for each vertex.\n\n
<b>Point3 *uvw</b>\n\n
The UVW coordinates. The rendering mode must include <b>GW_TEXTURE</b> for
these values to be used. */
virtual void polygonN(int ct, Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It
takes a count of 3 or more, and builds triangles in a strip. This sends a lot
less data and the underlying graphics library has to set up a lot less data
since it can use the previous information to start the rasterization. This
results in a significant speed increase.
\par Parameters:
<b>int ct</b>\n\n
The total number of points. After the first two points, each new point is used
to create a new triangle.\n\n
<b>IPoint3 *xyz</b>\n\n
The point data. For instance, to draw a quad, the first three points specify
the first triangle and the next one is combined with the previous two to
complete the square.\n\n
The order for these points follows the 'standard' conventions for stripping
used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n
<b>Point3 *rgb</b>\n\n
The colors for the vertices.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The rgb
values are ignored. Only the current material is taken into consideration.
(This is how OpenGL works.)\n\n
<b>Point3 *uvw</b>\n\n
The UVW texture coordinates for the vertices. */
virtual void triStrip(int ct, Point3 *xyz, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method is used for drawing a series of triangles specified as 'strips'. It
takes a count of 3 or more, and builds triangles in a strip. This sends a lot
less data and the underlying graphics library has to set up a lot less data
since it can use the previous information to start the rasterization. This
results in a significant speed increase. This method sends in normal vectors
instead of color for 3D accelerated rendering (when <b>GW_SPT_GEOM_ACCEL</b> is
TRUE)
\par Parameters:
<b>int ct</b>\n\n
The total number of points. After the first two points, each new point is used
to create a new triangle.\n\n
<b>Point3 *xyz</b>\n\n
The point data. For instance, to draw a quad, the first three points specify
the first triangle and the next one is combined with the previous two to
complete the square.\n\n
The order for these points follows the 'standard' conventions for stripping
used in most graphics libraries (for example Direct3D, OpenGL and Heidi).\n\n
<b>Point3 *nor</b>\n\n
The normal for each vertex.\n\n
<b>Point3 *uvw</b>\n\n
The UVW texture coordinates for the vertices. */
virtual void triStripN(int ct, Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method is called to begin sending a series of non-stripped triangles
to render. Call this method, then any of the <b>triangle*()</b> methods
many times, then <b>endTriangles()</b> to finish. */
virtual void startTriangles() = 0;
/*! \remarks This method sends a single non-stripped triangle to render. Call
<b>startTriangles()</b> first.\n\n
Note: This method maps points from the GraphicsWindow's current transform
to screen space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
The three points for the triangle.\n\n
<b>Point3 *rgb</b>\n\n
The color for each vertex.\n\n
Note: The use of these colors is not supported under the OpenGL driver. The
rgb values are ignored. Only the current material is taken into
consideration. (This is how OpenGL works.) */
virtual void triangle(Point3 *xyz, Point3 *rgb) = 0;
/*! \remarks This method draws a single triangle by specifying the vertex points in world
space, a normal, and texture coordinates for each vertex.\n\n
Note: This method maps points from the GraphicsWindow's current transform to
screen space. If the GraphicsWindow's transform is set to the identity matrix
then the mapping is done from points specified in world space. Otherwise the
points given are transformed by the GraphicsWindow transform, and are
<b>then</b> considered to be in world space. Thus, to get a world-space to
screen-space conversion, you need to set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
The three points for the triangle.\n\n
<b>Point3 *nor</b>\n\n
The three normals for the triangle.\n\n
<b>Point3 *uvw</b>\n\n
The texture coordinate for each vertex. */
virtual void triangleN(Point3 *xyz, Point3 *nor, Point3 *uvw, int texNum=1) = 0;
/*! \remarks This method draws a single triangle by specifying the vertex points in
world space, a normal, and a color for each vertex.\n\n
Note: This method maps points from the GraphicsWindow's current transform
to screen space. If the GraphicsWindow's transform is set to the identity
matrix then the mapping is done from points specified in world space.
Otherwise the points given are transformed by the GraphicsWindow transform,
and are <b>then</b> considered to be in world space. Thus, to get a
world-space to screen-space conversion, you need to set the transform to
the identity with <b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
The three points for the triangle.\n\n
<b>Point3 *nor</b>\n\n
The normal for each vertex.\n\n
<b>Point3 *rgb</b>\n\n
The color for each vertex. */
virtual void triangleNC(Point3 *xyz, Point3 *nor, Point3 *rgb) = 0;
/*! \remarks This method draws a single triangle by specifying the vertex points in world
space, a normal, a color, and a texture coordinate for each vertex.\n\n
Note: This method maps points from the GraphicsWindow's current transform to
screen space. If the GraphicsWindow's transform is set to the identity matrix
then the mapping is done from points specified in world space. Otherwise the
points given are transformed by the GraphicsWindow transform, and are
<b>then</b> considered to be in world space. Thus, to get a world-space to
screen-space conversion, you need to set the transform to the identity with
<b>gw-\>setTransform(Matrix3(1))</b>.
\par Parameters:
<b>Point3 *xyz</b>\n\n
The three points for the triangle.\n\n
<b>Point3 *nor</b>\n\n
The normal for each vertex.\n\n
<b>Point3 *rgb</b>\n\n
The color for each vertex.\n\n
<b>Point3 *uvw</b>\n\n
The texture coordinate for each vertex. */
virtual void triangleNCT(Point3 *xyz, Point3 *nor, Point3 *rgb, Point3 *uvw, int texNum=1) = 0;
virtual void triangleW(Point3 *xyz, int *es) = 0;
virtual void triangleNW(Point3 *xyz, Point3 *nor, int *es) = 0;
/*! \remarks Call this method to finish rendering triangles. See <b>startTriangles()</b>
above. */
virtual void endTriangles() = 0;
virtual void loadMeshData(DWORD_PTR id, int xyzCt, Point3 *xyz, int norCt, Point3 *nor, int texNum, int uvwCt, Point3 *uvw, int mtlCt, Material *mtl) = 0;
virtual void processStrips(DWORD_PTR id, int stripCt, StripTab *s, GFX_ESCAPE_FN fn) = 0;
virtual void processWireFaces(int xyzCt, Point3 *xyz, int faceCt, GWFace *face, int dispFlags, BitArray *faceSel, BitArray *edgeSel, int mtlCt, Material *mtl, GFX_ESCAPE_FN fn) = 0;
/*! \remarks Sets the hit region used for hit testing. See
Class HitRegion.
\par Parameters:
<b>HitRegion *rgn</b>\n\n
The hit region to use. */
virtual void setHitRegion(HitRegion *rgn) = 0;
/*! \remarks This methods clears the hit code. Call this method before
performing a hit test. */
virtual void clearHitCode(void) = 0;
/*! \remarks Returns TRUE if the hit code is set indicating a hit was
made; otherwise FALSE. */
virtual BOOL checkHitCode(void) = 0;
/*! \remarks This method allows drawing code to manually set the state of the hit code,
which is returned by the <b>checkHitCode()</b> method. For more information
see the topic on
<a href="ms-its:3dsmaxsdk.chm::/vports_hit_testing.html">Hit
Testing</a>.\n\n
The new methods <b>setHitDistance()</b> and <b>setHitCode()</b> make it
possible to work with GraphicsWindow hit-testing in otherwise impossible
situations. Why are they necessary? An example from is shown below. The
patch object contains bezier spline-based edges which can consist of up to
102 vertices. Since the GraphicsWindow::polyline function can only plot
lines with up to 32 vertices, it is impossible to plot these in a single
call to the polyline function. Multiple calls to the polyline call do not
return a proper hitcode when using a "window"-type hit region. By using the
new <b>setHitCode()</b> method, code can properly handle this situation.
The code below shows the function in use from the PatchMesh::renderEdge method:
\code
int steps = GetMeshSteps();
int segNum = steps+2;
float fsegNum = (float) (segNum-1);
// If steps are too high for GraphicsWindow's buffer, we must draw it
manually
if((steps + 2) > GW_MAX_VERTS) {
Point3 line[2];
Point3 prev,current(.0f,.0f,.0f);
BOOL hitAll = TRUE;
BOOL hitAny = FALSE;
DWORD hitDist = 0xffffffff;
for(int terp = 0; terp \
{
prev = current;
current = work.InterpCurve3D((float)terp / fsegNum);
if (terp != 0)
{
line[0] = prev;
line[1] = current;
gw->clearHitCode();
gw->polyline(2, line, NULL, NULL, 0, NULL);
if(gw->checkHitCode()) {
hitAny = TRUE;
if(gw->getHitDistance() \
hitDist = gw->getHitDistance();
}
else hitAll = FALSE;
}
}
if(hr && !hr->crossing && hr->type != POINT_RGN)
gw->setHitCode(hitAll);
else
gw->setHitCode(hitAny);
gw->setHitDistance(hitDist);
} else {
for(int terp = 0; terp \
fixedBuf[terp] = work.InterpCurve3D((float)terp /
fsegNum);
gw->polyline(steps+2, fixedBuf, NULL, NULL, 0, NULL);
}
\endcode
Note that the <b>gw-\>polyline</b> call is preceded by a call to
<b>clearHitCode()</b>, and followed by code which checks the hit code,
maintaining "hitAny" and "hitAll" flags. When all the segments are drawn,
the <b>gw-\>setHitCode()</b> call is made, setting the hit code depending
on the hit region type. When the code which called this function checks the
GraphicsWindow's hit code, it will contain the proper value. This code also
keeps track of the closest hit distance and places that into the
GraphicsWindow when all line segments are drawn.
\par Parameters:
<b>BOOL h</b>\n\n
Set to TRUE if the hit code is set, otherwise FALSE. */
virtual void setHitCode(BOOL h) = 0;
/*! \remarks If <b>checkHitCode()</b> returns TRUE you may call this
method to return the hit distance. In wireframe mode this is the distance
to the line. In shaded mode, this is the z distance. This allows you to
perform 'smart' hit testing by choosing the item with the smallest hit
distance. This method only returns meaningful values when the hit region is
a point. */
virtual DWORD getHitDistance(void) = 0;
/*! \remarks This method allows drawing code to manually set the hit distance, which is
returned by the <b>getHitDistance()</b> method. For more information see
the topic on <a href="ms-its:3dsmaxsdk.chm::/vports_hit_testing.html">Hit
Testing</a>.
\par Parameters:
<b>DWORD d</b>\n\n
In wireframe mode this is the distance to the line. In shaded mode, this is
the z distance. */
virtual void setHitDistance(DWORD d) = 0;
/*! \remarks Returns TRUE if the view is in perspective projection;
otherwise FALSE (orthographic projection). */
virtual int isPerspectiveView(void) = 0;
/*! \remarks This method is used internally. */
virtual float interpWorld(Point3 *world1, Point3 *world2, float sParam, Point3 *interpPt) = 0;
//watje
virtual void MarkerBufferSetMarkerType( MarkerType type) {};
virtual DWORD MarkerGetDXColor(Point3 p) {return 0;};
virtual VertexBuffer* MarkerBufferLock() { return NULL;};
virtual void MarkerBufferUnLock() {};
virtual int MarkerBufferSize( ) {return 0;};
virtual int MarkerBufferStride( ){ return 0;};
virtual void MarkerBufferDraw(int numberOfMarkers) {};
//watje
virtual DWORD LineGetDXColor(Point3 p) {return 0;};
virtual LineBuffer* LineBufferLock() { return NULL;};
virtual void LineBufferUnLock() {};
virtual int LineBufferSize( ) {return 0;};
virtual int LineBufferStride( ){ return 0;};
virtual void LineBufferDraw(int numberOfSegments) {};
virtual void escape(GFX_ESCAPE_FN fn, void *data) = 0;
/*! \remarks This method calculates the depth value of the screen pixel located at positon x,y.
This method returns TRUE if the depth value is calculated, FALSE otherwise.
It is currently supported in Direct3D and OpenGL driver. Thus returning FALSE for unsupported
driver. This method is used to locate center pivot in SteeringWheel.
\param[in] x The x coordinate in screen space. \n
\param[in] y The y coordinate in screen space. \n
\param[out] z A pointer to the buffer that receives the calculated depth value.
\return TRUE if calculated correctly, FALSE if the method failed or not supported.
*/
virtual BOOL getDepthValue(float x, float y, float* z) { return FALSE; }
/*! \remarks This method will clear the depth buffer bits of this GraphicsWindow.
It is currently supported in Direct3D and OpenGL driver. This method is used
clear the depth before actually drawing the ViewCube, which cannot be messed up
with the scene geometry.
*/
virtual void clearViewportDepth() {};
/*! \remarks This take a GFX_MESH::HWTupleMesh and creates a hardware specific mesh buffers
\param[in]GFX_MESH::HWTupleMesh *hwMesh the mesh used to create the Hardware specific buffers. \n
\return the hardware specific IHWDrawMesh. */
virtual GFX_MESH::IHWSubMesh *CreateHWDrawMesh(GFX_MESH::HWTupleMesh *hwMesh) {return NULL;};
/*! \remarks This draws the hwMesh to the display. If the hardware mesh holds a valid IHWDrawMesh
it will use that to draw the mesh in retained mode. Otherwise the buffers in the hwmesh will be used
to draw the mesh in immediate mode which is much slower.
\param[in]GFX_MESH::HWTupleMesh *hwMesh the mesh to be drawn. \n
*/
virtual void DrawHWDrawMesh(GFX_MESH::HWTupleMesh *hwMesh) {};
};
// for Windows int coords with origin at upper-left
inline int wIsFacingBack(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 )
{
int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) ) < 0;
return flip ? !s : s;
}
// for HEIDI int coords with origin at lower-left
inline int hIsFacingBack(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 )
{
int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) );
return flip ? s < 0 : s > 0;
}
// CAL-03/05/03: include side facing in the facing type
enum FacingType {kFrontFacing, kSideFacing, kBackFacing};
//! \brief Returns the facing of a given triangle relative to the screen.
/*! \remarks Returns whether a given triangle is front-facing,
side-facing, or back-facing relative to the screen. The triangle is passed as three points in screen space.
This function is used for "w" format device coordinates.
\param v0 The 1st triangle vertex
\param v1 The 2nd triangle vertex
\param v2 The 3rd triangle vertex
\param flip If true, flip the triangle (so backfacing would return frontfacing) */
inline FacingType wFacingType(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 )
{
int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) );
return (s == 0) ? kSideFacing : ((flip ? s > 0 : s < 0) ? kBackFacing : kFrontFacing);
}
//! \brief Returns the facing of a given triangle relative to the screen.
/*! \remarks The methods wFacingType() and hFacingType() will return whether a given triangle is front-facing,
side-facing, or back-facing relative to the screen. The triangle is passed as three points in screen space.
This function is used for "h" format device coordinates.
\param v0 The 1st triangle vertex
\param v1 The 2nd triangle vertex
\param v2 The 3rd triangle vertex
\param flip If true, flip the triangle (so backfacing would return frontfacing) */
inline FacingType hFacingType(const IPoint3 &v0, const IPoint3 &v1, const IPoint3 &v2, int flip=0 )
{
int s = ( (v0[0]-v1[0])*(v2[1]-v1[1]) - (v2[0]-v1[0])*(v0[1]-v1[1]) );
return (s == 0) ? kSideFacing : ((flip ? s < 0 : s > 0) ? kBackFacing : kFrontFacing);
}
/*! \remarks This function is available in release 2.0 and later only.\n\n
This function is not supported for use in the SDK. */
DllExport HINSTANCE GetGraphicsLibHandle(MCHAR *driverLibName);
/*! \remarks This function is available in release 2.0 and later only.\n\n
This function is not supported for use in the SDK. */
DllExport BOOL GraphicsSystemIsAvailable(HINSTANCE drv);
/*! \remarks This function is available in release 2.0 and later only.\n\n
This function is not supported for use in the SDK. */
DllExport BOOL GraphicsSystemCanConfigure(HINSTANCE drv);
/*! \remarks This function is available in release 2.0 and later only.\n\n
This function is not supported for use in the SDK. */
DllExport BOOL GraphicsSystemConfigure(HWND hWnd, HINSTANCE drv);
/*! \remarks This function is available in release 2.0 and later only.\n\n
This function is not supported for use in the SDK. */
DllExport void FreeGraphicsLibHandle(HINSTANCE drv);
/*! \remarks This function is used internally to create a new graphics window.
Use of this method is not supported for plug-ins. */
DllExport GraphicsWindow *createGW(HWND hWnd, GWinSetup &gws);
/*! \remarks Returns a bounding rectangle that encloses the entire hit region.
For example if the hit regions was a fence region, this method would return the
smallest rectangle that included the entire set of fence region points.
\par Parameters:
<b>HitRegion *hr</b>\n\n
The hit region to check.\n\n
<b>RECT *rect</b>\n\n
The returned bounding rectangle. */
DllExport void getRegionRect(HitRegion *hr, RECT *rect);
/*! \remarks Returns TRUE if the specified point is inside the region
<b>hr</b>; otherwise FALSE. */
DllExport BOOL pointInRegion(int x, int y, HitRegion *hr);
/*! \remarks Returns the signed distance from <b>x,y</b> to the line defined
by <b>p1-\>p2</b>. */
DllExport int distToLine(int x, int y, int *p1, int *p2);
DllExport int zDepthToLine(int x, int y, int *p1, int *p2);
/*! \remarks Returns nonzero if the line defined by <b>p1-\>p2</b> crosses
into the RECT and 0 otherwise. */
DllExport int lineCrossesRect(RECT *rc, int *p1, int *p2);
DllExport int segCrossesRect(RECT *rc, int *p1, int *p2);
/*! \remarks Returns nonzero if the line defined by <b>p1-\>p2</b> crosses the
circle center at (<b>cx, cy</b>) with a radius of <b>r</b> 0 otherwise. */
DllExport int segCrossesCircle(int cx, int cy, int r, int *p1, int *p2);
/*! \remarks Returns TRUE if the point passed is inside the specified
triangle.
\par Parameters:
<b>IPoint3 \&p0</b>\n\n
The first point of the triangle.\n\n
<b>IPoint3 \&p1</b>\n\n
The second point of the triangle.\n\n
<b>IPoint3 \&p2</b>\n\n
The third point of the triangle.\n\n
<b>IPoint3 \&q</b>\n\n
The point to check.
\return Returns TRUE if the point passed is inside the specified triangle;
otherwise FALSE. */
DllExport BOOL insideTriangle(IPoint3 &p0, IPoint3 &p1, IPoint3 &p2, IPoint3 &q);
/*! \remarks Returns the z value of where the projected screen point <b>q</b>
would intersect the triangle defined by (<b>p0, p1, p2</b>).
\par Parameters:
<b>IPoint3 \&p0</b>\n\n
The first point of the triangle.\n\n
<b>IPoint3 \&p1</b>\n\n
The second point of the triangle.\n\n
<b>IPoint3 \&p2</b>\n\n
The third point of the triangle.\n\n
<b>IPoint3 \&q</b>\n\n
The screen point to check. */
DllExport int getZfromTriangle(IPoint3 &p0, IPoint3 &p1, IPoint3 &p2, IPoint3 &q);
DllExport int getClosestPowerOf2(int num);
/*! \defgroup viewportDrawingColors Viewport Drawing Color Indices
\todo Document Viewport Drawing Colors defines
*/
//@{
#define COLOR_SELECTION 0 //!<
#define COLOR_SUBSELECTION 1 //!<
#define COLOR_FREEZE 2 //!<
#define COLOR_GRID 3 //!<
#define COLOR_GRID_INTENS 4 //!<
#define COLOR_SF_LIVE 5 //!<
#define COLOR_SF_ACTION 6 //!<
#define COLOR_SF_TITLE 7 //!<
#define COLOR_VP_LABELS 8 //!<
#define COLOR_VP_INACTIVE 9 //!<
#define COLOR_ARCBALL 10 //!<
#define COLOR_ARCBALL_HILITE 11 //!<
#define COLOR_ANIM_BUTTON 12 //!<
#define COLOR_SEL_BOXES 13 //!<
#define COLOR_LINK_LINES 14 //!<
#define COLOR_TRAJECTORY 15 //!<
#define COLOR_ACTIVE_AXIS 16 //!<
#define COLOR_INACTIVE_AXIS 17 //!<
#define COLOR_SPACE_WARPS 18 //!<
#define COLOR_DUMMY_OBJ 19 //!<
#define COLOR_POINT_OBJ 20 //!<
#define COLOR_POINT_AXES 21 //!<
#define COLOR_TAPE_OBJ 22 //!<
#define COLOR_BONES 23 //!<
#define COLOR_GIZMOS 24 //!<
#define COLOR_SEL_GIZMOS 25 //!<
#define COLOR_SPLINE_VECS 26 //!<
#define COLOR_SPLINE_HANDLES 27 //!<
#define COLOR_PATCH_LATTICE 28 //!< No longer used
#define COLOR_PARTICLE_EM 29 //!<
#define COLOR_CAMERA_OBJ 30 //!<
#define COLOR_CAMERA_CONE 31 //!<
#define COLOR_CAMERA_HORIZ 32 //!<
#define COLOR_NEAR_RANGE 33 //!<
#define COLOR_FAR_RANGE 34 //!<
#define COLOR_LIGHT_OBJ 35 //!<
#define COLOR_TARGET_LINE 36 //!<
#define COLOR_HOTSPOT 37 //!<
#define COLOR_FALLOFF 38 //!<
#define COLOR_START_RANGE 39 //!<
#define COLOR_END_RANGE 40 //!<
#define COLOR_VIEWPORT_BKG 41 //!<
#define COLOR_TRAJ_TICS_1 42 //!<
#define COLOR_TRAJ_TICS_2 43 //!<
#define COLOR_TRAJ_TICS_3 44 //!<
#define COLOR_GHOST_BEFORE 45 //!<
#define COLOR_GHOST_AFTER 46 //!<
#define COLOR_12FIELD_GRID 47 //!<
#define COLOR_START_RANGE1 48 //!<
#define COLOR_END_RANGE1 49 //!<
#define COLOR_CAMERA_CLIP 50 //!<
#define COLOR_NURBS_CV 51 //!<
#define COLOR_NURBS_LATTICE 52 //!<
#define COLOR_NURBS_CP 53 //!<
#define COLOR_NURBS_FP 54 //!<
#define COLOR_NURBS_DEP 55 //!<
#define COLOR_NURBS_ERROR 56 //!<
#define COLOR_NURBS_HILITE 57 //!<
#define COLOR_NURBS_FUSE 58 //!<
#define COLOR_END_EFFECTOR 59 //!<
#define COLOR_END_EFFECTOR_STRING 60 //!<
#define COLOR_JOINT_LIMIT_SEL 61 //!<
#define COLOR_JOINT_LIMIT_UNSEL 62 //!<
#define COLOR_IK_TERMINATOR 63 //!<
#define COLOR_SF_USER 64 //!<
#define COLOR_VERT_TICKS 65 //!<
#define COLOR_XRAY 66 //!<
#define COLOR_GROUP_OBJ 67 //!<
#define COLOR_MANIPULATOR_X 68 //!<
#define COLOR_MANIPULATOR_Y 69 //!<
#define COLOR_MANIPULATOR_Z 70 //!<
#define COLOR_MANIPULATOR_ACTIVE 71 //!<
#define COLOR_VPT_CLIPPING 72 //!<
#define COLOR_DECAY_RADIUS 73 //!<
#define COLOR_VERT_NUMBERS 74 //!<
#define COLOR_CROSSHAIR_CURSOR 75 //!<
#define COLOR_SV_WINBK 76 //!< SV Window Background
#define COLOR_SV_NODEBK 77 //!< SV Default Node Background
#define COLOR_SV_SELNODEBK 78 //!< SV Selected Node Background
#define COLOR_SV_NODE_HIGHLIGHT 79 //!< SV Viewport Selected Node Highlight
#define COLOR_SV_MATERIAL_HIGHLIGHT 80 //!< SV MEDIT Selected Node Highlight
#define COLOR_SV_MODIFIER_HIGHLIGHT 81 //!< SV Selected Modifier Highlight
#define COLOR_SV_PLUGIN_HIGHLIGHT 82 //!< SV Plug-in Highlight
#define COLOR_SV_SUBANIM_LINE 83 //!< SV Subanim line color
#define COLOR_SV_CHILD_LINE 84 //!< SV Child node line color
#define COLOR_SV_FRAME 85 //!< SV Frame color
#define COLOR_SV_SELTEXT 86 //!< SV Selected Label Color
#define COLOR_SV_TEXT 87 //!< SV Label Color
#define COLOR_UNSEL_TAB 88
#define COLOR_ATMOS_APPARATUS 89 //!<
#define COLOR_SUBSELECTION_HARD 90 //!<
#define COLOR_SUBSELECTION_MEDIUM 91 //!<
#define COLOR_SUBSELECTION_SOFT 92 //!<
#define COLOR_SV_UNFOLD_BUTTON 93 //!< SV Unfold Button
#define COLOR_SV_GEOMOBJECT_BK 94 //!< Geometry Object Node Background
#define COLOR_SV_LIGHT_BK 95 //!< Light Node Background
#define COLOR_SV_CAMERA_BK 96 //!< Camera Node Background
#define COLOR_SV_SHAPE_BK 97 //!< Shape Node Background
#define COLOR_SV_HELPER_BK 98 //!< Helper Node Background
#define COLOR_SV_SYSTEM_BK 99 //!< System Node Background
#define COLOR_SV_CONTROLLER_BK 100 //!< Controller Node Background
#define COLOR_SV_MODIFIER_BK 101 //!< Modifier Node Background
#define COLOR_SV_MATERIAL_BK 102 //!< Material Node Background
#define COLOR_SV_MAP_BK 103 //!< Map Node Background
#define COLOR_SETKEY_BUTTON 104
#define COLOR_BACK_LINES 105 //!< Backface lines on selected objects
#define COLOR_BACK_VERTS 106 //!< Backface vertices on selected objects
#define COLOR_MANIPULATOR_CONTOUR 107 //!< Background color for the rotation gizmo
#define COLOR_MANIPULATOR_SCREEN 108 //!< screen space manipulator handle color for the rotation gizmo
#define COLOR_MANIPULATOR_TRAIL 109 //!< move gizmo displacement trail color
//@}
const int kColorNormalsUnspecified = 110;
const int kColorNormalsSpecified = 111;
const int kColorNormalsExplicit = 112;
/*! \addtogroup viewportDrawingColors */
//@{
#define COLOR_SV_GRID 113 //!< SV Grid
#define COLOR_SV_REL_INSTANCE 114 //!< SV Relationship Instances
#define COLOR_SV_REL_CONSTRAINT 115 //!< SV Relationship Contraints
#define COLOR_SV_REL_PARAMWIRE 116 //!< SV Relationship Param Wires
#define COLOR_SV_REL_LIGHT 117 //!< SV Relationship Lights
#define COLOR_SV_REL_MODIFIER 118 //!< SV Relationship Modifiers
#define COLOR_SV_REL_CONTROLLER 119 //!< SV Relationship Controllers
#define COLOR_SV_REL_OTHER 120 //!< SV Relationship Others
#define COLOR_SV_SPACEWARP_BK 121 //!< SV SpaceWarp
#define COLOR_SV_BASEOBJECT_BK 122 //!< SV BaseObject
#define COLOR_VP_STATISTICS 123 //!< Colour for viewport statistics display
#define COLOR_SPLINE_KNOT_UNSELECTED 124 //!< color of bezier knots unselected
#define COLOR_SPLINE_KNOT_FIRST 125 //!< color of first knot of the bezier spline
#define COLOR_HIDDENLINE_UNSELECTED 126 //!< color of first knot of the bezier spline
#define COLOR_VP_LABEL_HIGHLIGHT 127 //!< Color of selected/mouse over viewport labels
#define COLOR_TOTAL 128 //!< always the max number of colors
//@}
// Returns/sets color values for drawing in the viewport (selection, subsel, etc)
DllExport Point3 GetUIColor(int which);
DllExport void SetUIColor(int which, Point3 *clr);
DllExport Point3 GetDefaultUIColor(int which);
#define GetSelColor() GetUIColor(COLOR_SELECTION)
/*! \remarks Returns the color used for sub-object selection. */
#define GetSubSelColor() GetUIColor(COLOR_SUBSELECTION)
#define GetFreezeColor() GetUIColor(COLOR_FREEZE)
//! Internal Use only
//! NH Flags used to tell Max graphics drivers that the user has returned from various system events
//! Internal Use only - resolves issues with DirectX - the flags are used with GraphicsWindow::setFlags
#define SYSTEM_LOCK_RETURN 0x001
#define SYSTEM_REMOTE_RETURN 0x002
#endif // _GFX_H_
|
Java
|
/**
*
* Web Starter Kit
* Copyright 2014 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
*
*/
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// Clean Output Directory
gulp.task('clean', del.bind(null, ['./index.js', './assertRank.js', './specs.js']));
gulp.task('es6', ['clean'], function () {
return gulp.src(['./src/**/*.js'])
// .pipe($.sourcemaps.init({loadMaps: true}))
.pipe($['6to5']()).on('error', console.error.bind(console))
// .pipe($.sourcemaps.write())
.pipe(gulp.dest('.'))
.pipe($.size({title: 'es6'}))
})
gulp.task('browserify', ['es6'], function () {
return gulp.src(['./specs.js'])
.pipe($.browserify({debug: false}))
.pipe(gulp.dest('.'))
.pipe($.size({title: 'browserify'}))
})
// Watch Files For Changes & Reload
gulp.task('serve', ['browserify'], function () {
browserSync({
notify: false, browser: 'skip', ghostMode: false,
// Customize the BrowserSync console logging prefix
logPrefix: 'WSK',
port: 3010,
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: ['.', 'src']
});
gulp.watch(['gulpfile.js'], process.exit)
gulp.watch(['./src/**/*.{js,html}'], ['browserify', reload]);
});
gulp.task('default', ['es6'])
// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
|
Java
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-65704319-1', 'auto');
ga('send', 'pageview');
|
Java
|
/**
* Copyright 2017 Shusheng Shao <iblackangel@163.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.
*/
#include <mpl/mlog.h>
#include <mpl/msysinfo.h>
#include <mpl/mdatetime.h>
#include <mpl/mapplication.h>
#include <mpl/mprocess.h>
#include <mpl/mstring.h>
#include <mpl/merror.h>
#include <mpl/mfile.h>
#ifdef _MSC_VER
# pragma warning (push)
# pragma warning (disable: 4996)
#endif
MPL_BEGIN_NAMESPACE
MLog *MLog::_ins = NULL;
MLog *MLog::instance()
{
if (NULL == _ins) {
_ins = new MLog();
atexit(desposed);
}
return _ins;
}
void MLog::desposed()
{
if (NULL != _ins) {
delete _ins; _ins = NULL;
}
}
MLog::MLog()
: _priority(kDebug)
, _performance(kNormal)
, _pattern(kSyslog)
{
}
MLog::~MLog()
{
}
void MLog::init(const char *logfile, int priority, int performance)
{
if (logfile != NULL) {
_logfile = logfile;
_pattern = kFile;
}
_priority = priority;
_performance = performance;
}
void MLog::initdir(const char *logdir,
const char *prefix,
int priority,
int performance)
{
if (logdir != NULL) {
_logdir = logdir;
_pattern = kDir;
}
if (prefix != NULL)
_prefix = prefix;
_priority = priority;
_performance = performance;
}
void MLog::log(const std::string &file, const std::string &func,
uint32_t line, int pri,
const char *__format, ...)
{
MScopedLock locker(_mutex);
// according to pri
if (pri > _priority) return;
// combine log head
std::string head;
int len;
std::string buffer;
va_list vargs;
va_start(vargs, __format);
len = vsnprintf(NULL, 0, __format, vargs);
buffer.resize(len);
va_start(vargs, __format);
vsnprintf(&buffer[0], len + 1, __format, vargs);
va_end(vargs);
// DATETIME HOSTNAME APPLICATIONNAME[PID] FILE FUNC[LINE]
#if defined(_MSC_VER) || defined(M_OS_WIN)
const char *fmt = "%s %s %s[%ld] %s %s[%u]: <%s> %s\n";
#else
const char *fmt = "%s %s %s[%lld] %s %s[%u]: <%s> %s\n";
#endif
std::string logstr = format(fmt,
now().c_str(), hostname().c_str(),
applicationName().c_str(), process::pid(),
file.c_str(), func.c_str(), line,
strpriority(pri).c_str(),
buffer.c_str());
std::cout << logstr;
switch (_pattern) {
case kFile:
logToFile(logstr);
break;
case kDir:
logToDir(logstr);
break;
default:
logToSyslog(logstr);
break;
}
}
std::string MLog::strpriority(int pri) const
{
std::string ret = "debug";
switch (pri) {
case kEmerg:
ret = "emerg"; break;
case kAlert:
ret = "alert"; break;
case kCrit:
ret = "crit"; break;
case kError:
ret = "error"; break;
case kWarn:
ret = "warn"; break;
case kNotice:
ret = "notice"; break;
case kInfo:
ret = "info"; break;
default:
break;
}
return ret;
}
void MLog::logToFile(const std::string &logstr)
{
file::appendbuf(_logfile.c_str(), logstr.c_str(), logstr.size());
}
void MLog::logToDir(const std::string &logstr)
{
std::string logfile = _logdir + DIRECTORY_SEPARATOR
+ _prefix + MDateTime::currentDateTime().toString("%Y%m%d")
+ std::string(".log");
file::appendbuf(logfile.c_str(), logstr.c_str(), logstr.size());
}
void MLog::logToSyslog(const std::string &logstr)
{
#ifdef M_OS_LINUX
syslog(LOG_DEBUG, "%s", logstr.c_str());
#else
OutputDebugString(logstr.c_str());
#endif
}
MPL_END_NAMESPACE
#ifdef _MSC_VER
# pragma warning (pop)
#endif
|
Java
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include <time.h>
#include "Basics/system-functions.h"
#include "Basics/tri-strings.h"
#include "Replication/common-defines.h"
namespace arangodb {
/// @brief generate a timestamp string in a target buffer
void TRI_GetTimeStampReplication(char* dst, size_t maxLength) {
struct tm tb;
time_t tt = time(nullptr);
TRI_gmtime(tt, &tb);
strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb);
}
/// @brief generate a timestamp string in a target buffer
void TRI_GetTimeStampReplication(double timeStamp, char* dst, size_t maxLength) {
struct tm tb;
time_t tt = static_cast<time_t>(timeStamp);
TRI_gmtime(tt, &tb);
strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb);
}
bool TRI_ExcludeCollectionReplication(std::string const& name, bool includeSystem,
bool includeFoxxQueues) {
if (name.empty()) {
// should not happen...
return true;
}
if (name[0] != '_') {
// all regular collections are included
return false;
}
if (!includeSystem) {
// do not include any system collections
return true;
}
if (TRI_IsPrefixString(name.c_str(), "_statistics") ||
name == "_configuration" || name == "_frontend" ||
name == "_cluster_kickstarter_plans" || name == "_routing" ||
name == "_fishbowl" || name == "_foxxlog" || name == "_sessions") {
// these system collections will always be excluded
return true;
} else if (!includeFoxxQueues && (name == "_jobs" || name == "_queues")) {
return true;
}
return false;
}
} // namespace arangodb
|
Java
|
#!/bin/bash -e
#
# Copyright 2014 The Kythe 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.
#
# This script tests the indexpack binary. It requires the jq command (≥ 1.4).
kindex_contents() {
$viewindex --files "$1" | $jq -c -S .
}
tmp="$(mktemp -d 2>/dev/null || mktemp -d -t 'kythetest')"
trap 'rm -rf "$tmp"' EXIT ERR INT
$indexpack --to_archive "$tmp/archive" "$input" >/dev/null
$indexpack --from_archive "$tmp/archive" "$tmp/idx"
kindex_file="$(find "$tmp/idx" -name "*.kindex")"
result="$(kindex_contents "$kindex_file")"
expected="$(kindex_contents $input)"
if [[ ! "$result" == "$expected" ]]; then
echo "ERROR: expected $expected; received $result" >&2
exit 1
fi
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>ClickCloud | Rapid deployment</title>
<link rel="stylesheet" type="text/css" href="static/styles/font-awesome.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="static/styles/font-awesome-ie7.min.css">
<![endif]-->
<link rel="stylesheet" type="text/css" href="static/styles/master.css" />
<link rel="stylesheet" type="text/css" href="static/styles/index.css" /><!-- Only Hadoop Install -->
<script type="text/javascript" src="static/scripts/jquery.js"></script>
<script type="text/javascript" src="static/scripts/click.js"></script>
<script type="text/javascript">
window.addEventListener('load', function () {
crumbsContent = crumbs([{ name: 'Home', url: 'index.html' }, { name: 'Hadoop', url: '' }]);
var crumbs_ = document.getElementById('crumbs');
if (!!crumbs_) {
crumbs_.insertAdjacentHTML('afterBegin', crumbsContent);
}
clickgo(document.getElementsByClassName('alert'));
clicktoggle(document.getElementById('_01'),
document.getElementById('_01_'));
clicktoggle(document.getElementById('_02'),
document.getElementById('_02_'));
clickfocus(document.getElementsByClassName('_focus_'));
__IFRAME__ = document.getElementById('iframe_just_me');
window.switch_ = function (flag) {
switch (flag) {
case 'clusters':
iframe_switch('My Cluster', '>> Cluster list', [
{ url: 'parts/clusters', d: {} },
]);
break;
case 'host-add':
iframe_switch('Add Host', '>> Register your machine to the system', [
{ url: 'parts/host-add', d: {} },
]);
break;
case 'hosts':
iframe_switch('My Hosts', '>> Registered host', [
{ url: 'parts/hosts', d: {} },
]);
break;
case 'dns':
iframe_switch('Domain Name System', '>> Configuration /etc/hosts', [
{ url: 'parts/dns', d: {} },
]);
break;
case 'hs':
iframe_switch('Install Hadoop and Spark Enviroment', '>> include HDFS and YARN cluster', [
{ url: 'parts/hs', d: {} },
]);
break;
}
}
});
</script>
</head>
<body>
<div class="row-head">
<div class="column-logo">
</div>
</div>
<div class="row-navigation">
<div class="column-icons">
</div>
<div class="column-crumbs">
<div class="crumbs" id="crumbs"></div>
</div>
</div>
<div class="row-main">
<div class="column-list">
<ul>
<li><a class="_focus_" href="javascript:void(0);"><i class="icon-dashboard icon-large"></i>Dashboard</a></li>
<li><a class="_focus_" href="javascript:switch_('dns');"><i class="icon-book icon-large"></i>DNS</a></li>
<li>
<a id="_01" focus="1" href="javascript:void(0);"><i class="icon-book icon-large"></i>Hadoop</a>
<ul id="_01_">
<li><a class="_focus_" href="javascript:switch_('hs');">Install Hadoop and Spark</a></li>
</ul>
</li>
<li><a class="_focus_" href="javascript:void(0);"><i class="icon-tasks icon-large"></i>Tasks</a></li>
<li><a class="_focus_" href="javascript:void(0);"><i class="icon-bar-chart icon-large"></i>Monitor</a></li>
<li>
<a id="_02" focus="1" href="javascript:void(0);"><i class="icon-sitemap icon-large"></i>My Cluster</a>
<ul id="_02_">
<li><a class="_focus_" href="javascript:switch_('clusters');">Clusters</a></li>
<li><a class="_focus_" href="javascript:switch_('host-add');">Add Host</a></li>
<li><a class="_focus_" href="javascript:switch_('hosts');">Hosts</a></li>
</ul>
</li>
<li><a class="_focus_" href="javascript:void(0);"><i class="icon-lightbulb icon-large"></i>Issues</a></li>
<li><a class="_focus_" href="javascript:void(0);"><i class="icon-file icon-large"></i>Other Pages</a></li>
</ul>
</div>
<div class="column-board" id="board-main" style="display:none;">
<div class="title">
<span class="maintitle" id="board-main-title"></span>
<span class="subtitle" id="board-sub-title"></span>
</div>
<div class="alert">
<i class="icon-ok"></i> Welcome to use <b>ClickCloud</b> Deployment Service, the rapid deployment plan
</div>
<div id="iframe_just_me">
<!-- append to here-->
</div>
</div>
</div>
</body>
</html>
|
Java
|
package event
import (
"time"
"github.com/go-kit/kit/log"
)
type logService struct {
logger log.Logger
next Service
}
// LogServiceMiddleware given a Logger wraps the next Service with logging capabilities.
func LogServiceMiddleware(logger log.Logger, store string) ServiceMiddleware {
return func(next Service) Service {
logger = log.With(
logger,
"service", "event",
"store", store,
)
return &logService{logger: logger, next: next}
}
}
func (s *logService) Count(ns string, opts QueryOptions) (count int, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"count", count,
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Count",
"namespace", ns,
"opts", opts,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Count(ns, opts)
}
func (s *logService) Put(ns string, input *Event) (output *Event, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"input", input,
"method", "Put",
"namespace", ns,
"output", output,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Put(ns, input)
}
func (s *logService) Query(ns string, opts QueryOptions) (list List, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"datapoints", len(list),
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Query",
"namespace", ns,
"opts", opts,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Query(ns, opts)
}
func (s *logService) Setup(ns string) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Setup",
"namespace", ns,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Setup(ns)
}
func (s *logService) Teardown(ns string) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Teardown",
"namespace", ns,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Teardown(ns)
}
type logSource struct {
logger log.Logger
next Source
}
// LogSourceMiddleware given a Logger wraps the next Source logging capabilities.
func LogSourceMiddleware(store string, logger log.Logger) SourceMiddleware {
return func(next Source) Source {
logger = log.With(
logger,
"source", "event",
"store", store,
)
return &logSource{
logger: logger,
next: next,
}
}
}
func (s *logSource) Ack(id string) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"ack_id", id,
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Ack",
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Ack(id)
}
func (s *logSource) Consume() (change *StateChange, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Consume",
}
if change != nil {
ps = append(ps,
"namespace", change.Namespace,
"event_new", change.New,
"event_old", change.Old,
)
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Consume()
}
func (s *logSource) Propagate(ns string, old, new *Event) (id string, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"id", id,
"method", "Propagate",
"namespace", ns,
"event_new", new,
"event_old", old,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Propagate(ns, old, new)
}
|
Java
|
# Hieracium peterfii Nyár. & Zahn SPECIES
#### Status
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
<template name="home_footer">
<footer>
<section class="container">
<div class="blk-card-bg blk-card text-center">
<div class="client-logos">
<ul class="thumb-list">
<li>
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/soylent.svg" alt="" width="128">
</li>
<li>
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/freshdesk.png" alt="" width="156">
</li>
<li>
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/proxyclick.svg" alt="" width="125">
</li>
<li>
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/sharetribe.svg" alt="" width="218">
</li>
<li>
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/customers/vinylmeplease.png" alt="" width="119">
</li>
</ul>
</div>
<h2 class="mar-t-zero">YOU’D FEEL A DEEP KINSHIP <br class="hidden-xs">WITH OUR CUSTOMERS.</h2>
<p>We know why. Because they’re all doing great work. Just like you.</p>
<div class="mar-t-sm mar-b-xs hidden-xs hidden-sm">
<a href="/trial-signup/" class="btn btn-sec btn-primary btn-primary-sec btn-md btn-suffix">
<img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-white.svg" alt="" style="width: 30px; margin-top: -4px; margin-right: 10px;">
SIGN UP FOR FREE
</a>
</div>
<div class="hidden-xs hidden-sm"><a href="/pricing/" class="btn-flat">View our Plans and Pricing</a></div>
<!--Start Mobile-view Demo request -->
<div class="mar-t-sm mar-b-xs visible-xs visible-sm">
<a href="https://chargebee.typeform.com/to/PWNukp" data-mode="1" target="_blank" class="typeform-share btn btn-sec btn-primary btn-primary-sec btn-md btn-suffix">
<!-- <img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-white.svg" alt=""> -->
Fancy a demo?
</a>
</div>
<div class="visible-xs visible-sm"><a href="/trial-signup/" class="btn-flat">SIGN UP FOR FREE</a></div>
<!--Start Mobile-view Demo request -->
<div class="blk-testimonial bg-light hidden-xs">
<blockquote>
<div class="media">
<div class="media-left">
<img class="media-object img-circle" src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/client-matt.jpeg" width="100" alt="">
</div>
<div class="media-body">
<div class="blk-clientdescription">
Chargebee has given us greater control over our member management and product diversification as well as deep insight into our revenue cycles and member cash flow.
</div>
<div class="blk-clientname">
Matt Fiedler, <div>Founder, Vinyl Me, Please</div>
</div>
</div>
</div>
</blockquote>
</div>
</div>
</section>
<section class="bg-light pad-y-md hidden-xs">
<div class="container">
<article class="footer-anchor-part">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<div class="row">
<div class="col-sm-4">
<div class="footer-links">
<h6 class="text-uppercase">PRODUCT</h6>
<ul>
<li><a href="/subscriptions">Features</a></li>
<li><a href="/recurring-billing-saas.html">Recurring Billing - How It Works</a></li>
<li><a href="/features/eu-vat/">EU VAT</a></li>
<li><a href="/pricing/">Pricing and Plans</a></li>
<li><a href="/partners.html">Partners</a></li>
<li><a href="/integrations/">Integrations</a></li>
<li><a href="/features/webhooks/">Webhooks</a></li>
</ul>
</div>
<div class="footer-links">
<h6 class="text-uppercase">DEVELOPERS</h6>
<ul>
<li><a href="/developers/">Developer Central</a></li>
<li><a href="https://apidocs.chargebee.com/docs/api/" onclick="ga('send', 'event', 'website', 'click', 'api-docs');">API Reference</a></li>
<li><a href="/tutorials/">API Integration Tutorials</a></li>
</ul>
</div>
</div>
<div class="col-sm-4">
<div class="footer-links">
<h6 class="text-uppercase">SUPPORT</h6>
<ul>
<li><a href="/docs/">Product Documentation</a></li>
<li><a href="/discussions/">Support</a></li>
<li><a href="/guides/trials">Guides</a></li>
<li><a href="/faq/">FAQ - Online Billing</a></li>
<li><a href="/status/" target="_blank">Chargebee Service Status</a></li>
</ul>
</div>
<div class="footer-links">
<h6 class="text-uppercase">PAYMENT GATEWAYS</h6>
<ul>
<li><a href="/payment-gateways/">Find a Payment Gateway</a></li>
<li><a href="/do-more-with-stripe.html">Do More With Stripe</a></li>
<li><a href="/payment-gateways/braintree/">Do More With Braintree</a></li>
</ul>
</div>
</div>
<div class="col-sm-4">
<div class="footer-links">
<div class="chargebee-icon mar-b-xs"><img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon.svg" alt="" width="30"></div>
<ul>
<li><a href="/about/">About Us</a></li>
<li><a href="/customers/">Customers</a></li>
<li><a href="/blog/">Blog</a></li>
<li><a href="/security.html">Security</a></li>
<li><a href="/press/brand-guidelines/">Press</a></li>
<li><a href="/careers/">Careers</a></li>
<li><a href="/schedule-a-demo/">Schedule a Demo</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</article>
</div>
</section>
<section class="bg-dark-primary pad-y-md">
<div class="container">
<div class="row">
<div class="col-md-8">
<article class="blk-recent-activity">
<h5>FEATURED STORY</h5>
<div class="media">
<div class="media-left">
<a href="/blog/the-chargebee-redesign/">
<img class="media-object img-circle" src="/blog/images/posts/thumbs/chargebee-new-face.png" width="140" alt="">
</a>
</div>
<div class="media-body">
<h4 class="media-heading ff-brandon">
<a href="/blog/the-chargebee-redesign/">Spinning out the new Chargebee</a></h4>
<div class="post-author"><p><em>By Kirthika S</em></p></div>
<p>The decision to redesign Chargebee, how it came about, and where we're headed. <a href="/blog/the-chargebee-redesign/">Read More ></a></p>
</div>
</div>
</article>
</div>
<div class="col-md-4 hidden-sm">
<article class="blk-subscription">
<div class="mar-t-md mar-b-xs">
For more stories, product announcements, events, and walkthroughs, subscribe to our newsletter
</div>
<div class="blk-subscribe">
<form action="//chargebee.us4.list-manage.com/subscribe/post?u=e11a967531022bc3af44ad5ea&id=52a6570bc7" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate form" target="_blank" novalidate>
<input type="text" name="EMAIL" class="required email form-control" id="mce-EMAIL" placeholder="Enter your mail">
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn">
<span class="subscribe-placeholder">What's your email?</span>
</form>
</div>
</article>
</div>
</div>
</div>
</section>
<section class="bg-dark-primary blk-subfooter pad-y-sm">
<div class="container">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
<ul class="blk-socialmedia">
<li><a href="/terms.html">Terms</a></li>
<li><a href="/privacy.html">Privacy</a></li>
<li><a href="#"><i class="fa fa-facebook"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
</ul>
</div>
<div class="col-sm-4 hidden-xs text-center">
<div class="blk-copyright">
<a href="#"><img src="https://d2jxbtsa1l6d79.cloudfront.net/assets/web/6.3.3/images/home/chargebee-icon-gray.svg" alt="" width="30"></a>
</div>
</div>
<div class="col-sm-4 col-sm-pull-8">
<div class="blk-copyright">
©2015 Chargebee Inc. All rights reserved.
</div>
</div>
</div>
</div>
</section>
</footer>
<!-- End Footer-->
</template>
|
Java
|
/*
* 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.taverna.workbench.views.graph.config;
import javax.swing.JPanel;
import org.apache.taverna.configuration.Configurable;
import org.apache.taverna.configuration.ConfigurationUIFactory;
/**
* ConfigurationFactory for the GraphViewConfiguration.
*
* @author David Withers
*/
public class GraphViewConfigurationUIFactory implements ConfigurationUIFactory {
private GraphViewConfiguration graphViewConfiguration;
@Override
public boolean canHandle(String uuid) {
return uuid.equals(getConfigurable().getUUID());
}
@Override
public JPanel getConfigurationPanel() {
return new GraphViewConfigurationPanel(graphViewConfiguration);
}
@Override
public Configurable getConfigurable() {
return graphViewConfiguration;
}
public void setGraphViewConfiguration(
GraphViewConfiguration graphViewConfiguration) {
this.graphViewConfiguration = graphViewConfiguration;
}
}
|
Java
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudsearchv2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* UpdateDomainEndpointOptionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDomainEndpointOptionsResultStaxUnmarshaller implements Unmarshaller<UpdateDomainEndpointOptionsResult, StaxUnmarshallerContext> {
public UpdateDomainEndpointOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
UpdateDomainEndpointOptionsResult updateDomainEndpointOptionsResult = new UpdateDomainEndpointOptionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return updateDomainEndpointOptionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("DomainEndpointOptions", targetDepth)) {
updateDomainEndpointOptionsResult.setDomainEndpointOptions(DomainEndpointOptionsStatusStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return updateDomainEndpointOptionsResult;
}
}
}
}
private static UpdateDomainEndpointOptionsResultStaxUnmarshaller instance;
public static UpdateDomainEndpointOptionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new UpdateDomainEndpointOptionsResultStaxUnmarshaller();
return instance;
}
}
|
Java
|
/*
* Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved.
*
* The Sun Project JXTA(TM) Software License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by Sun Microsystems, Inc. for JXTA(TM) technology."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please contact
* Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA", nor may
* "JXTA" appear in their name, without prior written permission of Sun.
*
* 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 SUN
* MICROSYSTEMS 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.
*
* JXTA is a registered trademark of Sun Microsystems, Inc. in the United
* States and other countries.
*
* Please see the license information page at :
* <http://www.jxta.org/project/www/license.html> for instructions on use of
* the license in source files.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of Project JXTA. For more information on Project JXTA, please see
* http://www.jxta.org.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.platform;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredDocumentUtils;
import net.jxta.document.XMLDocument;
import net.jxta.document.XMLElement;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.impl.membership.pse.PSEUtils;
import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo;
import net.jxta.impl.peergroup.StdPeerGroup;
import net.jxta.impl.protocol.HTTPAdv;
import net.jxta.impl.protocol.PSEConfigAdv;
import net.jxta.impl.protocol.PeerGroupConfigAdv;
import net.jxta.impl.protocol.PlatformConfig;
import net.jxta.impl.protocol.RdvConfigAdv;
import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration;
import net.jxta.impl.protocol.RelayConfigAdv;
import net.jxta.impl.protocol.TCPAdv;
import net.jxta.logging.Logging;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.protocol.ConfigParams;
import net.jxta.protocol.TransportAdvertisement;
import javax.security.cert.CertificateException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.List;
import java.util.MissingResourceException;
import java.util.NoSuchElementException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Logger;
import net.jxta.impl.protocol.MulticastAdv;
/**
* NetworkConfigurator provides a simple programmatic interface for JXTA configuration.
* <p/>
* By default, it defines an edge configuration with TCP in auto mode w/port
* range 9701-9799, multicast enabled on group "224.0.1.85", and port 1234,
* HTTP transport with only outgoing enabled.
* <p/>
* By default a new PeerID is always generated. This can be overridden via
* {@link NetworkConfigurator#setPeerID} method or loading a PlatformConfig via
* {@link NetworkConfigurator#load}.
* <p/>
* A facility is provided to initialize a configuration by loading from an
* existing configuration. This provides limited platform configuration lifecycle
* management as well as configuration change management.
* <p/>
* Also by default, this class sets the default platform configurator to
* {@link net.jxta.impl.peergroup.NullConfigurator}. <code>NullConfigurator<code>
* is a no operation configurator intended to prevent any other configurators from
* being invoked.
* <p/>
* NetworkConfigurator makes use of classes from the {@code net.jxta.impl.*}
* packages. Applications are very strongly encouraged to avoid importing these
* classes as their interfaces may change without notice in future JXTA releases.
* The NetworkConfigurator API abstracts the configuration implementation details
* and will provide continuity and stability i.e. the NetworkConfigurator API
* won't change and it will automatically accommodate changes to service
* configuration.
* <p/>
* <em> Configuration example :</em>
* <pre>
* NetworkConfigurator config = new NetworkConfigurator();
* if (!config.exists()) {
* // Create a new configuration with a new name, principal, and pass
* config.setName("New Name");
* config.setPrincipal("username");
* config.setPassword("password");
* try {
* //persist it
* config.save();
* } catch (IOException io) {
* // deal with the io error
* }
* } else {
* // Load the pre-existing configuration
* File pc = new File(config.getHome(), "PlatformConfig");
* try {
* config.load(pc.toURI());
* // make changes if so desired
* ..
* ..
* // store the PlatformConfig under the default home
* config.save();
* } catch (CertificateException ce) {
* // In case the root cert is invalid, this creates a new one
* try {
* //principal
* config.setPrincipal("principal");
* //password to encrypt private key with
* config.setPassword("password");
* config.save();
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
* <p/>
* </pre>
*
* @since JXTA JSE 2.4
*/
public class NetworkConfigurator {
/**
* Logger
*/
private final static transient Logger LOG = Logger.getLogger(NetworkConfigurator.class.getName());
// begin configuration modes
/**
* Relay off Mode
*/
public final static int RELAY_OFF = 1 << 2;
/**
* Relay client Mode
*/
public final static int RELAY_CLIENT = 1 << 3;
/**
* Relay Server Mode
*/
public final static int RELAY_SERVER = 1 << 4;
/**
* Proxy Server Mode
*/
public final static int PROXY_SERVER = 1 << 5;
/**
* TCP transport client Mode
*/
public final static int TCP_CLIENT = 1 << 6;
/**
* TCP transport Server Mode
*/
public final static int TCP_SERVER = 1 << 7;
/**
* HTTP transport client Mode
*/
public final static int HTTP_CLIENT = 1 << 8;
/**
* HTTP transport server Mode
*/
public final static int HTTP_SERVER = 1 << 9;
/**
* IP multicast transport Mode
*/
public final static int IP_MULTICAST = 1 << 10;
/**
* RendezVousService Mode
*/
public final static int RDV_SERVER = 1 << 11;
/**
* RendezVousService Client
*/
public final static int RDV_CLIENT = 1 << 12;
/**
* RendezVousService Ad-Hoc mode
*/
public final static int RDV_AD_HOC = 1 << 13;
/**
* HTTP2 (netty http tunnel) client
*/
public final static int HTTP2_CLIENT = 1 << 14;
/**
* HTTP2 (netty http tunnel) server
*/
public final static int HTTP2_SERVER = 1 << 15;
/**
* Default AD-HOC configuration
*/
public final static int ADHOC_NODE = TCP_CLIENT | TCP_SERVER | IP_MULTICAST | RDV_AD_HOC | RELAY_OFF;
/**
* Default Edge configuration
*/
public final static int EDGE_NODE = TCP_CLIENT | TCP_SERVER | HTTP_CLIENT | HTTP2_CLIENT | IP_MULTICAST | RDV_CLIENT | RELAY_CLIENT;
/**
* Default Rendezvous configuration
*/
public final static int RDV_NODE = RDV_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
/**
* Default Relay configuration
*/
public final static int RELAY_NODE = RELAY_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
// /**
// * Default Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int PROXY_NODE = PROXY_SERVER | RELAY_NODE;
// /**
// * Default Rendezvous/Relay/Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int RDV_RELAY_PROXY_NODE = RDV_NODE | PROXY_NODE;
// end configuration modes
/**
* Default mode
*/
protected transient int mode = EDGE_NODE;
/**
* Default PlatformConfig Peer Description
*/
protected transient String description = "Platform Config Advertisement created by : " + NetworkConfigurator.class.getName();
/**
* The location which will serve as the parent for all stored items used
* by JXTA.
*/
private transient URI storeHome = null;
/**
* Default peer name
*/
protected transient String name = "unknown";
/**
* AuthenticationType used by PSEMembership to specify the type of authentication.
*/
protected transient String authenticationType = null;
/**
* Password value used to generate root Certificate and to protect the
* Certificate's PrivateKey.
*/
protected transient String password = null;
/**
* Default PeerID
*/
protected transient PeerID peerid = null;
/**
* Principal value used to generate root certificate
*/
protected transient String principal = null;
/**
* Public Certificate chain
*/
protected transient X509Certificate[] cert = null;
/**
* Subject private key
*/
protected transient PrivateKey subjectPkey = null;
/**
* Freestanding keystore location
*/
protected transient URI keyStoreLocation = null;
/**
* Proxy Service Document
*/
@Deprecated
protected transient XMLElement proxyConfig;
/**
* Personal Security Environment Config Advertisement
*
* @see net.jxta.impl.membership.pse.PSEConfig
*/
protected transient PSEConfigAdv pseConf;
/**
* Rendezvous Config Advertisement
*/
protected transient RdvConfigAdv rdvConfig;
/**
* Default Rendezvous Seeding URI
*/
protected URI rdvSeedingURI = null;
/**
* Relay Config Advertisement
*/
protected transient RelayConfigAdv relayConfig;
/**
* Default Relay Seeding URI
*/
protected transient URI relaySeedingURI = null;
/**
* TCP Config Advertisement
*/
protected transient TCPAdv tcpConfig;
/**
* Multicating Config Advertisement
*/
protected transient MulticastAdv multicastConfig;
/**
* Default TCP transport state
*/
protected transient boolean tcpEnabled = true;
/**
* Default Multicast transport state
*/
protected transient boolean multicastEnabled = true;
/**
* HTTP Config Advertisement
*/
protected transient HTTPAdv httpConfig;
/**
* Default HTTP transport state
*/
protected transient boolean httpEnabled = true;
/**
* HTTP2 Config Advertisement
*/
protected transient TCPAdv http2Config;
/**
* Default HTTP2 transport state
*/
protected transient boolean http2Enabled = true;
/**
* Infrastructure Peer Group Configuration
*/
protected transient PeerGroupConfigAdv infraPeerGroupConfig;
/**
* Creates NetworkConfigurator instance with default AD-HOC configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newAdHocConfiguration(URI storeHome) {
return new NetworkConfigurator(ADHOC_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Edge configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newEdgeConfiguration(URI storeHome) {
return new NetworkConfigurator(EDGE_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Relay configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Relay configuration
*/
public static NetworkConfigurator newRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RELAY_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE | RELAY_SERVER, storeHome);
}
// /**
// * Creates NetworkConfigurator instance with default Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with defaultProxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(PROXY_NODE, storeHome);
// }
// /**
// * Creates NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @since 2.6 It will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newRdvRelayProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(RDV_RELAY_PROXY_NODE, storeHome);
// }
/**
* Creates the default NetworkConfigurator. The configuration is stored with a default configuration mode of EDGE_NODE
*/
public NetworkConfigurator() {
this(EDGE_NODE, new File(".jxta").toURI());
}
/**
* Creates a NetworkConfigurator with the default configuration of the
* specified mode. <p/>Valid modes include ADHOC_NODE, EDGE_NODE, RDV_NODE
* PROXY_NODE, RELAY_NODE, RDV_RELAY_PROXY_NODE, or any combination of
* specific configuration.<p/> e.g. RDV_NODE | HTTP_CLIENT
*
* @param mode the new configuration mode
* @param storeHome the URI to persistent store
* @see #setMode
*/
public NetworkConfigurator(int mode, URI storeHome) {
Logging.logCheckedFine(LOG, "Creating a default configuration");
setStoreHome(storeHome);
httpConfig = createHttpAdv();
rdvConfig = createRdvConfigAdv();
relayConfig = createRelayConfigAdv();
// proxyConfig = createProxyAdv();
tcpConfig = createTcpAdv();
multicastConfig = createMulticastAdv();
http2Config = createHttp2Adv();
infraPeerGroupConfig = createInfraConfigAdv();
setMode(mode);
}
/**
* Sets PlaformConfig Peer Description element
*
* @param description the peer description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Set the current directory for configuration and cache persistent store
* <p/>(default is $CWD/.jxta)
* <p/>
* <dt>Simple example :</dt>
* <pre>
* <code>
* //Create an application home
* File appHome = new File(System.getProperty("JXTA_HOME", ".cache"));
* //Create an instance home under the application home
* File instanceHome = new File(appHome, instanceName);
* jxtaConfig.setHome(instanceHome);
* </code>
* </pre>
*
* @param home the new home value
* @see #getHome
*/
public void setHome(File home) {
this.storeHome = home.toURI();
}
/**
* Returns the current directory for configuration and cache persistent
* store. This is the same location as returned by {@link #getStoreHome()}
* which is more general than this method.
*
* @return Returns the current home directory
* @see #setHome
*/
public File getHome() {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
return new File(storeHome);
} else {
throw new UnsupportedOperationException("Home location is not a file:// URI : " + storeHome);
}
}
/**
* Returns the location which will serve as the parent for all stored items
* used by JXTA.
*
* @return The location which will serve as the parent for all stored
* items used by JXTA.
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public URI getStoreHome() {
return storeHome;
}
/**
* Sets the location which will serve as the parent for all stored items
* used by JXTA.
*
* @param newHome new home directory URI
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public void setStoreHome(URI newHome) {
// Fail if the URI is not absolute.
if (!newHome.isAbsolute()) {
throw new IllegalArgumentException("Only absolute URIs accepted for store home location.");
}
// Fail if the URI is Opaque.
if (newHome.isOpaque()) {
throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location.");
}
// FIXME this should be removed when 1488 is committed
if (!"file".equalsIgnoreCase(newHome.getScheme())) {
throw new IllegalArgumentException("Only file based URI currently supported");
}
// Adds a terminating /
if (!newHome.toString().endsWith("/")) {
newHome = URI.create(newHome.toString() + "/");
}
storeHome = newHome;
}
/**
* Toggles HTTP transport state
*
* @param enabled if true, enables HTTP transport
*/
public void setHttpEnabled(boolean enabled) {
this.httpEnabled = enabled;
if (!httpEnabled) {
httpConfig.setClientEnabled(false);
httpConfig.setServerEnabled(false);
}
}
/**
* Toggles the HTTP transport server (incoming) mode
*
* @param incoming toggles HTTP transport server mode
*/
public void setHttpIncoming(boolean incoming) {
httpConfig.setServerEnabled(incoming);
}
/**
* Toggles the HTTP transport client (outgoing) mode
*
* @param outgoing toggles HTTP transport client mode
*/
public void setHttpOutgoing(boolean outgoing) {
httpConfig.setClientEnabled(outgoing);
}
/**
* Sets the HTTP listening port (default 9901)
*
* @param port the new HTTP port value
*/
public void setHttpPort(int port) {
httpConfig.setPort(port);
}
/**
* Sets the HTTP interface Address to bind the HTTP transport to
* <p/>e.g. "192.168.1.1"
*
* @param address the new address value
*/
public void setHttpInterfaceAddress(String address) {
httpConfig.setInterfaceAddress(address);
}
/**
* Returns the HTTP interface Address
*
* @param address the HTTP interface address
*/
public String getHttpInterfaceAddress() {
return httpConfig.getInterfaceAddress();
}
/**
* Sets the HTTP JXTA Public Address
* e.g. "192.168.1.1:9700"
*
* @param address the HTTP transport public address
* @param exclusive determines whether an address is advertised exclusively
*/
public void setHttpPublicAddress(String address, boolean exclusive) {
httpConfig.setServer(address);
httpConfig.setPublicAddressOnly(exclusive);
}
public boolean isHttp2Enabled() {
return http2Enabled;
}
public void setHttp2Enabled(boolean enabled) {
http2Enabled = enabled;
if(http2Enabled) {
http2Config.setClientEnabled(false);
http2Config.setServerEnabled(false);
}
}
public boolean getHttp2IncomingStatus() {
return http2Config.getServerEnabled();
}
public void setHttp2Incoming(boolean enabled) {
http2Config.setServerEnabled(enabled);
}
public boolean getHttp2OutgoingStatus() {
return http2Config.getClientEnabled();
}
public void setHttp2Outgoing(boolean enabled) {
http2Config.setClientEnabled(enabled);
}
public int getHttp2Port() {
return http2Config.getPort();
}
public void setHttp2Port(int port) {
http2Config.setPort(port);
}
public int getHttp2StartPort() {
return http2Config.getStartPort();
}
public void setHttp2StartPort(int startPort) {
http2Config.setStartPort(startPort);
}
public int getHttp2EndPort() {
return http2Config.getEndPort();
}
public void setHttp2EndPort(int endPort) {
http2Config.setEndPort(endPort);
}
public String getHttp2InterfaceAddress() {
return http2Config.getInterfaceAddress();
}
public void setHttp2InterfaceAddress(String address) {
http2Config.setInterfaceAddress(address);
}
public String getHttp2PublicAddress() {
return http2Config.getServer();
}
public boolean isHttp2PublicAddressExclusive() {
return http2Config.getPublicAddressOnly();
}
public void setHttp2PublicAddress(String address, boolean exclusive) {
http2Config.setServer(address);
http2Config.setPublicAddressOnly(exclusive);
}
/**
* Returns the HTTP JXTA Public Address
*
* @return exclusive determines whether an address is advertised exclusively
*/
public String getHttpPublicAddress() {
return httpConfig.getServer();
}
/**
* Returns the HTTP JXTA Public Address exclusivity
*
* @return exclusive determines whether an address is advertised exclusively
*/
public boolean isHttpPublicAddressExclusive() {
return httpConfig.getPublicAddressOnly();
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param id the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(ID id) {
if (id == null || id.equals(ID.nullID)) {
throw new IllegalArgumentException("PeerGroupID can not be null");
}
infraPeerGroupConfig.setPeerGroupID(id);
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param idStr the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(String idStr) {
if (idStr == null || idStr.length() == 0) {
throw new IllegalArgumentException("PeerGroupID string can not be empty or null");
}
PeerGroupID pgid = (PeerGroupID) ID.create(URI.create(idStr));
setInfrastructureID(pgid);
}
/**
* Gets the ID which will be used for new net peer group instances.
* <p/>
*
* @return the infrastructure PeerGroupID as a string
*/
public String getInfrastructureIDStr() {
return infraPeerGroupConfig.getPeerGroupID().toString();
}
/**
* Sets the infrastructure PeerGroup name meta-data
*
* @param name the Infrastructure PeerGroup name
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGName
*/
public void setInfrastructureName(String name) {
infraPeerGroupConfig.setName(name);
}
/**
* Gets the infrastructure PeerGroup name meta-data
*
* @return the Infrastructure PeerGroup name
*/
public String getInfrastructureName() {
return infraPeerGroupConfig.getName();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDescriptionStr(String description) {
infraPeerGroupConfig.setDescription(description);
}
/**
* Returns the infrastructure PeerGroup description meta-data
*
* @return the infrastructure PeerGroup description meta-data
*/
public String getInfrastructureDescriptionStr() {
return infraPeerGroupConfig.getDescription();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDesc(XMLElement description) {
infraPeerGroupConfig.setDesc(description);
}
/**
* Sets the current node configuration mode.
* <p/>The default mode is EDGE, unless modified at construction time.
* A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
* <p/> Valid modes include EDGE, RDV_SERVER,
* RELAY_OFF, RELAY_CLIENT, RELAY_SERVER, PROXY_SERVER, or any combination
* of which.<p/> e.g. RDV_SERVER + RELAY_SERVER
*
* @param mode the new configuration mode
* @see #getMode
*/
public void setMode(int mode) {
this.mode = mode;
if ((mode & PROXY_SERVER) == PROXY_SERVER && ((mode & RELAY_SERVER) != RELAY_SERVER)) {
mode = mode | RELAY_SERVER;
}
// RELAY config
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
// RDV_SERVER
if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_AD_HOC) == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
}
// TCP
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
// HTTP
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
// HTTP2
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == HTTP2_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == HTTP2_SERVER);
// Multicast
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
// EDGE
if (mode == EDGE_NODE) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
}
}
/**
* Returns the current configuration mode
* <p/>The default mode is EDGE, unless modified at construction time or through
* Method {@link NetworkConfigurator#setMode}. A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
*
* @return mode the current mode value
* @see #setMode
*/
public int getMode() {
return mode;
}
/**
* Sets the IP group multicast packet size
*
* @param size the new multicast packet
*/
public void setMulticastSize(int size) {
multicastConfig.setMulticastSize(size);
}
/**
* Gets the IP group multicast packet size
*
* @return the multicast packet
*/
public int getMulticastSize() {
return multicastConfig.getMulticastSize();
}
/**
* Sets the IP group multicast address (default 224.0.1.85)
*
* @param mcastAddress the new multicast group address
* @see #setMulticastPort
*/
public void setMulticastAddress(String mcastAddress) {
multicastConfig.setMulticastAddr(mcastAddress);
}
/**
* Gets the multicast network interface
*
* @return the multicast network interface, null if none specified
*/
public String getMulticastInterface() {
return multicastConfig.getMulticastInterface();
}
/**
* Sets the multicast network interface
*
* @param interfaceAddress multicast network interface
*/
public void setMulticastInterface(String interfaceAddress) {
multicastConfig.setMulticastInterface(interfaceAddress);
}
/**
* Sets the IP group multicast port (default 1234)
*
* @param port the new IP group multicast port
* @see #setMulticastAddress
*/
public void setMulticastPort(int port) {
multicastConfig.setMulticastPort(port);
}
/**
* Sets the group multicast thread pool size (default 10)
*
* @param size the new multicast thread pool size
*/
public void setMulticastPoolSize(int size) {
multicastConfig.setMulticastPoolSize(size);
}
/**
* Sets the node name
*
* @param name node name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the node name
*
* @return node name
*/
public String getName() {
return this.name;
}
/**
* Sets the Principal for the peer root certificate
*
* @param principal the new principal value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPrincipal(String principal) {
this.principal = principal;
}
/**
* Gets the Principal for the peer root certificate
*
* @return principal if a principal is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPrincipal() {
return principal;
}
/**
* Sets the public Certificate for this configuration.
*
* @param cert the new cert value
*/
public void setCertificate(X509Certificate cert) {
this.cert = new X509Certificate[]{cert};
}
/**
* Returns the public Certificate for this configuration.
*
* @return X509Certificate
*/
public X509Certificate getCertificate() {
return (cert == null || cert.length == 0 ? null : cert[0]);
}
/**
* Sets the public Certificate chain for this configuration.
*
* @param certificateChain the new Certificate chain value
*/
public void setCertificateChain(X509Certificate[] certificateChain) {
this.cert = certificateChain;
}
/**
* Gets the public Certificate chain for this configuration.
*
* @return X509Certificate chain
*/
public X509Certificate[] getCertificateChain() {
return cert;
}
/**
* Sets the Subject private key
*
* @param subjectPkey the subject private key
*/
public void setPrivateKey(PrivateKey subjectPkey) {
this.subjectPkey = subjectPkey;
}
/**
* Gets the Subject private key
*
* @return the subject private key
*/
public PrivateKey getPrivateKey() {
return this.subjectPkey;
}
/**
* Sets freestanding keystore location
*
* @param keyStoreLocation the absolute location of the freestanding keystore
*/
public void setKeyStoreLocation(URI keyStoreLocation) {
this.keyStoreLocation = keyStoreLocation;
}
/**
* Gets the freestanding keystore location
*
* @return the location of the freestanding keystore
*/
public URI getKeyStoreLocation() {
return keyStoreLocation;
}
/**
* Gets the authenticationType
*
* @return authenticationType the authenticationType value
*/
public String getAuthenticationType() {
return this.authenticationType;
}
/**
* Sets the authenticationType
*
* @param authenticationType the new authenticationType value
*/
public void setAuthenticationType(String authenticationType) {
this.authenticationType = authenticationType;
}
/**
* Sets the password used to sign the private key of the root certificate
*
* @param password the new password value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Gets the password used to sign the private key of the root certificate
*
* @return password if a password is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPassword() {
return password;
}
/**
* Sets the PeerID (by default, a new PeerID is generated).
* <p/>Note: Persist the PeerID generated, or use load()
* to avoid overridding a node's PeerID between restarts.
*
* @param peerid the new <code>net.jxta.peer.PeerID</code>
*/
public void setPeerID(PeerID peerid) {
this.peerid = peerid;
}
/**
* Gets the PeerID
*
* @return peerid the <code>net.jxta.peer.PeerID</code> value
*/
public PeerID getPeerID() {
return this.peerid;
}
/**
* Sets Rendezvous Seeding URI
*
* @param seedURI Rendezvous service seeding URI
*/
public void addRdvSeedingURI(URI seedURI) {
rdvConfig.addSeedingURI(seedURI);
}
// /**
// * Sets Rendezvous Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @param aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRdvACLURI(URI aclURI) {
// rdvConfig.setAclUri(aclURI);
// }
// /**
// * Gets Rendezvous Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @return aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRdvACLURI() {
// return rdvConfig.getAclUri();
// }
// /**
// * Sets Relay Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @param aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRelayACLURI(URI aclURI) {
// relayConfig.setAclUri(aclURI);
// }
// /**
// * Gets Relay Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @return aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRelayACLURI() {
// return relayConfig.getAclUri();
// }
/**
* Sets the RelayService maximum number of simultaneous relay clients
*
* @param relayMaxClients the new relayMaxClients value
*/
public void setRelayMaxClients(int relayMaxClients) {
if ((relayMaxClients != -1) && (relayMaxClients <= 0)) {
throw new IllegalArgumentException("Relay Max Clients : " + relayMaxClients + " must be > 0");
}
relayConfig.setMaxClients(relayMaxClients);
}
/**
* Sets the RelayService Seeding URI
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint addresse(s) to relay peers
*
* @param seedURI RelayService seeding URI
*/
public void addRelaySeedingURI(URI seedURI) {
relayConfig.addSeedingURI(seedURI);
}
/**
* Sets the RendezVousService maximum number of simultaneous rendezvous clients
*
* @param rdvMaxClients the new rendezvousMaxClients value
*/
public void setRendezvousMaxClients(int rdvMaxClients) {
if ((rdvMaxClients != -1) && (rdvMaxClients <= 0)) {
throw new IllegalArgumentException("Rendezvous Max Clients : " + rdvMaxClients + " must be > 0");
}
rdvConfig.setMaxClients(rdvMaxClients);
}
/**
* Toggles TCP transport state
*
* @param enabled if true, enables TCP transport
*/
public void setTcpEnabled(boolean enabled) {
this.tcpEnabled = enabled;
if (!tcpEnabled) {
tcpConfig.setClientEnabled(false);
tcpConfig.setServerEnabled(false);
}
}
/**
* Sets the TCP transport listening port (default 9701)
*
* @param port the new tcpPort value
*/
public void setTcpPort(int port) {
tcpConfig.setPort(port);
}
/**
* Sets the lowest port on which the TCP Transport will listen if configured
* to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or less than the value
* used for end port.
*
* @param start the lowest port on which to listen.
*/
public void setTcpStartPort(int start) {
tcpConfig.setStartPort(start);
}
/**
* Returns the highest port on which the TCP Transport will listen if
* configured to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or greater than the value
* used for start port.
*
* @param end the new TCP end port
*/
public void setTcpEndPort(int end) {
tcpConfig.setEndPort(end);
}
/**
* Toggles TCP transport server (incoming) mode (default is on)
*
* @param incoming the new TCP server mode
*/
public void setTcpIncoming(boolean incoming) {
tcpConfig.setServerEnabled(incoming);
}
/**
* Toggles TCP transport client (outgoing) mode (default is true)
*
* @param outgoing the new tcpOutgoing value
*/
public void setTcpOutgoing(boolean outgoing) {
tcpConfig.setClientEnabled(outgoing);
}
/**
* Sets the TCP transport interface address
* <p/>e.g. "192.168.1.1"
*
* @param address the TCP transport interface address
*/
public void setTcpInterfaceAddress(String address) {
tcpConfig.setInterfaceAddress(address);
}
/**
* Sets the node public address
* <p/>e.g. "192.168.1.1:9701"
* <p/>This address is the physical address defined in a node's
* AccessPointAdvertisement. This often required for NAT'd/FW nodes
*
* @param address the TCP transport public address
* @param exclusive public address advertised exclusively
*/
public void setTcpPublicAddress(String address, boolean exclusive) {
tcpConfig.setServer(address);
tcpConfig.setPublicAddressOnly(exclusive);
}
/**
* Toggles whether to use IP group multicast (default is true)
*
* @param multicastOn the new useMulticast value
*/
public void setUseMulticast(boolean multicastOn) {
multicastConfig.setMulticastState(multicastOn);
}
/**
* Determines whether to restrict RelayService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
* </p>WARNING: Disabling 'use only relay seed' will cause this peer to
* search and fetch RdvAdvertisements for use as relay candidates. Rdvs
* are not necessarily relays.
*
* @param useOnlyRelaySeeds restrict RelayService lease to seed list
*/
public void setUseOnlyRelaySeeds(boolean useOnlyRelaySeeds) {
relayConfig.setUseOnlySeeds(useOnlyRelaySeeds);
}
/**
* Determines whether to restrict RendezvousService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
*
* @param useOnlyRendezvouSeeds restrict RendezvousService lease to seed list
*/
public void setUseOnlyRendezvousSeeds(boolean useOnlyRendezvouSeeds) {
rdvConfig.setUseOnlySeeds(useOnlyRendezvouSeeds);
}
/**
* Adds RelayService peer seed address
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the relay seed URI
*/
public void addSeedRelay(URI seedURI) {
relayConfig.addSeedRelay(seedURI.toString());
}
/**
* Adds Rendezvous peer seed, physical endpoint address
* <p/>A RendezVousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the rendezvous seed URI
*/
public void addSeedRendezvous(URI seedURI) {
rdvConfig.addSeedRendezvous(seedURI);
}
/**
* Returns true if a PlatformConfig file exist under store home
*
* @return true if a PlatformConfig file exist under store home
*/
public boolean exists() {
URI platformConfig = storeHome.resolve("PlatformConfig");
try {
return null != read(platformConfig);
} catch (IOException failed) {
return false;
}
}
/**
* Sets the PeerID for this Configuration
*
* @param peerIdStr the new PeerID as a string
*/
public void setPeerId(String peerIdStr) {
this.peerid = (PeerID) ID.create(URI.create(peerIdStr));
}
/**
* Sets the new RendezvousService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers
*
* @param seedURIStr the new rendezvous seed URI as a string
*/
public void addRdvSeedingURI(String seedURIStr) {
rdvConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the new RelayService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIStr the new RelayService seed URI as a string
*/
public void addRelaySeedingURI(String seedURIStr) {
relayConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the List relaySeeds represented as Strings
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set RelayService seed URIs as a string
*/
public void setRelaySeedURIs(List<String> seeds) {
relayConfig.clearSeedRelays();
for (String seedStr : seeds) {
relayConfig.addSeedRelay(new EndpointAddress(seedStr));
}
}
/**
* Sets the relaySeeds represented as Strings
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIs the List relaySeeds represented as Strings
*/
public void setRelaySeedingURIs(Set<String> seedURIs) {
relayConfig.clearSeedingURIs();
for (String seedStr : seedURIs) {
relayConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the List of RelayService seeds
*/
public void clearRelaySeeds() {
relayConfig.clearSeedRelays();
}
/**
* Clears the List of RelayService seeding URIs
*/
public void clearRelaySeedingURIs() {
relayConfig.clearSeedingURIs();
}
/**
* Sets the List of RendezVousService seeds represented as Strings
* <p/>A RendezvousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set of rendezvousSeeds represented as Strings
*/
public void setRendezvousSeeds(Set<String> seeds) {
rdvConfig.clearSeedRendezvous();
for (String seedStr : seeds) {
rdvConfig.addSeedRendezvous(URI.create(seedStr));
}
}
/**
* Sets the List of RendezVousService seeding URIs represented as Strings.
* A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers.
*
* @param seedingURIs the List rendezvousSeeds represented as Strings.
*/
public void setRendezvousSeedingURIs(List<String> seedingURIs) {
rdvConfig.clearSeedingURIs();
for (String seedStr : seedingURIs) {
rdvConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the list of RendezVousService seeds
*/
public void clearRendezvousSeeds() {
rdvConfig.clearSeedRendezvous();
}
/**
* Clears the list of RendezVousService seeding URIs
*/
public void clearRendezvousSeedingURIs() {
rdvConfig.clearSeedingURIs();
}
/**
* Load a configuration from the specified store home uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MembershipService is invalid
*/
public ConfigParams load() throws IOException, CertificateException {
return load(storeHome.resolve("PlatformConfig"));
}
/**
* Loads a configuration from a specified uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @param uri the URI to PlatformConfig
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MemebershipService is invalid
*/
public ConfigParams load(URI uri) throws IOException, CertificateException {
if (uri == null) throw new IllegalArgumentException("URI can not be null");
Logging.logCheckedFine(LOG, "Loading configuration : ", uri);
PlatformConfig platformConfig = read(uri);
name = platformConfig.getName();
peerid = platformConfig.getPeerID();
description = platformConfig.getDescription();
XMLElement<?> param;
// TCP
tcpEnabled = platformConfig.isSvcEnabled(PeerGroup.tcpProtoClassID);
tcpConfig = loadTcpAdv(platformConfig, PeerGroup.tcpProtoClassID);
multicastEnabled = platformConfig.isSvcEnabled(PeerGroup.multicastProtoClassID);
multicastConfig = loadMulticastAdv(platformConfig, PeerGroup.multicastProtoClassID);
// HTTP
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.httpProtoClassID);
httpEnabled = platformConfig.isSvcEnabled(PeerGroup.httpProtoClassID);
Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv
if (httpChilds.hasMoreElements()) {
param = (XMLElement) httpChilds.nextElement();
} else {
throw new IllegalStateException("Missing HTTP Advertisment");
}
// Read-in the adv as it is now.
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the HTTP config advertisement");
ioe.initCause(failure);
throw ioe;
}
// HTTP2
http2Enabled = platformConfig.isSvcEnabled(PeerGroup.http2ProtoClassID);
http2Config = loadTcpAdv(platformConfig, PeerGroup.http2ProtoClassID);
// // ProxyService
// try {
// param = (XMLElement) platformConfig.getServiceParam(PeerGroup.proxyClassID);
// if (param != null && !platformConfig.isSvcEnabled(PeerGroup.proxyClassID)) {
// mode = mode | PROXY_SERVER;
// }
// } catch (Exception failure) {
// IOException ioe = new IOException("error processing the pse config advertisement");
// ioe.initCause(failure);
// throw ioe;
// }
// Rendezvous
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.rendezvousClassID);
// backwards compatibility
param.addAttribute("type", RdvConfigAdv.getAdvertisementType());
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param);
if (rdvConfig.getConfiguration() == RendezVousConfiguration.AD_HOC) {
mode = mode | RDV_AD_HOC;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.EDGE) {
mode = mode | RDV_CLIENT;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.RENDEZVOUS) {
mode = mode | RDV_SERVER;
}
} catch (Exception failure) {
IOException ioe = new IOException("error processing the rendezvous config advertisement");
ioe.initCause(failure);
throw ioe;
}
// Relay
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.relayProtoClassID);
if (param != null && !platformConfig.isSvcEnabled(PeerGroup.relayProtoClassID)) {
mode = mode | RELAY_OFF;
}
// backwards compatibility
param.addAttribute("type", RelayConfigAdv.getAdvertisementType());
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the relay config advertisement");
ioe.initCause(failure);
throw ioe;
}
// PSE
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID);
if (param != null) {
Advertisement adv = null;
try {
adv = AdvertisementFactory.newAdvertisement(param);
} catch (NoSuchElementException notAnAdv) {
CertificateException cnfe = new CertificateException("No membership advertisement found");
cnfe.initCause(notAnAdv);
} catch (IllegalArgumentException invalidAdv) {
CertificateException cnfe = new CertificateException("Invalid membership advertisement");
cnfe.initCause(invalidAdv);
}
if (adv instanceof PSEConfigAdv) {
pseConf = (PSEConfigAdv) adv;
cert = pseConf.getCertificateChain();
} else {
throw new CertificateException("Error processing the Membership config advertisement. Unexpected membership advertisement "
+ adv.getAdvertisementType());
}
}
// Infra Group
infraPeerGroupConfig = (PeerGroupConfigAdv) platformConfig.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID);
if (null == infraPeerGroupConfig) {
infraPeerGroupConfig = createInfraConfigAdv();
try {
URI configPropsURI = storeHome.resolve("config.properties");
InputStream configPropsIS = configPropsURI.toURL().openStream();
ResourceBundle rsrcs = new PropertyResourceBundle(configPropsIS);
configPropsIS.close();
NetGroupTunables tunables = new NetGroupTunables(rsrcs, new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
} catch (IOException ignored) {
//ignored
} catch (MissingResourceException ignored) {
//ignored
}
}
return platformConfig;
}
private TCPAdv loadTcpAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or tcpConfig
if (tcpChilds.hasMoreElements()) {
param = (XMLElement<?>) tcpChilds.nextElement();
} else {
throw new IllegalStateException("Missing TCP Advertisement");
}
return (TCPAdv) AdvertisementFactory.newAdvertisement(param);
}
private MulticastAdv loadMulticastAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param2 = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds2 = param2.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or multicastConfig
if (tcpChilds2.hasMoreElements()) {
param2 = (XMLElement<?>) tcpChilds2.nextElement();
} else {
throw new IllegalStateException("Missing Multicast Advertisment");
}
return (MulticastAdv) AdvertisementFactory.newAdvertisement(param2);
}
/**
* Persists a PlatformConfig advertisement under getStoreHome()+"/PlaformConfig"
* <p/>
* Home may be overridden by a call to setHome()
*
* @throws IOException If there is a failure saving the PlatformConfig.
* @see #load
*/
public void save() throws IOException {
httpEnabled = (httpConfig.isClientEnabled() || httpConfig.isServerEnabled());
tcpEnabled = (tcpConfig.isClientEnabled() || tcpConfig.isServerEnabled());
http2Enabled = (http2Config.isClientEnabled() || http2Config.isServerEnabled());
ConfigParams advertisement = getPlatformConfig();
OutputStream out = null;
try {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
File saveDir = new File(storeHome);
saveDir.mkdirs();
// Sadly we can't use URL.openConnection() to create the
// OutputStream for file:// URLs. bogus.
out = new FileOutputStream(new File(saveDir, "PlatformConfig"));
} else {
out = storeHome.resolve("PlatformConfig").toURL().openConnection().getOutputStream();
}
XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8);
OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");
aDoc.sendToWriter(os);
os.flush();
} finally {
if (null != out) {
out.close();
}
}
}
/**
* Returns a XMLDocument representation of an Advertisement
*
* @param enabled whether the param doc is enabled, adds a "isOff"
* element if disabled
* @param adv the Advertisement to retrieve the param doc from
* @return the parmDoc value
*/
protected XMLDocument getParmDoc(boolean enabled, Advertisement adv) {
XMLDocument parmDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
XMLDocument doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8);
StructuredDocumentUtils.copyElements(parmDoc, parmDoc, doc);
if (!enabled) {
parmDoc.appendChild(parmDoc.createElement("isOff"));
}
return parmDoc;
}
/**
* Creates an HTTP transport advertisement
*
* @return an HTTP transport advertisement
*/
protected HTTPAdv createHttpAdv() {
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType());
httpConfig.setProtocol("http");
httpConfig.setPort(9700);
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
return httpConfig;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param principal principal
* @param password the password used to sign the private key of the root certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(String principal, String password) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (principal != null && password != null) {
IssuerInfo info = PSEUtils.genCert(principal, null);
pseConf.setCertificate(info.cert);
pseConf.setPrivateKey(info.subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param cert X509Certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate cert) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificate(cert);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param certificateChain X509Certificate[]
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate[] certificateChain) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificateChain(certificateChain);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates a ProxyService configuration advertisement
*
* @return ProxyService configuration advertisement
*/
@Deprecated
protected XMLDocument createProxyAdv() {
return (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
}
/**
* Creates a RendezVousService configuration advertisement with default values (EDGE)
*
* @return a RdvConfigAdv
*/
protected RdvConfigAdv createRdvConfigAdv() {
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType());
if (mode == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
}
// A better alternative is to reference rdv service defaults (currently private)
// rdvConfig.setMaxClients(200);
return rdvConfig;
}
/**
* Creates a RelayService configuration advertisement with default values (EDGE)
*
* @return a RelayConfigAdv
*/
protected RelayConfigAdv createRelayConfigAdv() {
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType());
// Since 2.6 - We should only use seeds when it comes to relay (see Javadoc)
// relayConfig.setUseOnlySeeds(false);
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT || mode == EDGE_NODE);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
return relayConfig;
}
/**
* Creates an TCP transport advertisement with the platform default values.
* multicast on, 224.0.1.85:1234, with a max packet size of 16K
*
* @return a TCP transport advertisement
*/
protected TCPAdv createTcpAdv() {
tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
tcpConfig.setProtocol("tcp");
tcpConfig.setInterfaceAddress(null);
tcpConfig.setPort(9701);
//tcpConfig.setStartPort(9701);
//tcpConfig.setEndPort(9799);
tcpConfig.setServer(null);
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
return tcpConfig;
}
/**
* Creates an multicast transport advertisement with the platform default values.
* Multicast on, 224.0.1.85:1234, with a max packet size of 16K.
*
* @return a TCP transport advertisement
*/
protected MulticastAdv createMulticastAdv() {
multicastConfig = (MulticastAdv) AdvertisementFactory.newAdvertisement(MulticastAdv.getAdvertisementType());
multicastConfig.setProtocol("tcp");
multicastConfig.setMulticastAddr("224.0.1.85");
multicastConfig.setMulticastPort(1234);
multicastConfig.setMulticastSize(16384);
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
return multicastConfig;
}
protected TCPAdv createHttp2Adv() {
http2Config = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
http2Config.setProtocol("http2");
http2Config.setInterfaceAddress(null);
http2Config.setPort(8080);
http2Config.setStartPort(8080);
http2Config.setEndPort(8089);
http2Config.setServer(null);
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == TCP_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == TCP_SERVER);
return http2Config;
}
protected PeerGroupConfigAdv createInfraConfigAdv() {
infraPeerGroupConfig = (PeerGroupConfigAdv) AdvertisementFactory.newAdvertisement(
PeerGroupConfigAdv.getAdvertisementType());
NetGroupTunables tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
return infraPeerGroupConfig;
}
/**
* Returns a PlatformConfig which represents a platform configuration.
* <p/>Fine tuning is achieved through accessing each configured advertisement
* and achieved through accessing each configured advertisement and modifying
* each object directly.
*
* @return the PeerPlatformConfig Advertisement
*/
public ConfigParams getPlatformConfig() {
PlatformConfig advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement(
PlatformConfig.getAdvertisementType());
advertisement.setName(name);
advertisement.setDescription(description);
if (tcpConfig != null) {
boolean enabled = tcpEnabled && (tcpConfig.isServerEnabled() || tcpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.tcpProtoClassID, getParmDoc(enabled, tcpConfig));
}
if (multicastConfig != null) {
boolean enabled = multicastConfig.getMulticastState();
advertisement.putServiceParam(PeerGroup.multicastProtoClassID, getParmDoc(enabled, multicastConfig));
}
if (httpConfig != null) {
boolean enabled = httpEnabled && (httpConfig.isServerEnabled() || httpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.httpProtoClassID, getParmDoc(enabled, httpConfig));
}
if (http2Config != null) {
boolean enabled = http2Enabled && (http2Config.isServerEnabled() || http2Config.isClientEnabled());
advertisement.putServiceParam(PeerGroup.http2ProtoClassID, getParmDoc(enabled, http2Config));
}
if (relayConfig != null) {
boolean isOff = ((mode & RELAY_OFF) == RELAY_OFF) || (relayConfig.isServerEnabled() && relayConfig.isClientEnabled());
XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8);
if (isOff) {
relayDoc.appendChild(relayDoc.createElement("isOff"));
}
advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc);
}
if (rdvConfig != null) {
XMLDocument rdvDoc = (XMLDocument) rdvConfig.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc);
}
if (principal == null) {
principal = System.getProperty("impl.membership.pse.authentication.principal", "JxtaCN");
}
if (password == null) {
password = System.getProperty("impl.membership.pse.authentication.password", "the!one!password");
}
if (cert != null) {
pseConf = createPSEAdv(cert);
} else {
pseConf = createPSEAdv(principal, password);
cert = pseConf.getCertificateChain();
}
if (pseConf != null) {
if (keyStoreLocation != null) {
if (keyStoreLocation.isAbsolute()) {
pseConf.setKeyStoreLocation(keyStoreLocation);
} else {
Logging.logCheckedWarning(LOG, "Keystore location set, but is not absolute: ", keyStoreLocation);
}
}
XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc);
}
if (authenticationType == null) {
authenticationType = System.getProperty("impl.membership.pse.authentication.type", "StringAuthentication");
}
StdPeerGroup.setPSEMembershipServiceKeystoreInfoFactory(new StdPeerGroup.DefaultPSEMembershipServiceKeystoreInfoFactory(authenticationType, password));
if (peerid == null) {
peerid = IDFactory.newPeerID(PeerGroupID.worldPeerGroupID, cert[0].getPublicKey().getEncoded());
}
advertisement.setPeerID(peerid);
// if (proxyConfig != null && ((mode & PROXY_SERVER) == PROXY_SERVER)) {
// advertisement.putServiceParam(PeerGroup.proxyClassID, proxyConfig);
// }
if ((null != infraPeerGroupConfig) && (null != infraPeerGroupConfig.getPeerGroupID())
&& (ID.nullID != infraPeerGroupConfig.getPeerGroupID())
&& (PeerGroupID.defaultNetPeerGroupID != infraPeerGroupConfig.getPeerGroupID())) {
advertisement.setSvcConfigAdvertisement(PeerGroup.peerGroupClassID, infraPeerGroupConfig);
}
return advertisement;
}
/**
* @param location The location of the platform config.
* @return The platformConfig
* @throws IOException Thrown for failures reading the PlatformConfig.
*/
private PlatformConfig read(URI location) throws IOException {
URL url;
try {
url = location.toURL();
} catch (MalformedURLException mue) {
IllegalArgumentException failure = new IllegalArgumentException("Failed to convert URI to URL");
failure.initCause(mue);
throw failure;
}
InputStream input = url.openStream();
try {
XMLDocument document = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, input);
PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(document);
return platformConfig;
} finally {
input.close();
}
}
/**
* Indicates whether Http is enabled
*
* @return true if Http is enabled, else returns false
* @see #setHttpEnabled
*/
public boolean isHttpEnabled() {
return this.httpEnabled;
}
/**
* Retrieves the Http incoming status
*
* @return true if Http incomming status is enabled, else returns false
* @see #setHttpIncoming
*/
public boolean getHttpIncomingStatus() {
return httpConfig.getServerEnabled();
}
/**
* Retrieves the Http outgoing status
*
* @return true if Http outgoing status is enabled, else returns false
* @see #setHttpOutgoing
*/
public boolean getHttpOutgoingStatus() {
return httpConfig.getClientEnabled();
}
/**
* Retrieves the Http port
*
* @return the current Http port
* @see #setHttpPort
*/
public int getHttpPort() {
return httpConfig.getPort();
}
/**
* Retrieves the current infrastructure ID
*
* @return the current infrastructure ID
* @see #setInfrastructureID
*/
public ID getInfrastructureID() {
return infraPeerGroupConfig.getPeerGroupID();
}
/**
* Retrieves the current multicast address
*
* @return the current multicast address
* @see #setMulticastAddress
*/
public String getMulticastAddress() {
return multicastConfig.getMulticastAddr();
}
/**
* Retrieves the current multicast port
*
* @return the current mutlicast port
* @see #setMulticastPort
*/
public int getMulticastPort() {
return multicastConfig.getMulticastPort();
}
/**
* Gets the group multicast thread pool size
*
* @return multicast thread pool size
*/
public int getMulticastPoolSize() {
return multicastConfig.getMulticastPoolSize();
}
/**
* Indicates whether tcp is enabled
*
* @return true if tcp is enabled, else returns false
* @see #setTcpEnabled
*/
public boolean isTcpEnabled() {
return this.tcpEnabled;
}
/**
* Retrieves the current tcp end port
*
* @return the current tcp port
* @see #setTcpEndPort
*/
public int getTcpEndport() {
return tcpConfig.getEndPort();
}
/**
* Retrieves the Tcp incoming status
*
* @return true if tcp incoming is enabled, else returns false
* @see #setTcpIncoming
*/
public boolean getTcpIncomingStatus() {
return tcpConfig.getServerEnabled();
}
/**
* Retrieves the Tcp outgoing status
*
* @return true if tcp outcoming is enabled, else returns false
* @see #setTcpOutgoing
*/
public boolean getTcpOutgoingStatus() {
return tcpConfig.getClientEnabled();
}
/**
* Retrieves the Tcp interface address
*
* @return the current tcp interface address
* @see #setTcpInterfaceAddress
*/
public String getTcpInterfaceAddress() {
return tcpConfig.getInterfaceAddress();
}
/**
* Retrieves the current Tcp port
*
* @return the current tcp port
* @see #setTcpPort
*/
public int getTcpPort() {
return tcpConfig.getPort();
}
/**
* Retrieves the current Tcp public address
*
* @return the current tcp public address
* @see #setTcpPublicAddress
*/
public String getTcpPublicAddress() {
return tcpConfig.getServer();
}
/**
* Indicates whether the current Tcp public address is exclusive
*
* @return true if the current tcp public address is exclusive, else returns false
* @see #setTcpPublicAddress
*/
public boolean isTcpPublicAddressExclusive() {
return tcpConfig.getPublicAddressOnly();
}
/**
* Retrieves the current Tcp start port
*
* @return the current tcp start port
* @see #setTcpStartPort
*/
public int getTcpStartPort() {
return tcpConfig.getStartPort();
}
/**
* Retrieves the multicast use status
*
* @return true if multicast is enabled, else returns false
* @see #setUseMulticast
*/
public boolean getMulticastStatus() {
return multicastConfig.getMulticastState();
}
/**
* Retrieves the use relay seeds only status
*
* @return true if only relay seeds are used, else returns false
* @see #setUseOnlyRelaySeeds
*/
public boolean getUseOnlyRelaySeedsStatus() {
return relayConfig.getUseOnlySeeds();
}
/**
* Retrieves the use rendezvous seeds only status
*
* @return true if only rendezvous seeds are used, else returns false
* @see #setUseOnlyRendezvousSeeds
*/
public boolean getUseOnlyRendezvousSeedsStatus() {
return rdvConfig.getUseOnlySeeds();
}
/**
* Retrieves the RendezVousService maximum number of simultaneous rendezvous clients
*
* @return the RendezVousService maximum number of simultaneous rendezvous clients
* @see #setRendezvousMaxClients
*/
public int getRendezvousMaxClients() {
return rdvConfig.getMaxClients();
}
/**
* Retrieves the RelayVousService maximum number of simultaneous relay clients
*
* @return the RelayService maximum number of simultaneous relay clients
* @see #setRelayMaxClients
*/
public int getRelayMaxClients() {
return relayConfig.getMaxClients();
}
/**
* Retrieves the rendezvous seedings
*
* @return the array of rendezvous seeding URL
* @see #addRdvSeedingURI
*/
public URI[] getRdvSeedingURIs() {
return rdvConfig.getSeedingURIs();
}
/**
* Retrieves the rendezvous seeds
*
* @return the array of rendezvous seeds URL
* @see #addRdvSeedURI
*/
public URI[] getRdvSeedURIs() {
return rdvConfig.getSeedRendezvous();
}
/**
* Retrieves the relay seeds
*
* @return the array of relay seeds URL
* @see #addRelaySeedURI
*/
public URI[] getRelaySeedURIs() {
return relayConfig.getSeedRelayURIs();
}
/**
* Retrieves the relay seeds
*
* @return the array of rendezvous seed URL
* @see #addRelaySeedingURI
*/
public URI[] getRelaySeedingURIs() {
return relayConfig.getSeedingURIs();
}
/**
* Holds the construction tunables for the Net Peer Group. This consists of
* the peer group id, the peer group name and the peer group description.
*/
static class NetGroupTunables {
final ID id;
final String name;
final XMLElement desc;
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*/
NetGroupTunables() {
id = PeerGroupID.defaultNetPeerGroupID;
name = "NetPeerGroup";
desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group");
}
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*
* @param pgid the PeerGroupID
* @param pgname the group name
* @param pgdesc the group description
*/
NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) {
id = pgid;
name = pgname;
desc = pgdesc;
}
/**
* Constructor for loading the Net Peer Group construction
* tunables from the provided resource bundle.
*
* @param rsrcs The resource bundle from which resources will be loaded.
* @param defaults default values
*/
NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) {
ID idTmp;
String nameTmp;
XMLElement descTmp;
try {
String idTmpStr = rsrcs.getString("NetPeerGroupID").trim();
if (idTmpStr.startsWith(ID.URNNamespace + ":")) {
idTmpStr = idTmpStr.substring(5);
}
idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr));
nameTmp = rsrcs.getString("NetPeerGroupName").trim();
descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", rsrcs.getString("NetPeerGroupDesc").trim());
} catch (Exception failed) {
if (null != defaults) {
Logging.logCheckedFine(LOG, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.\n\n", failed);
idTmp = defaults.id;
nameTmp = defaults.name;
descTmp = defaults.desc;
} else {
Logging.logCheckedSevere(LOG, "NetPeerGroup tunables not defined or could not be loaded.\n", failed);
throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded.");
}
}
id = idTmp;
name = nameTmp;
desc = descTmp;
}
}
}
|
Java
|
import Observable from '../Observable';
import mergeStatic from './merge-static';
export default function merge<R>(...observables: (Observable<any>|number)[]): Observable<R> {
observables.unshift(this);
return mergeStatic.apply(this, observables);
}
|
Java
|
package com.sissi.protocol.message;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import com.sissi.io.read.Metadata;
/**
* @author kim 2014年1月28日
*/
@Metadata(uri = Message.XMLNS, localName = Thread.NAME)
@XmlRootElement
public class Thread {
public final static String NAME = "thread";
private String text;
private String parent;
public Thread() {
super();
}
public Thread(String text) {
super();
this.text = text;
}
public Thread(String text, String parent) {
super();
this.text = text;
this.parent = parent;
}
@XmlValue
public String getText() {
return this.text;
}
public Thread setText(String text) {
this.text = text;
return this;
}
@XmlAttribute
public String getParent() {
return this.parent;
}
public Thread setParent(String parent) {
this.parent = parent;
return this;
}
public boolean content() {
return this.text != null && this.text.length() > 0;
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0) on Fri Feb 01 09:13:22 EST 2013 -->
<title>Uses of Class org.drip.analytics.holset.IEPHoliday</title>
<meta name="date" content="2013-02-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.drip.analytics.holset.IEPHoliday";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/drip/analytics/holset/IEPHoliday.html" title="class in org.drip.analytics.holset">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/drip/analytics/holset/\class-useIEPHoliday.html" target="_top">Frames</a></li>
<li><a href="IEPHoliday.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.drip.analytics.holset.IEPHoliday" class="title">Uses of Class<br>org.drip.analytics.holset.IEPHoliday</h2>
</div>
<div class="classUseContainer">No usage of org.drip.analytics.holset.IEPHoliday</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/drip/analytics/holset/IEPHoliday.html" title="class in org.drip.analytics.holset">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/drip/analytics/holset/\class-useIEPHoliday.html" target="_top">Frames</a></li>
<li><a href="IEPHoliday.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
# kauri
|
Java
|
#import <Cocoa/Cocoa.h>
FOUNDATION_EXPORT double SwiftHTTPVersionNumber;
FOUNDATION_EXPORT const unsigned char SwiftHTTPVersionString[];
|
Java
|
---
layout: default
title: CAS - Password Management
category: Password Management
---
# Password Management
If authentication fails due to a rejected password policy, CAS is able to intercept
that request and allow the user to update the account password in place. The password management features of CAS are rather modest, and alternatively should the functionality provide inadequate for your policy, you may always redirect CAS to use a separate and standalone application that is fully in charge of managing the account password and associated flows.
CAS may also allow users to reset their passwords voluntarily. Those who have forgotten their account password
may receive a secure link with a time-based expiration policy at their registered email address and/or phone. The link
will allow the user to provide answers to his/her pre-defined security questions, which if successfully done,
will allow the user to next reset their password and login again. You may also specify a pattern for accepted passwords.
By default, after a user has successfully changed their password they will be redirected to the login screen
to enter their new password and log in. CAS can also be configured to automatically log the user in after
a successful change. This behavior can be altered via CAS settings.
To learn more about available notification options, please [see this guide](SMS-Messaging-Configuration.html) or [this guide](Sending-Email-Configuration.html). To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#password-management).
## JSON
Accounts and password may be stored inside a static modest JSON resource. This option is most useful during development and
for demo purposes. To learn more, please [see this guide](Password-Management-JSON.html).
## Groovy
Accounts and password may be handled and calculated via a Groovy script. To learn more, please [see this guide](Password-Management-Groovy.html).
## LDAP
The account password and security questions may be stored inside an LDAP server. To learn more, please [see this guide](Password-Management-LDAP.html).
## JDBC
The account password and security questions may be stored inside a relational database. To learn more, please [see this guide](Password-Management-JDBC.html).
## REST
The account password and security questions can also be managed using a REST API. To learn more please [see this guide](Password-Management-REST.html).
## Custom
To design your own password management storage options and strategy, please [see this guide](Password-Management-Custom.html).
|
Java
|
package instance
import (
"io/ioutil"
"os"
"testing"
"github.com/scaleway/scaleway-cli/internal/core"
)
func Test_UserDataGet(t *testing.T) {
t.Run("Get an existing key", core.Test(&core.TestConfig{
BeforeFunc: core.BeforeFuncCombine(
createServer("Server"),
core.ExecBeforeCmd("scw instance user-data set server-id={{.Server.ID}} key=happy content=true"),
),
Commands: GetCommands(),
Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy",
AfterFunc: deleteServer("Server"),
Check: core.TestCheckCombine(
core.TestCheckGolden(),
core.TestCheckExitCode(0),
),
}))
t.Run("Get an nonexistent key", core.Test(&core.TestConfig{
BeforeFunc: createServer("Server"),
Commands: GetCommands(),
Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy",
AfterFunc: deleteServer("Server"),
Check: core.TestCheckCombine(
core.TestCheckGolden(),
core.TestCheckExitCode(1),
),
}))
}
func Test_UserDataList(t *testing.T) {
t.Run("Simple", core.Test(&core.TestConfig{
BeforeFunc: core.BeforeFuncCombine(
createServer("Server"),
core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=foo content=bar"),
core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=bar content=foo"),
),
Commands: GetCommands(),
Cmd: "scw instance user-data list server-id={{ .Server.ID }}",
AfterFunc: deleteServer("Server"),
Check: core.TestCheckCombine(
core.TestCheckGolden(),
core.TestCheckExitCode(0),
),
}))
}
func Test_UserDataFileUpload(t *testing.T) {
content := "cloud-init file content"
t.Run("on-cloud-init", core.Test(&core.TestConfig{
Commands: GetCommands(),
BeforeFunc: core.BeforeFuncCombine(
core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"),
func(ctx *core.BeforeFuncCtx) error {
file, _ := ioutil.TempFile("", "test")
_, _ = file.WriteString(content)
ctx.Meta["filePath"] = file.Name()
return nil
},
),
Cmd: `scw instance user-data set key=cloud-init server-id={{ .Server.ID }} content=@{{ .filePath }}`,
Check: core.TestCheckCombine(
core.TestCheckGolden(),
),
AfterFunc: core.AfterFuncCombine(
func(ctx *core.AfterFuncCtx) error {
_ = os.RemoveAll(ctx.Meta["filePath"].(string))
return nil
},
),
}))
t.Run("on-random-key", core.Test(&core.TestConfig{
Commands: GetCommands(),
BeforeFunc: core.BeforeFuncCombine(
core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"),
func(ctx *core.BeforeFuncCtx) error {
file, _ := ioutil.TempFile("", "test")
_, _ = file.WriteString(content)
ctx.Meta["filePath"] = file.Name()
return nil
},
),
Cmd: `scw instance user-data set key=foobar server-id={{ .Server.ID }} content=@{{ .filePath }}`,
Check: core.TestCheckCombine(
core.TestCheckGolden(),
),
AfterFunc: core.AfterFuncCombine(
func(ctx *core.AfterFuncCtx) error {
_ = os.RemoveAll(ctx.Meta["filePath"].(string))
return nil
},
),
}))
}
|
Java
|
# wardtrack
A web application to track and visualise questionnaire data.
|
Java
|
using ArangoDB.Client.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArangoDB.Client
{
public class BaseResultAnalyzer
{
IArangoDatabase db;
public BaseResultAnalyzer(IArangoDatabase db)
{
this.db = db;
}
public void ThrowIfNeeded(BaseResult baseResult)
{
if (baseResult.HasError() && db.Setting.ThrowForServerErrors == true)
{
throw new ArangoServerException(baseResult);
}
}
public void Throw(BaseResult baseResult)
{
if (baseResult.HasError())
throw new ArangoServerException(baseResult);
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.