code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Delphi CodeCoverage Coverage Report</title>
<style type="text/css">
table {border-spacing:0; border-collapse:collapse;}
table, td, th {border: 1px solid black;}
td, th {background: white; margin: 0; padding: 2px 0.5em 2px 0.5em}
td {border-width: 0 1px 0 0;}
th {border-width: 1px 1px 1px 0;}
p, h1, h2, h3, th {font-family: verdana,arial,sans-serif; font-size: 10pt;}
td {font-family: courier,monospace; font-size: 10pt;}
th {background: #CCCCCC;}
table.o tr td:nth-child(1) {font-weight: bold;}
table.o tr td:nth-child(2) {text-align: right;}
table.o tr td {border-width: 1px;}
table.s {width: 100%;}
table.s tr td {padding: 0 0.25em 0 0.25em;}
table.s tr td:first-child {text-align: right; font-weight: bold;}
table.s tr.notcovered td {background: #DDDDFF;}
table.s tr.nocodegen td {background: #FFFFEE;}
table.s tr.covered td {background: #CCFFCC;}
table.s tr.covered td:first-child {color: green;}
table.s {border-width: 1px 0 1px 1px;}
table.sum tr td {border-width: 1px;}
table.sum tr th {text-align:right;}
table.sum tr th:first-child {text-align:center;}
table.sum tr td {text-align:right;}
table.sum tr td:first-child {text-align:left;}
</style>
</head>
<body>
<p>Coverage report for <strong>Core.Card (I:\Examples\DUnitX_CodeCoverage\Core\Core.Card.pas)</strong>.</p>
<p> Generated at 6/11/2015 11:19:07 AM by <a href="http://code.google.com/p/delphi-code-coverage/" title="Code Coverage for Delphi 5+">DelphiCodeCoverage</a> - an open source tool for Delphi Code Coverage.</p>
<p> Statistics for I:\Examples\DUnitX_CodeCoverage\Core\Core.Card.pas </p>
<table class="o"><tr><td>Number of lines covered</td><td>11</td></tr><tr><td>Number of lines with code gen</td><td>15</td></tr><tr><td>Line coverage</td><td>73%</td></tr></table>
<br /><br />
<table class="s">
<tr class="nocodegen"><td>1</td><td><pre style="display:inline;">unit Core.Card;</pre></td></tr>
<tr class="nocodegen"><td>2</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>3</td><td><pre style="display:inline;">interface</pre></td></tr>
<tr class="nocodegen"><td>4</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>5</td><td><pre style="display:inline;">type</pre></td></tr>
<tr class="nocodegen"><td>6</td><td><pre style="display:inline;"> ICard = interface</pre></td></tr>
<tr class="nocodegen"><td>7</td><td><pre style="display:inline;"> ['{1BD19858-F354-498C-AF3D-E363122019A3}']</pre></td></tr>
<tr class="nocodegen"><td>8</td><td><pre style="display:inline;"> function GetFacingUp : boolean;</pre></td></tr>
<tr class="nocodegen"><td>9</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>10</td><td><pre style="display:inline;"> function Flip : boolean;</pre></td></tr>
<tr class="nocodegen"><td>11</td><td><pre style="display:inline;"> property FacingUp : boolean read GetFacingUp;</pre></td></tr>
<tr class="nocodegen"><td>12</td><td><pre style="display:inline;"> end;</pre></td></tr>
<tr class="nocodegen"><td>13</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>14</td><td><pre style="display:inline;"> TCard = class(TInterfacedObject, ICard)</pre></td></tr>
<tr class="nocodegen"><td>15</td><td><pre style="display:inline;"> private</pre></td></tr>
<tr class="nocodegen"><td>16</td><td><pre style="display:inline;"> FFacingUp : boolean;</pre></td></tr>
<tr class="nocodegen"><td>17</td><td><pre style="display:inline;"> public</pre></td></tr>
<tr class="nocodegen"><td>18</td><td><pre style="display:inline;"> constructor Create;</pre></td></tr>
<tr class="nocodegen"><td>19</td><td><pre style="display:inline;"> function GetFacingUp : boolean;</pre></td></tr>
<tr class="nocodegen"><td>20</td><td><pre style="display:inline;"> function Flip : boolean;</pre></td></tr>
<tr class="nocodegen"><td>21</td><td><pre style="display:inline;"> function TurnFaceDown : boolean;</pre></td></tr>
<tr class="nocodegen"><td>22</td><td><pre style="display:inline;"> end;</pre></td></tr>
<tr class="nocodegen"><td>23</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>24</td><td><pre style="display:inline;">implementation</pre></td></tr>
<tr class="nocodegen"><td>25</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>26</td><td><pre style="display:inline;">{ TCard }</pre></td></tr>
<tr class="nocodegen"><td>27</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>28</td><td><pre style="display:inline;">constructor TCard.Create;</pre></td></tr>
<tr class="covered"><td>29</td><td><pre style="display:inline;">begin</pre></td></tr>
<tr class="covered"><td>30</td><td><pre style="display:inline;"> inherited;</pre></td></tr>
<tr class="nocodegen"><td>31</td><td><pre style="display:inline;"> //By default the card is facing up.</pre></td></tr>
<tr class="covered"><td>32</td><td><pre style="display:inline;"> FFacingUp := True;</pre></td></tr>
<tr class="covered"><td>33</td><td><pre style="display:inline;">end;</pre></td></tr>
<tr class="nocodegen"><td>34</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>35</td><td><pre style="display:inline;">function TCard.Flip: boolean;</pre></td></tr>
<tr class="covered"><td>36</td><td><pre style="display:inline;">begin</pre></td></tr>
<tr class="nocodegen"><td>37</td><td><pre style="display:inline;"> //Change the card from facing the way it is to the facing the other way.</pre></td></tr>
<tr class="nocodegen"><td>38</td><td><pre style="display:inline;"> //A card can either be facing up, or down.</pre></td></tr>
<tr class="covered"><td>39</td><td><pre style="display:inline;"> FFacingUp := not FFacingUp;</pre></td></tr>
<tr class="nocodegen"><td>40</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>41</td><td><pre style="display:inline;"> //Return the current facing up status.</pre></td></tr>
<tr class="covered"><td>42</td><td><pre style="display:inline;"> result := FFacingUp;</pre></td></tr>
<tr class="covered"><td>43</td><td><pre style="display:inline;">end;</pre></td></tr>
<tr class="nocodegen"><td>44</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>45</td><td><pre style="display:inline;">function TCard.GetFacingUp: boolean;</pre></td></tr>
<tr class="covered"><td>46</td><td><pre style="display:inline;">begin</pre></td></tr>
<tr class="nocodegen"><td>47</td><td><pre style="display:inline;"> //Return whether the card is facing up or not.</pre></td></tr>
<tr class="covered"><td>48</td><td><pre style="display:inline;"> result := FFacingUp;</pre></td></tr>
<tr class="covered"><td>49</td><td><pre style="display:inline;">end;</pre></td></tr>
<tr class="nocodegen"><td>50</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>51</td><td><pre style="display:inline;">function TCard.TurnFaceDown: boolean;</pre></td></tr>
<tr class="notcovered"><td>52</td><td><pre style="display:inline;">begin</pre></td></tr>
<tr class="nocodegen"><td>53</td><td><pre style="display:inline;"> //Make the card face down.</pre></td></tr>
<tr class="notcovered"><td>54</td><td><pre style="display:inline;"> FFacingUp := false;</pre></td></tr>
<tr class="nocodegen"><td>55</td><td><pre style="display:inline;"> //Return the current facing up status.</pre></td></tr>
<tr class="notcovered"><td>56</td><td><pre style="display:inline;"> result := FFacingUp;</pre></td></tr>
<tr class="notcovered"><td>57</td><td><pre style="display:inline;">end;</pre></td></tr>
<tr class="nocodegen"><td>58</td><td><pre style="display:inline;"></pre></td></tr>
<tr class="nocodegen"><td>59</td><td><pre style="display:inline;">end.</pre></td></tr>
</table>
</body>
</html>
| VSoftTechnologies/DelphiCodeCoverageExample | CodeCoverage/Output/Core.Card(Core.Card.pas).html | HTML | apache-2.0 | 8,101 |
package com.tms.entities;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Evan on 2016/3/12.
*/
public class UserInfo implements Serializable {
private Integer id;
private String acctName;
private String userName;
private String fullName;
private String password;
private String status;
private String description;
private Integer gender;
private Date birthday;
private String email;
private String phone;
private String delState;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAcctName() {
return acctName;
}
public void setAcctName(String acctName) {
this.acctName = acctName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getDelState() {
return delState;
}
public void setDelState(String delState) {
this.delState = delState;
}
}
| EvilGreenArmy/tms | src/main/java/com/tms/entities/UserInfo.java | Java | apache-2.0 | 2,287 |
#!/usr/bin/env python3
"""
./e09asynctwostage.py http://camlistore.org 1 6
Found 10 urls
http://camlistore.org/ frequencies: [('camlistore', 13), ...]
...
First integer arg is depth, second is minimum word count.
"""
import re
from sys import argv
import asyncio
from e01extract import canonicalize
from e04twostage import print_popular_words
from e06asyncextract import extract_async
@asyncio.coroutine
def wordcount_async(data, word_length):
counts = {}
for match in re.finditer('\w{%d,100}' % word_length, data):
word = match.group(0).lower()
counts[word] = counts.get(word, 0) + 1
return counts
@asyncio.coroutine
def extract_count_async(url, word_length):
_, data, found_urls = yield from extract_async(url)
top_word = yield from wordcount_async(data, word_length)
return url, top_word, found_urls
@asyncio.coroutine
def twostage_async(to_fetch, seen_urls, word_length):
futures, results = [], []
for url in to_fetch:
if url in seen_urls: continue
seen_urls.add(url)
futures.append(extract_count_async(url, word_length))
for future in asyncio.as_completed(futures):
try:
results.append((yield from future))
except Exception:
continue
return results
@asyncio.coroutine
def crawl_async(start_url, max_depth, word_length):
seen_urls = set()
to_fetch = [canonicalize(start_url)]
results = []
for depth in range(max_depth + 1):
batch = yield from twostage_async(to_fetch, seen_urls, word_length)
to_fetch = []
for url, data, found_urls in batch:
results.append((url, data))
to_fetch.extend(found_urls)
return results
def main():
# Bridge the gap between sync and async
future = asyncio.Task(crawl_async(argv[1], int(argv[2]), int(argv[3])))
loop = asyncio.get_event_loop()
loop.run_until_complete(future)
loop.close()
result = future.result()
print_popular_words(result)
if __name__ == '__main__':
main()
| bslatkin/pycon2014 | e09asynctwostage.py | Python | apache-2.0 | 2,046 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//$CI = &get_instance();
class Checksum extends MY_Controller
{
public function __construct()
{
parent::__construct("Checksum");
}
public function createchecksum()
{
if (isset($_SESSION['token']) && isset($_POST['token'])) {
if ($_POST['token'] == $_SESSION['token']) {
unset($_SESSION['token']);
$_SESSION['token'] = generate_password();
$data = $_POST;
$key = hash_hmac("SHA1", implode("-", $data), HASH_KEY);
echo json_encode(array("status" => 1, "token" => $_SESSION['token'], "checksum" => $key));
} else
echo json_encode(array("status" => 0));
} else
echo json_encode(array("status" => 0));
}
}
| phongnguyenpro/furniture | application/controllers/Checksum.php | PHP | apache-2.0 | 883 |
// <copyright file="JsonConfigTests.cs" company="ClrCoder project">
// Copyright (c) ClrCoder project. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// </copyright>
namespace ClrCoder.Tests.Json
{
using System;
using System.IO;
using System.Threading.Tasks;
using ClrCoder.Json;
using FluentAssertions;
using NUnit.Framework;
/// <summary>
/// JsonConfig class tests.
/// </summary>
[TestFixture]
public class JsonConfigTests
{
/// <summary>
/// Config file load test.
/// </summary>
/// <returns>Async execution TPL task.</returns>
[Test]
public async Task LoadConfigTest()
{
string fileName = Path.Combine(AppContext.BaseDirectory, "test.cfg.json");
File.WriteAllText(fileName, "{\"test\":\"data\"}");
TestConfig testConfig =
await JsonDefaults.JsonConfigSerializerSource.Serializer.DeserializeFile<TestConfig>(fileName);
testConfig.Test.Should().Be("data");
}
private class TestConfig
{
public string Test { get; set; }
}
}
} | dmitriyse/ClrCoder | src/ClrCoder.Tests/Json/JsonConfigTests.cs | C# | apache-2.0 | 1,237 |
/**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the LDP4j Project:
* http://www.ldp4j.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2014-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.ldp4j.framework:ldp4j-application-api:0.2.2
* Bundle : ldp4j-application-api-0.2.2.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.ldp4j.application;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Verifications;
import mockit.integration.junit4.JMockit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.ldp4j.application.data.DataSet;
import org.ldp4j.application.data.Individual;
import org.ldp4j.application.data.Name;
import org.ldp4j.application.ext.ResourceHandler;
import org.ldp4j.application.ext.UnknownResourceException;
import org.ldp4j.application.session.ResourceSnapshot;
import org.ldp4j.application.session.WriteSession;
import org.ldp4j.application.spi.RuntimeDelegate;
import org.ldp4j.commons.testing.Utils;
import com.google.common.base.Throwables;
@RunWith(JMockit.class)
public class ApplicationContextTest {
@Rule
public TestName name=new TestName();
@Rule
public Timeout timeout=
Timeout.
builder().
withTimeout(5,TimeUnit.SECONDS).
withLookingForStuckThread(true).
build();
@Mocked
private RuntimeDelegate delegate;
@Mocked
private ResourceSnapshot resource;
@Mocked
private Name<?> resourceName;
private ApplicationContext createContext() {
ApplicationContext sut=ApplicationContext.getInstance();
Deencapsulation.setField(sut, "delegate",delegate);
return sut;
}
@Test
public void testGetInstance() throws Exception {
assertThat(createContext(),notNullValue());
}
@Test
public void verifyIsUtilityClass() throws ClassNotFoundException {
Class<?> innerClass = Thread.currentThread().getContextClassLoader().loadClass(ApplicationContext.class.getCanonicalName()+"$ApplicationEngineSingleton");
assertThat(Utils.isUtilityClass(innerClass),equalTo(true));
}
@Test
public void testToString() throws Exception {
ApplicationContext sut = createContext();
assertThat(
sut.toString(),
not(equalTo(Utils.defaultToString(sut))));
}
@Test
public void testCreateSession$happyPath(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
WriteSession session = createContext().createSession();
assertThat(session,notNullValue());
session.close();
new Verifications() {{
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testCreateSession$nullNativeSession() throws Exception {
new Expectations() {{
delegate.createSession();result=null;
}};
try {
createContext().createSession();
} catch (ApplicationContextException e) {
assertThat(e.getMessage(),notNullValue());
}
}
@Test
public void testCreateSession$offline(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.isOffline();result=true;
}};
try {
createContext().createSession();
fail("Should not create session when off-line");
} catch (ApplicationContextException e) {
assertThat(e.getMessage(),notNullValue());
}
}
@Test
public void testCreateSession$singleSessionPerThread(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
try {
sut.createSession();
fail("Should not allow creating multiple sessions per thread");
} catch(ApplicationContextException e) {
assertThat(e.getMessage(),notNullValue());
} finally {
session.close();
}
new Verifications() {{
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$active$find(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
nativeSession.find(ResourceSnapshot.class,resourceName,CustomResourceHandler.class);result=resource;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
assertThat(
session.find(ResourceSnapshot.class,this.resourceName,CustomResourceHandler.class),
sameInstance(this.resource));
session.close();
new Verifications() {{
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$active$find(@Mocked final WriteSession nativeSession, @Mocked final Individual<?,?> individual) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
nativeSession.resolve(ResourceSnapshot.class,individual);result=resource;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
assertThat(
session.resolve(ResourceSnapshot.class,individual),
sameInstance(this.resource));
session.close();
new Verifications() {{
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$active$modify(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.modify(resource);
session.close();
new Verifications() {{
nativeSession.modify(resource);maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$active$delete(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.delete(resource);
session.close();
new Verifications() {{
nativeSession.delete(resource);maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$active$saveChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
session.close();
verifySessionUsage(nativeSession);
}
@Test
public void testWriteSession$active$discardChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.discardChanges();
session.close();
new Verifications() {{
nativeSession.discardChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$find(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.find(ResourceSnapshot.class,this.resourceName,CustomResourceHandler.class);
fail("Session should not find resources after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.find(ResourceSnapshot.class,resourceName,CustomResourceHandler.class);maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$find(@Mocked final WriteSession nativeSession, @Mocked final Individual<?,?> individual) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.resolve(ResourceSnapshot.class,individual);
fail("Session should not resolve resources after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.resolve(ResourceSnapshot.class,individual);maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$modify(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.modify(resource);
fail("Session should not modify resources after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.modify(resource);maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$delete(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.delete(resource);
fail("Session should not delete resources after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.delete(resource);maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$saveChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.saveChanges();
fail("Session should not save changes after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.saveChanges();maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$closed$discardChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.close();
try {
session.discardChanges();
fail("Session should not discard changes after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
}
new Verifications() {{
nativeSession.discardChanges();maxTimes=0;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$completed$find(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.find(ResourceSnapshot.class,this.resourceName,CustomResourceHandler.class);
fail("Session should not find resources after being closed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
new Verifications() {{
nativeSession.find(ResourceSnapshot.class,resourceName,CustomResourceHandler.class);maxTimes=0;
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$completed$find(@Mocked final WriteSession nativeSession, @Mocked final Individual<?,?> individual) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.resolve(ResourceSnapshot.class,individual);
fail("Session should not resolve resources after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
new Verifications() {{
nativeSession.resolve(ResourceSnapshot.class,individual);maxTimes=0;
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$completed$modify(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.modify(resource);
fail("Session should not modify resources after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
new Verifications() {{
nativeSession.modify(resource);maxTimes=0;
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$completed$delete(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.delete(resource);
fail("Session should not delete resources after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
new Verifications() {{
nativeSession.delete(resource);maxTimes=0;
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
@Test
public void testWriteSession$completed$saveChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.saveChanges();
fail("Session should not save changes after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
verifySessionUsage(nativeSession);
}
@Test
public void testWriteSession$completed$discardChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.discardChanges();
fail("Session should not discard changes after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
new Verifications() {{
nativeSession.discardChanges();maxTimes=0;
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
private void verifySessionUsage(final WriteSession nativeSession) throws Exception {
new Verifications() {{
nativeSession.saveChanges();maxTimes=1;minTimes=1;
nativeSession.close();maxTimes=1;minTimes=1;
}};
}
public static class CustomResourceHandler implements ResourceHandler {
@Override
public DataSet get(ResourceSnapshot resource) throws UnknownResourceException {
return null;
}
}
}
| ldp4j/ldp4j | framework/application/api/src/test/java/org/ldp4j/application/ApplicationContextTest.java | Java | apache-2.0 | 17,332 |
<!doctype html>
<html>
<head>
<meta name="mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width">
<link href='http://fonts.googleapis.com/css?family=Audiowide' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>グリッドペイント</title>
<meta name="gwt:property" content="locale=ja">
<link type="text/css" rel="stylesheet" href="common.css">
<script type="text/javascript" src="/js/LZWEncoder.js"></script>
<script type="text/javascript" src="/js/NeuQuant.js"></script>
<script type="text/javascript" src="/js/GIFEncoder.js"></script>
<script type="text/javascript" language="javascript" src="gridpaint/gridpaint.nocache.js"></script>
</head>
<body>
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
<br/>
<a href="gridpaint_help.html">GridPaint Help - how to use/使い方</a>
</div>
</noscript>
</body>
</html>
| akjava/gwthtml5apps | war/jp/gridpaint.html | HTML | apache-2.0 | 1,246 |
/**
*
* Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.common.codegen.internal.java.view;
import com.speedment.common.codegen.Generator;
import com.speedment.common.codegen.Transform;
import com.speedment.common.codegen.internal.java.view.trait.*;
import static com.speedment.common.codegen.internal.util.NullUtil.requireNonNullElements;
import static com.speedment.common.codegen.internal.util.NullUtil.requireNonNulls;
import com.speedment.common.codegen.model.ClassOrInterface;
import static com.speedment.common.codegen.util.Formatting.*;
import java.util.Optional;
import static java.util.stream.Collectors.joining;
import java.util.stream.Stream;
/**
* An abstract base class used to share functionality between different view
* components such as {@link ClassView}, {@link EnumView} and
* {@link InterfaceView}.
*
* @param <M> the extending model type
* @author Emil Forslund
*/
abstract class ClassOrInterfaceView<M extends ClassOrInterface<M>> implements Transform<M, String>,
HasNameView<M>,
HasModifiersView<M>,
HasJavadocView<M>,
HasGenericsView<M>,
HasImplementsView<M>,
HasInitializersView<M>,
HasMethodsView<M>,
HasClassesView<M>,
HasAnnotationUsageView<M>,
HasFieldsView<M> {
protected static final String
CLASS_STRING = "class ",
INTERFACE_STRING = "interface ",
ENUM_STRING = "enum ",
IMPLEMENTS_STRING = "implements ",
EXTENDS_STRING = "extends ";
/**
* A hook that is executed just before the 'fields' part of the class code.
*
* @param gen the generator being used
* @param model the model that is generated
* @return code to be inserted before the fields
*/
protected String onBeforeFields(Generator gen, M model) {
return "";
}
@Override
public String fieldSeparator(M model) {
return nl();
}
@Override
public String fieldSuffix() {
return ";";
}
/**
* Returns the declaration type of this model. This can be either 'class',
* 'interface' or 'enum'.
*
* @return the declaration type
*/
protected abstract String renderDeclarationType();
/**
* Returns the supertype of this model. The supertype should include any
* declaration like 'implements' or 'extends'.
* <p>
* Example: <pre>"implements List"</pre>
*
* @param gen the generator to use
* @param model the model of the component
* @return the supertype part
*/
protected abstract String renderSupertype(Generator gen, M model);
/**
* Should render the constructors part of the code and return it.
*
* @param gen the generator to use
* @param model the model of the component
* @return generated constructors or an empty string if there shouldn't
* be any
*/
protected abstract String renderConstructors(Generator gen, M model);
@Override
public Optional<String> transform(Generator gen, M model) {
requireNonNulls(gen, model);
return Optional.of(renderJavadoc(gen, model) +
renderAnnotations(gen, model) +
renderModifiers(gen, model) +
renderDeclarationType() +
renderName(gen, model) +
renderGenerics(gen, model) +
(model.getGenerics().isEmpty() ? " " : "") +
renderSupertype(gen, model) +
renderInterfaces(gen, model) +
// Code
block(nl() + separate(
onBeforeFields(gen, model), // Enums have constants here.´
renderFields(gen, model),
renderConstructors(gen, model),
renderInitalizers(gen, model),
renderMethods(gen, model),
renderClasses(gen, model)
))
);
}
/**
* Converts the specified elements into strings using their
* <code>toString</code>-method and combines them with two new-line-characters.
* Empty strings will be discarded.
*
* @param strings the strings to combine
* @return the combined string
*/
private String separate(Object... strings) {
requireNonNullElements(strings);
return Stream.of(strings)
.map(Object::toString)
.filter(s -> s.length() > 0)
.collect(joining(dnl()));
}
} | Pyknic/CodeGen | src/main/java/com/speedment/common/codegen/internal/java/view/ClassOrInterfaceView.java | Java | apache-2.0 | 4,958 |
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join(conf.paths.src, '/**/*.spec.js'),
path.join(conf.paths.src, '/**/*.mock.js'),
])
.concat(pathSrcHtml);
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: true,
autoWatch: false,
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'appDdhh'
},
logLevel: 'WARN',
frameworks: ['phantomjs-shim', 'jasmine', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-angular-filesort',
'karma-phantomjs-shim',
'karma-coverage',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
reporters: ['progress'],
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
// This block is needed to execute Chrome on Travis
// If you ever plan to use Chrome and Travis, you can keep it
// If not, you can safely remove it
// https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076
if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) {
configuration.customLaunchers = {
'chrome-travis-ci': {
base: 'Chrome',
flags: ['--no-sandbox']
}
};
configuration.browsers = ['chrome-travis-ci'];
}
config.set(configuration);
};
| alvaromamani/appDDHH | karma.conf.js | JavaScript | apache-2.0 | 2,705 |
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "libbel.h"
#include "bel-ast.h"
#include "bel-node-stack.h"
static const int set_start = 1;
static const int set_first_final = 33;
static const int set_error = 0;
static const int set_en_arguments = 4;
static const int set_en_term = 1;
bel_ast* bel_parse_term(char* line) {
int cs;
char *p;
char *pe;
int top;
int *stack;
bel_ast_node* term;
bel_ast_node* current_nv;
bel_ast_node* arg;
bel_ast* ast;
bel_node_stack* term_stack;
char *function;
char *value;
int fi;
int vi;
// Copy line to stack; Append new line if needed.
int line_length = strlen(line);
int i;
char input[line_length + 2];
strcpy(input, line);
for (i = line_length - 1; (input[i] == '\n' || input[i] == '\r'); i--)
input[i] = '\0';
input[i + 1] = '\n';
input[i + 2] = '\0';
p = input;
pe = input + strlen(input);
top = 0;
stack = malloc(sizeof(int) * TERM_STACK_SIZE);
current_nv = NULL;
function = malloc(sizeof(char) * BEL_VALUE_CHAR_LEN);
value = malloc(sizeof(char) * BEL_VALUE_CHAR_LEN);
fi = 0;
vi = 0;
term_stack = stack_init(TERM_STACK_SIZE);
term = bel_new_ast_node_token(BEL_TOKEN_TERM);
ast = bel_new_ast();
ast->root = term;
stack_push(term_stack, term);
memset(function, '\0', BEL_VALUE_CHAR_LEN);
memset(value, '\0', BEL_VALUE_CHAR_LEN);
{
cs = set_start;
top = 0;
}
{
if ( p == pe )
goto _test_eof;
goto _resume;
_again:
switch ( cs ) {
case 1:
goto st1;
case 0:
goto st0;
case 2:
goto st2;
case 3:
goto st3;
case 33:
goto st33;
case 4:
goto st4;
case 5:
goto st5;
case 6:
goto st6;
case 7:
goto st7;
case 8:
goto st8;
case 9:
goto st9;
case 10:
goto st10;
case 11:
goto st11;
case 12:
goto st12;
case 13:
goto st13;
case 14:
goto st14;
case 15:
goto st15;
case 34:
goto st34;
case 16:
goto st16;
case 17:
goto st17;
case 18:
goto st18;
case 19:
goto st19;
case 35:
goto st35;
case 20:
goto st20;
case 21:
goto st21;
case 22:
goto st22;
case 23:
goto st23;
case 24:
goto st24;
case 25:
goto st25;
case 26:
goto st26;
case 27:
goto st27;
case 28:
goto st28;
case 36:
goto st36;
case 29:
goto st29;
case 30:
goto st30;
case 31:
goto st31;
case 32:
goto st32;
}
p+= 1;
if ( p == pe )
goto _test_eof;
_resume:
switch ( cs ) {
case 1:
goto st_case_1;
case 0:
goto st_case_0;
case 2:
goto st_case_2;
case 3:
goto st_case_3;
case 33:
goto st_case_33;
case 4:
goto st_case_4;
case 5:
goto st_case_5;
case 6:
goto st_case_6;
case 7:
goto st_case_7;
case 8:
goto st_case_8;
case 9:
goto st_case_9;
case 10:
goto st_case_10;
case 11:
goto st_case_11;
case 12:
goto st_case_12;
case 13:
goto st_case_13;
case 14:
goto st_case_14;
case 15:
goto st_case_15;
case 34:
goto st_case_34;
case 16:
goto st_case_16;
case 17:
goto st_case_17;
case 18:
goto st_case_18;
case 19:
goto st_case_19;
case 35:
goto st_case_35;
case 20:
goto st_case_20;
case 21:
goto st_case_21;
case 22:
goto st_case_22;
case 23:
goto st_case_23;
case 24:
goto st_case_24;
case 25:
goto st_case_25;
case 26:
goto st_case_26;
case 27:
goto st_case_27;
case 28:
goto st_case_28;
case 36:
goto st_case_36;
case 29:
goto st_case_29;
case 30:
goto st_case_30;
case 31:
goto st_case_31;
case 32:
goto st_case_32;
}
goto st_out;
st1:
p+= 1;
if ( p == pe )
goto _test_eof1;
st_case_1:
if ( ( (*( p ))
) == 95 )
{
goto ctr0;
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr0;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr0;
}
}
else
{
goto ctr0;
}
{
goto st0;
}
st_case_0:
st0:
cs = 0;
goto _out;
ctr0:
{fi = 0;
memset(function, '\0', BEL_VALUE_CHAR_LEN);
}
{function[fi++] = (( (*( p ))
));
}
goto st2;
ctr3:
{function[fi++] = (( (*( p ))
));
}
goto st2;
st2:
p+= 1;
if ( p == pe )
goto _test_eof2;
st_case_2:
switch ( ( (*( p ))
) ) {
case 40:
{
goto ctr2;
}
case 95:
{
goto ctr3;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr3;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr3;
}
}
else
{
goto ctr3;
}
{
goto st0;
}
ctr2:
{term = stack_peek(term_stack);
term->token->left = bel_new_ast_node_value(BEL_VALUE_FX, function);
term->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
}
{{stack[top] = 3;
top+= 1;
goto st4;}}
goto st3;
st3:
p+= 1;
if ( p == pe )
goto _test_eof3;
st_case_3:
if ( ( (*( p ))
) == 41 )
{
goto st33;
}
{
goto st0;
}
st33:
p+= 1;
if ( p == pe )
goto _test_eof33;
st_case_33:
{
goto st0;
}
st4:
p+= 1;
if ( p == pe )
goto _test_eof4;
st_case_4:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr5;
}
case 95:
{
goto ctr6;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr6;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr6;
}
}
else
{
goto ctr6;
}
{
goto st0;
}
ctr5:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
goto st5;
ctr7:
{value[vi++] = (( (*( p ))
));
}
goto st5;
st5:
p+= 1;
if ( p == pe )
goto _test_eof5;
st_case_5:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr8;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr7;
}
{
goto ctr7;
}
ctr8:
{value[vi++] = (( (*( p ))
));
}
goto st6;
st6:
p+= 1;
if ( p == pe )
goto _test_eof6;
st_case_6:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr10;
}
case 32:
{
goto ctr10;
}
case 41:
{
goto ctr11;
}
case 44:
{
goto ctr12;
}
}
{
goto st0;
}
ctr10:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st7;
st7:
p+= 1;
if ( p == pe )
goto _test_eof7;
st_case_7:
switch ( ( (*( p ))
) ) {
case 9:
{
goto st7;
}
case 32:
{
goto st7;
}
case 44:
{
goto st8;
}
}
{
goto st0;
}
ctr12:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st8;
st8:
p+= 1;
if ( p == pe )
goto _test_eof8;
st_case_8:
switch ( ( (*( p ))
) ) {
case 9:
{
goto st8;
}
case 32:
{
goto st8;
}
case 34:
{
goto ctr15;
}
case 95:
{
goto ctr16;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr16;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr16;
}
}
else
{
goto ctr16;
}
{
goto st0;
}
ctr15:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
goto st9;
ctr17:
{value[vi++] = (( (*( p ))
));
}
goto st9;
st9:
p+= 1;
if ( p == pe )
goto _test_eof9;
st_case_9:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr8;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr17;
}
{
goto ctr17;
}
ctr18:
{value[vi++] = (( (*( p ))
));
}
goto st10;
st10:
p+= 1;
if ( p == pe )
goto _test_eof10;
st_case_10:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr19;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr17;
}
{
goto ctr17;
}
ctr25:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
goto st11;
ctr19:
{value[vi++] = (( (*( p ))
));
}
goto st11;
st11:
p+= 1;
if ( p == pe )
goto _test_eof11;
st_case_11:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr20;
}
case 32:
{
goto ctr20;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr21;
}
case 44:
{
goto ctr22;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) < 42 )
{
if ( ( (*( p ))
) > 31 )
{
if ( 35 <= ( (*( p ))
) && ( (*( p ))
) <= 40 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 10 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
{
goto ctr17;
}
ctr23:
{value[vi++] = (( (*( p ))
));
}
goto st12;
ctr20:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st12;
ctr47:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{value[vi++] = (( (*( p ))
));
}
goto st12;
st12:
p+= 1;
if ( p == pe )
goto _test_eof12;
st_case_12:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr23;
}
case 32:
{
goto ctr23;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 44:
{
goto ctr24;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
{
goto ctr17;
}
ctr24:
{value[vi++] = (( (*( p ))
));
}
goto st13;
ctr22:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st13;
ctr49:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{value[vi++] = (( (*( p ))
));
}
goto st13;
st13:
p+= 1;
if ( p == pe )
goto _test_eof13;
st_case_13:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr24;
}
case 32:
{
goto ctr24;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr25;
}
case 91:
{
goto ctr17;
}
case 92:
{
goto ctr18;
}
case 95:
{
goto ctr26;
}
case 96:
{
goto ctr17;
}
}
if ( ( (*( p ))
) < 58 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 47 )
{
{
goto ctr26;
}
}
else
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr26;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr26;
}
}
else
{
goto ctr17;
}
}
else
{
goto ctr17;
}
{
goto ctr17;
}
ctr26:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
{fi = 0;
memset(function, '\0', BEL_VALUE_CHAR_LEN);
}
{function[fi++] = (( (*( p ))
));
}
goto st14;
ctr28:
{value[vi++] = (( (*( p ))
));
}
{function[fi++] = (( (*( p ))
));
}
goto st14;
st14:
p+= 1;
if ( p == pe )
goto _test_eof14;
st_case_14:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr20;
}
case 32:
{
goto ctr20;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 40:
{
goto ctr27;
}
case 41:
{
goto ctr21;
}
case 44:
{
goto ctr22;
}
case 58:
{
goto ctr29;
}
case 91:
{
goto ctr17;
}
case 92:
{
goto ctr18;
}
case 95:
{
goto ctr28;
}
case 96:
{
goto ctr17;
}
}
if ( ( (*( p ))
) < 48 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 39 )
{
if ( ( (*( p ))
) > 43 )
{
if ( 45 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 42 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 57 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr28;
}
}
else if ( ( (*( p ))
) >= 59 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr28;
}
}
else
{
goto ctr17;
}
}
else
{
goto ctr28;
}
{
goto ctr17;
}
ctr27:
{value[vi++] = (( (*( p ))
));
}
{bel_ast_node* term_top = stack_peek(term_stack);
// find ARG leaf
arg = term_top->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
// create new nested term
term = bel_new_ast_node_token(BEL_TOKEN_TERM);
term->token->left = bel_new_ast_node_value(BEL_VALUE_FX, function);
term->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// set head term, left: new nested term, right: next arg
arg->token->left = term;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// push new nested term onto stack
stack_push(term_stack, term);
}
{{stack[top] = 15;
top+= 1;
goto st4;}}
goto st15;
st15:
p+= 1;
if ( p == pe )
goto _test_eof15;
st_case_15:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr23;
}
case 32:
{
goto ctr23;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr30;
}
case 44:
{
goto ctr24;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) < 42 )
{
if ( ( (*( p ))
) > 31 )
{
if ( 35 <= ( (*( p ))
) && ( (*( p ))
) <= 40 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 10 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
{
goto ctr17;
}
ctr21:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st34;
ctr30:
{value[vi++] = (( (*( p ))
));
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st34;
ctr48:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{value[vi++] = (( (*( p ))
));
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st34;
st34:
p+= 1;
if ( p == pe )
goto _test_eof34;
st_case_34:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr8;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr17;
}
{
goto ctr17;
}
ctr29:
{term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, value);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, NULL);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
}
{value[vi++] = (( (*( p ))
));
}
goto st16;
st16:
p+= 1;
if ( p == pe )
goto _test_eof16;
st_case_16:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr25;
}
case 91:
{
goto ctr17;
}
case 92:
{
goto ctr18;
}
case 95:
{
goto ctr31;
}
case 96:
{
goto ctr17;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( ( (*( p ))
) < 48 )
{
if ( 35 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 57 )
{
{
goto ctr17;
}
}
else
{
goto ctr31;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( ( (*( p ))
) < 97 )
{
if ( 93 <= ( (*( p ))
) && ( (*( p ))
) <= 94 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 122 )
{
{
goto ctr17;
}
}
else
{
goto ctr31;
}
}
else
{
goto ctr31;
}
{
goto ctr17;
}
ctr31:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
goto st17;
ctr32:
{value[vi++] = (( (*( p ))
));
}
goto st17;
st17:
p+= 1;
if ( p == pe )
goto _test_eof17;
st_case_17:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr20;
}
case 32:
{
goto ctr20;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr21;
}
case 44:
{
goto ctr22;
}
case 91:
{
goto ctr17;
}
case 92:
{
goto ctr18;
}
case 95:
{
goto ctr32;
}
case 96:
{
goto ctr17;
}
}
if ( ( (*( p ))
) < 48 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 40 )
{
if ( ( (*( p ))
) > 43 )
{
if ( 45 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 42 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 57 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr32;
}
}
else
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr32;
}
}
else
{
goto ctr17;
}
}
else
{
goto ctr32;
}
{
goto ctr17;
}
ctr16:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
{fi = 0;
memset(function, '\0', BEL_VALUE_CHAR_LEN);
}
{function[fi++] = (( (*( p ))
));
}
goto st18;
ctr34:
{value[vi++] = (( (*( p ))
));
}
{function[fi++] = (( (*( p ))
));
}
goto st18;
st18:
p+= 1;
if ( p == pe )
goto _test_eof18;
st_case_18:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr10;
}
case 32:
{
goto ctr10;
}
case 40:
{
goto ctr33;
}
case 41:
{
goto ctr11;
}
case 44:
{
goto ctr12;
}
case 58:
{
goto ctr35;
}
case 95:
{
goto ctr34;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr34;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr34;
}
}
else
{
goto ctr34;
}
{
goto st0;
}
ctr33:
{bel_ast_node* term_top = stack_peek(term_stack);
// find ARG leaf
arg = term_top->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
// create new nested term
term = bel_new_ast_node_token(BEL_TOKEN_TERM);
term->token->left = bel_new_ast_node_value(BEL_VALUE_FX, function);
term->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// set head term, left: new nested term, right: next arg
arg->token->left = term;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// push new nested term onto stack
stack_push(term_stack, term);
}
{{stack[top] = 19;
top+= 1;
goto st4;}}
goto st19;
st19:
p+= 1;
if ( p == pe )
goto _test_eof19;
st_case_19:
switch ( ( (*( p ))
) ) {
case 9:
{
goto st7;
}
case 32:
{
goto st7;
}
case 41:
{
goto ctr36;
}
case 44:
{
goto st8;
}
}
{
goto st0;
}
ctr11:
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st35;
ctr36:
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st35;
st35:
p+= 1;
if ( p == pe )
goto _test_eof35;
st_case_35:
{
goto st0;
}
ctr35:
{term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, value);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, NULL);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
}
goto st20;
st20:
p+= 1;
if ( p == pe )
goto _test_eof20;
st_case_20:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr15;
}
case 95:
{
goto ctr37;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr37;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr37;
}
}
else
{
goto ctr37;
}
{
goto st0;
}
ctr37:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
goto st21;
ctr38:
{value[vi++] = (( (*( p ))
));
}
goto st21;
st21:
p+= 1;
if ( p == pe )
goto _test_eof21;
st_case_21:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr10;
}
case 32:
{
goto ctr10;
}
case 41:
{
goto ctr11;
}
case 44:
{
goto ctr12;
}
case 95:
{
goto ctr38;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr38;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr38;
}
}
else
{
goto ctr38;
}
{
goto st0;
}
ctr9:
{value[vi++] = (( (*( p ))
));
}
goto st22;
st22:
p+= 1;
if ( p == pe )
goto _test_eof22;
st_case_22:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr39;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr7;
}
{
goto ctr7;
}
ctr39:
{value[vi++] = (( (*( p ))
));
}
goto st23;
st23:
p+= 1;
if ( p == pe )
goto _test_eof23;
st_case_23:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr40;
}
case 32:
{
goto ctr40;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr41;
}
case 44:
{
goto ctr42;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) < 42 )
{
if ( ( (*( p ))
) > 31 )
{
if ( 35 <= ( (*( p ))
) && ( (*( p ))
) <= 40 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 10 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr7;
}
}
else
{
goto ctr7;
}
{
goto ctr7;
}
ctr43:
{value[vi++] = (( (*( p ))
));
}
goto st24;
ctr40:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st24;
st24:
p+= 1;
if ( p == pe )
goto _test_eof24;
st_case_24:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr43;
}
case 32:
{
goto ctr43;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr8;
}
case 44:
{
goto ctr44;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr7;
}
}
else
{
goto ctr7;
}
{
goto ctr7;
}
ctr44:
{value[vi++] = (( (*( p ))
));
}
goto st25;
ctr42:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
goto st25;
st25:
p+= 1;
if ( p == pe )
goto _test_eof25;
st_case_25:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr44;
}
case 32:
{
goto ctr44;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr45;
}
case 91:
{
goto ctr7;
}
case 92:
{
goto ctr9;
}
case 95:
{
goto ctr46;
}
case 96:
{
goto ctr7;
}
}
if ( ( (*( p ))
) < 58 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 47 )
{
{
goto ctr46;
}
}
else
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr46;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr46;
}
}
else
{
goto ctr7;
}
}
else
{
goto ctr7;
}
{
goto ctr7;
}
ctr45:
{value[vi++] = (( (*( p ))
));
}
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
goto st26;
st26:
p+= 1;
if ( p == pe )
goto _test_eof26;
st_case_26:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr47;
}
case 32:
{
goto ctr47;
}
case 33:
{
goto ctr17;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr48;
}
case 44:
{
goto ctr49;
}
case 92:
{
goto ctr18;
}
}
if ( ( (*( p ))
) < 42 )
{
if ( ( (*( p ))
) > 31 )
{
if ( 35 <= ( (*( p ))
) && ( (*( p ))
) <= 40 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 10 )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr17;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr17;
}
}
else
{
goto ctr17;
}
{
goto ctr17;
}
ctr51:
{value[vi++] = (( (*( p ))
));
}
{function[fi++] = (( (*( p ))
));
}
goto st27;
ctr46:
{value[vi++] = (( (*( p ))
));
}
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{fi = 0;
memset(function, '\0', BEL_VALUE_CHAR_LEN);
}
{function[fi++] = (( (*( p ))
));
}
goto st27;
st27:
p+= 1;
if ( p == pe )
goto _test_eof27;
st_case_27:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr40;
}
case 32:
{
goto ctr40;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr8;
}
case 40:
{
goto ctr50;
}
case 41:
{
goto ctr41;
}
case 44:
{
goto ctr42;
}
case 58:
{
goto ctr52;
}
case 91:
{
goto ctr7;
}
case 92:
{
goto ctr9;
}
case 95:
{
goto ctr51;
}
case 96:
{
goto ctr7;
}
}
if ( ( (*( p ))
) < 48 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 39 )
{
if ( ( (*( p ))
) > 43 )
{
if ( 45 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 42 )
{
goto ctr7;
}
}
else
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 57 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr51;
}
}
else if ( ( (*( p ))
) >= 59 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr51;
}
}
else
{
goto ctr7;
}
}
else
{
goto ctr51;
}
{
goto ctr7;
}
ctr50:
{value[vi++] = (( (*( p ))
));
}
{bel_ast_node* term_top = stack_peek(term_stack);
// find ARG leaf
arg = term_top->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
// create new nested term
term = bel_new_ast_node_token(BEL_TOKEN_TERM);
term->token->left = bel_new_ast_node_value(BEL_VALUE_FX, function);
term->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// set head term, left: new nested term, right: next arg
arg->token->left = term;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
// push new nested term onto stack
stack_push(term_stack, term);
}
{{stack[top] = 28;
top+= 1;
goto st4;}}
goto st28;
st28:
p+= 1;
if ( p == pe )
goto _test_eof28;
st_case_28:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr43;
}
case 32:
{
goto ctr43;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr53;
}
case 44:
{
goto ctr44;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) < 42 )
{
if ( ( (*( p ))
) > 31 )
{
if ( 35 <= ( (*( p ))
) && ( (*( p ))
) <= 40 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 10 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 43 )
{
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 45 )
{
goto ctr7;
}
}
else
{
goto ctr7;
}
{
goto ctr7;
}
ctr41:
{value[vi++] = (( (*( p ))
));
}
{if (!current_nv) {
term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, NULL);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
} else {
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, value);
}
current_nv = 0;
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st36;
ctr53:
{value[vi++] = (( (*( p ))
));
}
{stack_pop(term_stack);
{top -= 1;
cs = stack[top];
goto _again;}
}
goto st36;
st36:
p+= 1;
if ( p == pe )
goto _test_eof36;
st_case_36:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr8;
}
case 92:
{
goto ctr9;
}
}
if ( ( (*( p ))
) > 91 )
{
if ( 93 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 35 )
{
goto ctr7;
}
{
goto ctr7;
}
ctr52:
{value[vi++] = (( (*( p ))
));
}
{term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, value);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, NULL);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
}
goto st29;
st29:
p+= 1;
if ( p == pe )
goto _test_eof29;
st_case_29:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr45;
}
case 91:
{
goto ctr7;
}
case 92:
{
goto ctr9;
}
case 95:
{
goto ctr54;
}
case 96:
{
goto ctr7;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( ( (*( p ))
) < 48 )
{
if ( 35 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 57 )
{
{
goto ctr7;
}
}
else
{
goto ctr54;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( ( (*( p ))
) < 97 )
{
if ( 93 <= ( (*( p ))
) && ( (*( p ))
) <= 94 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 122 )
{
{
goto ctr7;
}
}
else
{
goto ctr54;
}
}
else
{
goto ctr54;
}
{
goto ctr7;
}
ctr55:
{value[vi++] = (( (*( p ))
));
}
goto st30;
ctr54:
{value[vi++] = (( (*( p ))
));
}
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
goto st30;
st30:
p+= 1;
if ( p == pe )
goto _test_eof30;
st_case_30:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr40;
}
case 32:
{
goto ctr40;
}
case 33:
{
goto ctr7;
}
case 34:
{
goto ctr8;
}
case 41:
{
goto ctr41;
}
case 44:
{
goto ctr42;
}
case 91:
{
goto ctr7;
}
case 92:
{
goto ctr9;
}
case 95:
{
goto ctr55;
}
case 96:
{
goto ctr7;
}
}
if ( ( (*( p ))
) < 48 )
{
if ( ( (*( p ))
) < 35 )
{
if ( 10 <= ( (*( p ))
) && ( (*( p ))
) <= 31 )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 40 )
{
if ( ( (*( p ))
) > 43 )
{
if ( 45 <= ( (*( p ))
) )
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 42 )
{
goto ctr7;
}
}
else
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 57 )
{
if ( ( (*( p ))
) < 93 )
{
if ( ( (*( p ))
) > 64 )
{
if ( ( (*( p ))
) <= 90 )
{
goto ctr55;
}
}
else
{
goto ctr7;
}
}
else if ( ( (*( p ))
) > 94 )
{
if ( ( (*( p ))
) > 122 )
{
{
goto ctr7;
}
}
else if ( ( (*( p ))
) >= 97 )
{
goto ctr55;
}
}
else
{
goto ctr7;
}
}
else
{
goto ctr55;
}
{
goto ctr7;
}
ctr6:
{vi = 0;
memset(value, '\0', BEL_VALUE_CHAR_LEN);
}
{value[vi++] = (( (*( p ))
));
}
{fi = 0;
memset(function, '\0', BEL_VALUE_CHAR_LEN);
}
{function[fi++] = (( (*( p ))
));
}
goto st31;
ctr56:
{value[vi++] = (( (*( p ))
));
}
{function[fi++] = (( (*( p ))
));
}
goto st31;
st31:
p+= 1;
if ( p == pe )
goto _test_eof31;
st_case_31:
switch ( ( (*( p ))
) ) {
case 9:
{
goto ctr10;
}
case 32:
{
goto ctr10;
}
case 40:
{
goto ctr33;
}
case 41:
{
goto ctr11;
}
case 44:
{
goto ctr12;
}
case 58:
{
goto ctr57;
}
case 95:
{
goto ctr56;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr56;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr56;
}
}
else
{
goto ctr56;
}
{
goto st0;
}
ctr57:
{term = stack_peek(term_stack);
// find ARG leaf
arg = term->token->right;
while(arg->token->right != NULL) {
arg = arg->token->right;
}
current_nv = bel_new_ast_node_token(BEL_TOKEN_NV);
current_nv->token->left = bel_new_ast_node_value(BEL_VALUE_PFX, value);
current_nv->token->right = bel_new_ast_node_value(BEL_VALUE_VAL, NULL);
arg->token->left = current_nv;
arg->token->right = bel_new_ast_node_token(BEL_TOKEN_ARG);
}
goto st32;
st32:
p+= 1;
if ( p == pe )
goto _test_eof32;
st_case_32:
switch ( ( (*( p ))
) ) {
case 34:
{
goto ctr5;
}
case 95:
{
goto ctr37;
}
}
if ( ( (*( p ))
) < 65 )
{
if ( 48 <= ( (*( p ))
) && ( (*( p ))
) <= 57 )
{
goto ctr37;
}
}
else if ( ( (*( p ))
) > 90 )
{
if ( 97 <= ( (*( p ))
) && ( (*( p ))
) <= 122 )
{
goto ctr37;
}
}
else
{
goto ctr37;
}
{
goto st0;
}
st_out:
_test_eof1: cs = 1;
goto _test_eof;
_test_eof2: cs = 2;
goto _test_eof;
_test_eof3: cs = 3;
goto _test_eof;
_test_eof33: cs = 33;
goto _test_eof;
_test_eof4: cs = 4;
goto _test_eof;
_test_eof5: cs = 5;
goto _test_eof;
_test_eof6: cs = 6;
goto _test_eof;
_test_eof7: cs = 7;
goto _test_eof;
_test_eof8: cs = 8;
goto _test_eof;
_test_eof9: cs = 9;
goto _test_eof;
_test_eof10: cs = 10;
goto _test_eof;
_test_eof11: cs = 11;
goto _test_eof;
_test_eof12: cs = 12;
goto _test_eof;
_test_eof13: cs = 13;
goto _test_eof;
_test_eof14: cs = 14;
goto _test_eof;
_test_eof15: cs = 15;
goto _test_eof;
_test_eof34: cs = 34;
goto _test_eof;
_test_eof16: cs = 16;
goto _test_eof;
_test_eof17: cs = 17;
goto _test_eof;
_test_eof18: cs = 18;
goto _test_eof;
_test_eof19: cs = 19;
goto _test_eof;
_test_eof35: cs = 35;
goto _test_eof;
_test_eof20: cs = 20;
goto _test_eof;
_test_eof21: cs = 21;
goto _test_eof;
_test_eof22: cs = 22;
goto _test_eof;
_test_eof23: cs = 23;
goto _test_eof;
_test_eof24: cs = 24;
goto _test_eof;
_test_eof25: cs = 25;
goto _test_eof;
_test_eof26: cs = 26;
goto _test_eof;
_test_eof27: cs = 27;
goto _test_eof;
_test_eof28: cs = 28;
goto _test_eof;
_test_eof36: cs = 36;
goto _test_eof;
_test_eof29: cs = 29;
goto _test_eof;
_test_eof30: cs = 30;
goto _test_eof;
_test_eof31: cs = 31;
goto _test_eof;
_test_eof32: cs = 32;
goto _test_eof;
_test_eof: {}
_out: {}
}
if (term_stack) {
stack_destroy(term_stack);
}
free(stack);
free(function);
free(value);
return ast;
};
// vim: ft=c sw=4 ts=4 sts=4 expandtab
| nbargnesi/libbel | src/bel-parse-term.c | C | apache-2.0 | 45,422 |
package start
import (
"fmt"
"io"
"os"
"github.com/golang/glog"
"github.com/spf13/cobra"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"github.com/openshift/origin/pkg/cmd/flagtypes"
configapi "github.com/openshift/origin/pkg/cmd/server/apis/config"
)
var controllersLong = templates.LongDesc(`
Start the master controllers
This command starts the controllers for the master. Running
%[1]s start master %[2]s
will start the controllers that manage the master state, including the scheduler. The controllers
will run in the foreground until you terminate the process.`)
// NewCommandStartMasterControllers starts only the controllers
func NewCommandStartMasterControllers(name, basename string, out, errout io.Writer) (*cobra.Command, *MasterOptions) {
options := &MasterOptions{Output: out}
options.DefaultsFromName(basename)
cmd := &cobra.Command{
Use: "controllers",
Short: "Launch master controllers",
Long: fmt.Sprintf(controllersLong, basename, name),
Run: func(c *cobra.Command, args []string) {
if err := options.Complete(); err != nil {
fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, err.Error()))
return
}
if len(options.ConfigFile) == 0 {
fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, "--config is required for this command"))
return
}
if err := options.Validate(args); err != nil {
fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, err.Error()))
return
}
startProfiler()
if err := options.StartMaster(); err != nil {
if kerrors.IsInvalid(err) {
if details := err.(*kerrors.StatusError).ErrStatus.Details; details != nil {
fmt.Fprintf(errout, "Invalid %s %s\n", details.Kind, details.Name)
for _, cause := range details.Causes {
fmt.Fprintf(errout, " %s: %s\n", cause.Field, cause.Message)
}
os.Exit(255)
}
}
glog.Fatal(err)
}
},
}
// start controllers on a non conflicting health port from the default master
listenArg := &ListenArg{
ListenAddr: flagtypes.Addr{
Value: "127.0.0.1:8444",
DefaultScheme: "https",
DefaultPort: 8444,
AllowPrefix: true,
}.Default(),
}
var lockServiceName string
options.MasterArgs = NewDefaultMasterArgs()
options.MasterArgs.StartControllers = true
options.MasterArgs.OverrideConfig = func(config *configapi.MasterConfig) error {
config.ServingInfo.BindAddress = listenArg.ListenAddr.URL.Host
if len(lockServiceName) > 0 {
config.ControllerConfig.Election = &configapi.ControllerElectionConfig{
LockName: lockServiceName,
LockNamespace: "kube-system",
LockResource: configapi.GroupResource{
Resource: "configmaps",
},
}
}
return nil
}
flags := cmd.Flags()
// This command only supports reading from config and the listen argument
flags.StringVar(&options.ConfigFile, "config", "", "Location of the master configuration file to run from. Required")
cmd.MarkFlagFilename("config", "yaml", "yml")
flags.StringVar(&lockServiceName, "lock-service-name", "", "Name of a service in the kube-system namespace to use as a lock, overrides config.")
BindListenArg(listenArg, flags, "")
return cmd, options
}
| sg00dwin/origin | pkg/cmd/server/start/start_controllers.go | GO | apache-2.0 | 3,267 |
/*
Copyright 2011-2014 Lukas Vlcek
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.
*/
/*
{
cluster: {
cluster_name: {
connectionVerified: bool,
intervals: {_all_active_intervals_},
timeouts: {_all_active_timeouts_},
storeSize: int,
health: {},
nodesStats: [
timestamp_x: {
[nodeStats, nodeStats, ...]
},
timestamp_y: {[...]},
timestamp_z: {[...]},
...
],
nodesState: [
{node_with_id},
{node_with_id},
...
],
nodeInfo: {}, //relevant to selected node
clusterState: [
clusterStateTimestamp: {},
...
],
indicesStatus: [
indicesStatusTimestamp: {},
...
]
}
}
}
*/
var Cluster = Backbone.Model.extend({
defaults: {
id: "not_set_yet",
connectionVerified: false,
health: undefined,
nodesStats: undefined,
nodesState: undefined,
nodeInfo: undefined,
clusterState: undefined,
indicesStatus: undefined,
storeSize: 60000, // 1min
intervals: {},
timeouts: {},
dispatcher: undefined
},
// id: "cluster_name"
// baseUrl: "complete URL for REST API including port number"
// refreshInterval: _some_number_ [optional, defaults to 2000ms]
// dispatcher: function [optional].
initialize: function(attrs){
var _model = this;
var _conn = _model.get("connectionVerified");
if (_conn == false) {
// ensure default dispatcher (in case user explicitly provided "undefined" value instead of function)
if (this.get("dispatcher") == undefined /*|| typeof this.get("dispatcher") != "function"*/) {
console.log("using default dispatcher");
var _dispatcher = _.clone(Backbone.Events);
_dispatcher.on("onAjaxResponse", function(clusterName, restApiName, response) {
console.log("["+clusterName+"] ["+restApiName+"]", response)
});
this.set({dispatcher: _dispatcher});
}
var connection = {
baseUrl: attrs.baseUrl,
refreshInterval: attrs.refreshInterval || 2000
};
var hello = new Hello({},connection);
hello.fetch({
success: function(model, response){
var version = hello.get("version");
if (version && version.number) {
version = version.number;
var _vArray = version.split(".");
if (_vArray.length > 2 && _model.checkVersion(_vArray)) {
_model.versionVerified(version);
_model.initCluster(connection);
} else {
_model.yellAboutVersion(version);
}
} else {
_model.yellAboutVersion("n/a");
}
},
error: function(model, response) {
console.log("[Error] something wrong happened...", model, response);
}
});
}
},
// When creating a new cluster, client has to provide both REST URL endpoint and cluster name.
// The idea is that the cluster name is obtained by client upfront using cluster health API for example.
validate: function(attrs){
// this must be constructor call
if (this.get("connectionVerified") == undefined) {
if (!attrs.id || !attrs.baseUrl) {
return "Both cluster name and URL must be provided.\n" +
"Example: { " +
"id: \"_cluster_name_\", " +
"baseUrl: \"_ES_REST_end_point_\" " +
"}";
}
if (attrs.dispatcher != undefined) {
if (typeof attrs.dispatcher != "function") {
return "dispatcher must be a function.";
}
}
}
},
// returns false or true depending on given version numbers
checkVersion: function(parsedArray) {
var major = parsedArray[0];
var minor = parsedArray[1];
var maintenance = parsedArray[2];
var build = undefined;
if (parsedArray.length > 3) {
build = parsedArray[3]; // Betax, RCx, GAx ...
}
return (major == 2 && minor >= 0 && maintenance >= 0 && (build != 'Beta1' || build != 'Beta2'));
},
versionVerified: function(version) {
console.log("Check ES node version: " + version + " [ok]");
},
yellAboutVersion: function(version) {
var message =
"*********************************\n" +
"Bigdesk may not work correctly!\n" +
"Found ES node version: " + version + "\n" +
"Requires ES node version: >= 1.0.0.RC1\n" +
"*********************************";
console.log(message);
if (alert) { alert(message); }
},
// connection.baseUrl
// connection.refreshInterval
initCluster: function(connection) {
var _model = this;
// connection has been already verified
_model.set({connectionVerified: true});
_model.set({ health: new ClusterHealth({}, connection) });
_model.set({ nodesStats: new NodesStats([], connection) });
_model.set({ nodesState: new NodesState([], connection) });
_model.set({ nodeInfo: new NodeInfo({}, connection) });
_model.set({ clusterState: new ClusterState([], connection) });
_model.set({ indicesStatus: new IndicesStatus([], connection) });
this.startFetch(connection.refreshInterval);
},
clearTimeouts: function() {
var _cluster = this;
var timeouts = _cluster.get("timeouts");
_.each(timeouts, function(num, key){
_cluster.clearTimeout(key);
});
},
clearTimeout: function(timeoutId) {
var timeouts = this.get("timeouts");
if (timeouts && timeouts[timeoutId]) {
window.clearTimeout(timeouts[timeoutId]);
delete timeouts[timeoutId];
this.set({timeouts: timeouts});
}
},
clearIntervals: function() {
var _cluster = this;
var intervals = this.get("intervals");
_.each(intervals, function(num, key){
_cluster.clearInterval(key);
});
},
clearInterval: function(intervalId) {
// console.log("stop interval " + intervalId);
var intervals = this.get("intervals");
if (intervals && intervals[intervalId]) {
window.clearInterval(intervals[intervalId]);
delete intervals[intervalId];
this.set({intervals: intervals});
}
},
startTimeout: function(timeoutId, functionCall, interval) {
var _model = this;
var timeouts = _model.get("timeouts");
if (timeouts) {
if (timeouts[timeoutId]) {
console.log("[WARN] clearing and replacing existing timeout");
_model.clearTimeout(timeoutId);
}
var timeoutFn = function() {
functionCall();
timeouts[timeoutId] = window.setTimeout(timeoutFn, interval);
_model.set({timeouts: timeouts});
};
timeoutFn();
}
},
startInterval: function(intervalId, functionCall, interval) {
var _model = this;
var intervals = this.get("intervals");
if (intervals) {
if (intervals[intervalId]) {
console.log("[WARN] clearing and replacing existing interval");
_model.clearInterval(intervalId);
}
intervals[intervalId] = window.setInterval(functionCall, interval);
this.set({intervals: intervals});
// fire callback right now
functionCall();
}
},
// start fetching bigdesk models and collections
// params:
// refreshInterval
// baseUrl [optional] can override baseUrl that was passed into Cluster constructor
startFetch: function(refreshInterval, baseUrl) {
var _cluster = this;
var _dispatcher = _cluster.get("dispatcher");
var _clusterName = _cluster.get("id");
if (baseUrl && typeof baseUrl == "string") {
_cluster.get("health").setBaseUrl(baseUrl);
_cluster.get("nodesStats").setBaseUrl(baseUrl);
_cluster.get("nodesState").setBaseUrl(baseUrl);
_cluster.get("nodeInfo").setBaseUrl(baseUrl);
_cluster.get("clusterState").setBaseUrl(baseUrl);
_cluster.get("indicesStatus").setBaseUrl(baseUrl);
}
var healthRefreshFunction = function(){
_cluster.get("health").fetch({
success: function(model, response){
_dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > Health", response);
}
});
};
var nodesStatsRefreshFunction = function(){
_cluster.get("nodesStats").fetch({
add: true,
storeSize: _cluster.get("storeSize"),
now: new Date().getTime(),
silent: true,
success: function(model, response){
_dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesStats", response);
}
});
};
var nodesStateRefreshFunction = function(){
_cluster.get("nodesState").fetch({
add: true,
silent: true,
success: function(model, response){
_dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesState", response);
}
});
};
var clusterStateRefreshFunction = function(){
_cluster.get("clusterState").fetch({
add: true,
storeSize: _cluster.get("storeSize"),
now: new Date().getTime(),
silent: true,
success: function(model, response){
_dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > State", response);
_dispatcher.trigger("newClusterState");
}
});
};
var indicesStatusRefreshFunction = function(){
_cluster.get("indicesStatus").fetch({
add: true,
storeSize: _cluster.get("storeSize"),
now: new Date().getTime(),
silent: true,
success: function(model, response){
_dispatcher.trigger("onAjaxResponse", _clusterName, "indices > Status", response);
_dispatcher.trigger("newIndicesStatus");
}
});
};
this.clearInterval("nodesStateInterval");
this.clearInterval("nodesStatsInterval");
this.clearInterval("healthInterval");
this.clearTimeout("clusterStateInterval");
this.clearTimeout("indicesStatusInterval");
this.startInterval("nodesStateInterval", nodesStateRefreshFunction, refreshInterval);
this.startInterval("nodesStatsInterval", nodesStatsRefreshFunction, refreshInterval);
this.startInterval("healthInterval", healthRefreshFunction, refreshInterval);
this.startTimeout("clusterStateInterval", clusterStateRefreshFunction, refreshInterval);
this.startTimeout("indicesStatusInterval", indicesStatusRefreshFunction, refreshInterval);
},
// set storeSize value of the cluster
setStoreSize: function(storeSize) {
var _cluster = this;
_cluster.set({storeSize: storeSize});
},
// return master node id if available, otherwise return empty string
getMasterNodeId: function() {
var _cluster = this;
return _cluster.get("nodesState").getMasterNodeId();
}
});
var ClusterCollection = Backbone.Collection.extend({
model: Cluster
});
var BigdeskStore = Backbone.Model.extend({
defaults: {
cluster: new ClusterCollection()
},
// Returns an instance of a Cluster model with given name (id)
// or <code>undefined</code> if no instance if found.
getCluster: function(clusterName) {
return this.get("cluster").get(clusterName);
},
// Add a new cluster into store. Parameter is an instance of a Cluster model.
// Throws error if there already is a cluster with the same id.
addCluster: function(clusterModel) {
var _c = this.get("cluster");
if (_c.get(clusterModel.get("id")) == undefined) {
_c.add(clusterModel)
} else {
throw "Cluster already exists.";
}
}
});
| nishantsaini/bigdesk | _site/js/store/BigdeskStore.js | JavaScript | apache-2.0 | 13,702 |
/*
* Copyright 2012-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.invoke.reflect;
import java.lang.reflect.Method;
import org.junit.Test;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OperationMethodParameter}.
*
* @author Phillip Webb
*/
public class OperationMethodParameterTests {
private Method method = ReflectionUtils.findMethod(getClass(), "example",
String.class, String.class);
@Test
public void getNameShouldReturnName() {
OperationMethodParameter parameter = new OperationMethodParameter("name",
this.method.getParameters()[0]);
assertThat(parameter.getName()).isEqualTo("name");
}
@Test
public void getTypeShouldReturnType() {
OperationMethodParameter parameter = new OperationMethodParameter("name",
this.method.getParameters()[0]);
assertThat(parameter.getType()).isEqualTo(String.class);
}
@Test
public void isMandatoryWhenNoAnnotationShouldReturnTrue() {
OperationMethodParameter parameter = new OperationMethodParameter("name",
this.method.getParameters()[0]);
assertThat(parameter.isMandatory()).isTrue();
}
@Test
public void isMandatoryWhenNullableAnnotationShouldReturnFalse() {
OperationMethodParameter parameter = new OperationMethodParameter("name",
this.method.getParameters()[1]);
assertThat(parameter.isMandatory()).isFalse();
}
void example(String one, @Nullable String two) {
}
}
| kdvolder/spring-boot | spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java | Java | apache-2.0 | 2,108 |
package org.leguan.usageindex;
import java.util.UUID;
public class UsageIndexMemoryItem {
public UUID id;
public String usage;
public String createdAt;
public String location;
public UsageIndexURL usageIndexUrl;
public String toString () {
return id.toString() + "-" + usage + "-" + createdAt + "-" + location;
}
}
| moley/leguan | leguan-base/src/main/java/org/leguan/usageindex/UsageIndexMemoryItem.java | Java | apache-2.0 | 343 |
package br.com.caelum.leilao.dominio;
public class CriadorLeilao {
private Leilao leilao;
public CriadorLeilao para(String objetoLeilao) {
this.leilao = new Leilao(objetoLeilao);
return this;
}
public CriadorLeilao propoe(Usuario jose, double valorLance) {
this.leilao.propoe(new Lance(jose, valorLance));
return this;
}
public Leilao constroi() {
return leilao;
}
}
| wesleyegberto/courses-projects | java/java-tests/tdd-java/src/test/java/br/com/caelum/leilao/dominio/CriadorLeilao.java | Java | apache-2.0 | 390 |
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Start Bootstrap - Landing Page Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
.lead {
font-size: 18px;
font-weight: 400;
}
.intro-header {
padding-top: 50px; /* If you're making other pages, make sure there is 50px of padding to make sure the navbar doesn't overlap content! */
padding-bottom: 50px;
text-align: center;
color: #f8f8f8;
background: url(../img/intro-bg.jpg) no-repeat center center;
background-size: cover;
}
.intro-message {
position: relative;
padding-top: 20%;
padding-bottom: 20%;
}
.intro-message > h1 {
margin: 0;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
font-size: 5em;
}
.intro-divider {
border-top: 1px solid #f8f8f8;
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
.intro-message > h3 {
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
}
@media (max-width: 767px) {
.intro-message {
padding-bottom: 15%;
}
.intro-message > h1 {
font-size: 3em;
}
ul.intro-social-buttons > li {
display: block;
margin-bottom: 20px;
padding: 0;
}
ul.intro-social-buttons > li:last-child {
margin-bottom: 0;
}
.intro-divider {
width: 100%;
}
}
.network-name {
text-transform: uppercase;
font-size: 14px;
font-weight: 400;
letter-spacing: 2px;
}
.content-section-a {
padding: 50px 0;
background-color: #f8f8f8;
}
.content-section-b {
padding: 50px 0;
border-top: 1px solid #e7e7e7;
border-bottom: 1px solid #e7e7e7;
}
.section-heading {
margin-bottom: 30px;
}
.section-heading-spacer {
float: left;
width: 200px;
border-top: 3px solid #e7e7e7;
}
.banner {
padding: 100px 0;
color: #f8f8f8;
background: url(../img/banner-bg.jpg) no-repeat center center;
background-size: cover;
}
.banner h2 {
margin: 0;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
font-size: 3em;
}
.banner ul {
margin-bottom: 0;
}
.banner-social-buttons {
float: right;
margin-top: 0;
}
@media (max-width: 1199px) {
ul.banner-social-buttons {
float: left;
margin-top: 15px;
}
}
@media (max-width: 767px) {
.banner h2 {
margin: 0;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
font-size: 3em;
}
ul.banner-social-buttons > li {
display: block;
margin-bottom: 20px;
padding: 0;
}
ul.banner-social-buttons > li:last-child {
margin-bottom: 0;
}
}
| johannnallathamby/product-is | modules/samples/identity-mgt/info-recovery-sample/src/main/webapp/assets/css/landing-page.css | CSS | apache-2.0 | 3,294 |
/*
USER: zobayer
TASK: MDIGITS
ALGO: recursion
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
int p10[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000};
void calc(int num, int p, int cnt[], int f)
{
int n, i;
n = num / p10[p];
for(i=0;i<n;i++)
cnt[i] += p10[p];
cnt[i] += num % p10[p] + 1;
if(f) cnt[0] -= p10[p];
if(p==0) return;
for(i=0;i<10;i++)
cnt[i] += n*p*p10[p-1];
if(f) cnt[0] -= (p10[p]-1)/9;
calc(num % p10[p], p-1, cnt, 0);
}
int main()
{
int p1, p2, i, a, b, c,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b)
if(a>b)
{
c = a;
a = b;
b = c;
}
a--;
int cnt1[10] = {1};
int cnt2[10] = {1};
if(a)
{
p1 = (int)floor(log10(a));
calc(a, p1, cnt1, 1);
}
p2 = (int)floor(log10(b));
calc(b, p2, cnt2, 1);
printf("%d",cnt2[0]-cnt1[0]);
// for(i=1; i<10; i++) printf(" %d",cnt2[i]-cnt1[i]);
printf("\n");
}
return 0;
}
| pandian4github/competitive-programming | spojnew/zeronum-mdig.cpp | C++ | apache-2.0 | 920 |
#include "AutonDriveStraight.h"
#include <math.h>
// Used be constructed with (300,0.05,1,0,0,0)
AutonDriveStraight::AutonDriveStraight()
: PIDCommand(0.06, 0, 0.1)
, speed(0)
, goal(0)
, threshold(0)
, confirmTime(0)
, dAngle(0)
{
Requires(CommandBase::chassis);
}
void AutonDriveStraight::SetGoal(double dist, double thresh, double ispeed, double timeout, double angle) {
goal = dist;
threshold = thresh;
speed = ispeed;
confirmTime = timeout;
dAngle = angle;
GetPIDController()->SetSetpoint(goal);
GetPIDController()->SetAbsoluteTolerance(threshold);
}
// Called just before this Command runs the first time
void AutonDriveStraight::Initialize() {
GetPIDController()->Disable();
GetPIDController()->SetSetpoint(goal);
GetPIDController()->SetAbsoluteTolerance(threshold);
CommandBase::chassis->ResetEncoders();
CommandBase::chassis->HoldAngle(dAngle);
GetPIDController()->Reset();
GetPIDController()->Enable();
timer.Reset();
timer.Start();
}
// Called repeatedly when this Command is scheduled to run
void AutonDriveStraight::Execute() {
}
// Make this return true when this Command no longer needs to run execute()
bool AutonDriveStraight::IsFinished(){
char message[64];
if(GetPIDController()->OnTarget()) {
snprintf(message, sizeof(message), "On target. Time: %g", timer.Get() );
SmartDashboard::PutString(GetName()+"Finish", message);
return true;
}
else if(confirmTime > 0 && timer.Get() > confirmTime) {
snprintf(message, sizeof(message), "Time's up. Distance: %g", timer.Get() );
SmartDashboard::PutString(GetName()+"Finish", message);
return true;
}
else {
return false;
}
}
double AutonDriveStraight::ReturnPIDInput(){
return CommandBase::chassis->GetDistance();
}
void AutonDriveStraight::UsePIDOutput(double output){
if(output > speed) output = speed;
if(output < -speed) output = -speed;
CommandBase::chassis->GyroDrive(-output, true);
}
// Called once after isFinished returns true
void AutonDriveStraight::End() {
GetPIDController()->Disable();
CommandBase::chassis->m_drive.TankDrive(float(0),float(0));
timer.Stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AutonDriveStraight::Interrupted() {
End();
}
| team3130/Kitbot-2015 | Kitbot/src/Commands/AutonDriveStraight.cpp | C++ | apache-2.0 | 2,253 |
#!/usr/bin/python
# Copyright 2014 IBM Corp
#
# 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 will create a set of metrics at the endpoint specified as the
# program parameter
#
#
import json
import random
import requests
import string
import sys
import time
MOLD = {"name": "name1",
"timestamp": '2014-12-01',
"value": 100
}
MOLD_DIMENSIONS = {"key1": None}
def setup_metrics(argv):
for a in range(100):
MOLD_DIMENSIONS['key1'] = (
''.join(random.sample(string.ascii_uppercase * 6, 6)))
MOLD_DIMENSIONS['key2'] = (
''.join(random.sample(string.ascii_uppercase * 6, 6)))
MOLD_DIMENSIONS['key_' + str(a)] = (
''.join(random.sample(string.ascii_uppercase * 6, 6)))
"""
import hashlib
key_str = json.dumps(MOLD_DIMENSIONS, sort_keys=True,
indent=None,
separators=(',', ':'))
key = hashlib.md5(key_str).hexdigest()
MOLD['dimensions_hash'] = key
"""
MOLD['dimensions'] = MOLD_DIMENSIONS
print('starting round %s' % a)
# Generate unique 100 metrics
for i in range(100):
MOLD['name'] = ''.join(random.sample(string.ascii_uppercase * 6,
6))
for j in range(10):
MOLD['value'] = round((i + 1) * j * random.random(), 2)
the_time = time.time()
# single messages
for k in range(10):
factor = round(random.random(), 2) * 100
MOLD['timestamp'] = the_time + k * 50000 * factor
MOLD['value'] = i * j * k * random.random()
res = requests.post(argv[1], data=json.dumps(MOLD))
if res.status_code != 201 and res.status_code != 204:
print(json.dumps(MOLD))
exit(0)
# multiple messages
for k in range(3):
msg = "["
factor = round(random.random(), 2) * 100
MOLD['timestamp'] = the_time + k * 50000 * factor
MOLD['value'] = i * j * k * random.random()
msg += json.dumps(MOLD)
for l in range(9):
factor = round(random.random(), 2) * 100
MOLD['timestamp'] = the_time + k * 50000 * factor
MOLD['value'] = i * j * k * random.random()
msg += ',' + json.dumps(MOLD)
msg += "]"
res = requests.post(argv[1], data=msg)
if res.status_code != 201 and res.status_code != 204:
print(json.dumps(MOLD))
exit(0)
del MOLD_DIMENSIONS['key_' + str(a)]
print('round finished %s' % a)
if __name__ == '__main__':
if len(sys.argv) == 2:
setup_metrics(sys.argv)
else:
print('Usage: setup_metrics endpoint. For example:')
print(' setup_metrics http://host:9000/data_2015')
| litong01/python-monasca | kiloeyes/tests/setup_metrics.py | Python | apache-2.0 | 3,665 |
// Copyright 2016 InnerFunction Ltd.
//
// 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 Julian Goacher on 07/12/2015.
// Copyright © 2015 InnerFunction. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface IFLogger : NSObject {
NSString *_tag;
}
- (id)initWithTag:(NSString *)tag;
- (void)debug:(NSString *)message, ...;
- (void)info:(NSString *)message, ...;
- (void)warn:(NSString *)message, ...;
- (void)error:(NSString *)message, ...;
+ (void)withTag:(NSString *)tag error:(NSString *)message, ...;
+ (void)withTag:(NSString *)tag warn:(NSString *)message, ...;
@end | innerfunction/SCFFLD-ios | SCFFLD/util.prev/IFLogger.h | C | apache-2.0 | 1,118 |
# AUTOGENERATED FILE
FROM balenalib/nanopc-t4-debian:jessie-build
ENV GO_VERSION 1.15.8
RUN mkdir -p /usr/local/go \
&& curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \
&& echo "0e31ea4bf53496b0f0809730520dee98c0ae5c530f3701a19df0ba0a327bf3d2 go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-arm64.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Jessie \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.8 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/golang/nanopc-t4/debian/jessie/1.15.8/build/Dockerfile | Dockerfile | apache-2.0 | 1,998 |
//
// TestIndexViewController.h
// SimpleApp
//
// Created by 邬勇鹏 on 2018/5/10.
// Copyright © 2018年 wuyp. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TestIndexViewController : UIViewController
@end
| CreazyShadow/SimpleDemo | SimpleApp/SimpleApp/自定义视图/滑动索引控件/TestIndexViewController.h | C | apache-2.0 | 230 |
nmeta.FlowsBackGridView = Backbone.View.extend({
initialize:function (options) {
// Specify columns that will be displayed in Backgrid:
var columns = [{
name: "timestamp",
label: "Timestamp",
editable: false,
// Extend UriCell to have timestamp custom link to flow_hash value:
cell: Backgrid.UriCell.extend({
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get('timestamp'), this.model);
this.$el.append($("<a>", {
href: "#flowDetails/" + this.model.get('flow_hash'),
title: 'click for flow details'
}).text(formattedValue));
this.delegateEvents();
return this;
}
}),
}, {
name: "src_location_logical",
label: "Src Location",
editable: false,
cell: "string"
}, {
name: "src",
label: "Src",
editable: false,
cell: "string"
}, {
name: "dst",
label: "Dst",
editable: false,
cell: "string"
}, {
name: "proto",
label: "Proto",
editable: false,
cell: "string"
}, {
name: "tp_src",
label: "TP Src",
editable: false,
cell: "string"
}, {
name: "tp_dst",
label: "TP Dst",
editable: false,
cell: "string"
}, {
name: "classification",
label: "Classification",
editable: false,
cell: "string"
}, {
name: "actions",
label: "Actions",
editable: false,
cell: "string"
}, {
name: "data_sent",
label: "Sent",
editable: false,
cell: "string"
}, {
name: "data_received",
label: "Received",
editable: false,
cell: "string"
}];
// Set up a Backgrid grid to use the pageable collection
this.pageableGrid = new Backgrid.Grid({
columns: columns,
collection: this.model
});
// Display a loading indication whenever the Collection is fetching.
this.model.on("request", function() {
this.$el.html("Loading...");
}, this);
this.model.on('reset', this.render, this);
this.model.on('change', this.render, this);
},
render:function () {
console.log('FlowsBackgridView render function');
// Start with empty el:
this.$el.empty();
// Render the grid:
this.$el.append(this.pageableGrid.render().el)
return this;
},
});
| mattjhayes/nmeta | nmeta/webUI/js/views/flows_backgrid_view.js | JavaScript | apache-2.0 | 2,980 |
# 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 json
import numbers
import shutil
from tempfile import mkdtemp
import mock
import operator
import time
import unittest
import socket
import os
import errno
import itertools
import random
import eventlet
from collections import defaultdict
from datetime import datetime
import six
from six.moves import urllib
from swift.common.storage_policy import StoragePolicy, ECStoragePolicy
from swift.common.swob import Request
from swift.container import reconciler
from swift.container.server import gen_resp_headers, ContainerController
from swift.common.direct_client import ClientException
from swift.common import swob
from swift.common.header_key_dict import HeaderKeyDict
from swift.common.utils import split_path, Timestamp, encode_timestamps, mkdirs
from test.debug_logger import debug_logger
from test.unit import FakeRing, fake_http_connect, patch_policies, \
DEFAULT_TEST_EC_TYPE, make_timestamp_iter
from test.unit.common.middleware import helpers
def timestamp_to_last_modified(timestamp):
return datetime.utcfromtimestamp(
float(Timestamp(timestamp))).strftime('%Y-%m-%dT%H:%M:%S.%f')
def container_resp_headers(**kwargs):
return HeaderKeyDict(gen_resp_headers(kwargs))
class FakeStoragePolicySwift(object):
def __init__(self):
self.storage_policy = defaultdict(helpers.FakeSwift)
self._mock_oldest_spi_map = {}
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
return getattr(self.storage_policy[None], name)
def __call__(self, env, start_response):
method = env['REQUEST_METHOD']
path = env['PATH_INFO']
_, acc, cont, obj = split_path(env['PATH_INFO'], 0, 4,
rest_with_last=True)
if not obj:
policy_index = None
else:
policy_index = self._mock_oldest_spi_map.get(cont, 0)
# allow backend policy override
if 'HTTP_X_BACKEND_STORAGE_POLICY_INDEX' in env:
policy_index = int(env['HTTP_X_BACKEND_STORAGE_POLICY_INDEX'])
try:
return self.storage_policy[policy_index].__call__(
env, start_response)
except KeyError:
pass
if method == 'PUT':
resp_class = swob.HTTPCreated
else:
resp_class = swob.HTTPNotFound
self.storage_policy[policy_index].register(
method, path, resp_class, {}, '')
return self.storage_policy[policy_index].__call__(
env, start_response)
class FakeInternalClient(reconciler.InternalClient):
def __init__(self, listings=None):
self.app = FakeStoragePolicySwift()
self.user_agent = 'fake-internal-client'
self.request_tries = 1
self.use_replication_network = True
self.parse(listings)
self.container_ring = FakeRing()
def parse(self, listings):
listings = listings or {}
self.accounts = defaultdict(lambda: defaultdict(list))
for item, timestamp in listings.items():
# XXX this interface is stupid
if isinstance(timestamp, tuple):
timestamp, content_type = timestamp
else:
timestamp, content_type = timestamp, 'application/x-put'
storage_policy_index, path = item
if six.PY2 and isinstance(path, six.text_type):
path = path.encode('utf-8')
account, container_name, obj_name = split_path(
path, 0, 3, rest_with_last=True)
self.accounts[account][container_name].append(
(obj_name, storage_policy_index, timestamp, content_type))
for account_name, containers in self.accounts.items():
for con in containers:
self.accounts[account_name][con].sort(key=lambda t: t[0])
for account, containers in self.accounts.items():
account_listing_data = []
account_path = '/v1/%s' % account
for container, objects in containers.items():
container_path = account_path + '/' + container
container_listing_data = []
for entry in objects:
(obj_name, storage_policy_index,
timestamp, content_type) = entry
if storage_policy_index is None and not obj_name:
# empty container
continue
obj_path = swob.str_to_wsgi(
container_path + '/' + obj_name)
ts = Timestamp(timestamp)
headers = {'X-Timestamp': ts.normal,
'X-Backend-Timestamp': ts.internal}
# register object response
self.app.storage_policy[storage_policy_index].register(
'GET', obj_path, swob.HTTPOk, headers)
self.app.storage_policy[storage_policy_index].register(
'DELETE', obj_path, swob.HTTPNoContent, {})
# container listing entry
last_modified = timestamp_to_last_modified(timestamp)
# some tests setup mock listings using floats, some use
# strings, so normalize here
if isinstance(timestamp, numbers.Number):
timestamp = '%f' % timestamp
if six.PY2:
obj_name = obj_name.decode('utf-8')
timestamp = timestamp.decode('utf-8')
obj_data = {
'bytes': 0,
# listing data is unicode
'name': obj_name,
'last_modified': last_modified,
'hash': timestamp,
'content_type': content_type,
}
container_listing_data.append(obj_data)
container_listing_data.sort(key=operator.itemgetter('name'))
# register container listing response
container_headers = {}
container_qry_string = helpers.normalize_query_string(
'?format=json&marker=&end_marker=&prefix=')
self.app.register('GET', container_path + container_qry_string,
swob.HTTPOk, container_headers,
json.dumps(container_listing_data))
if container_listing_data:
obj_name = container_listing_data[-1]['name']
# client should quote and encode marker
end_qry_string = helpers.normalize_query_string(
'?format=json&marker=%s&end_marker=&prefix=' % (
urllib.parse.quote(obj_name.encode('utf-8'))))
self.app.register('GET', container_path + end_qry_string,
swob.HTTPOk, container_headers,
json.dumps([]))
self.app.register('DELETE', container_path,
swob.HTTPConflict, {}, '')
# simple account listing entry
container_data = {'name': container}
account_listing_data.append(container_data)
# register account response
account_listing_data.sort(key=operator.itemgetter('name'))
account_headers = {}
account_qry_string = '?format=json&marker=&end_marker=&prefix='
self.app.register('GET', account_path + account_qry_string,
swob.HTTPOk, account_headers,
json.dumps(account_listing_data))
end_qry_string = '?format=json&marker=%s&end_marker=&prefix=' % (
urllib.parse.quote(account_listing_data[-1]['name']))
self.app.register('GET', account_path + end_qry_string,
swob.HTTPOk, account_headers,
json.dumps([]))
class TestReconcilerUtils(unittest.TestCase):
def setUp(self):
self.fake_ring = FakeRing()
reconciler.direct_get_container_policy_index.reset()
self.tempdir = mkdtemp()
def tearDown(self):
shutil.rmtree(self.tempdir, ignore_errors=True)
def test_parse_raw_obj(self):
got = reconciler.parse_raw_obj({
'name': "2:/AUTH_bob/con/obj",
'hash': Timestamp(2017551.49350).internal,
'last_modified': timestamp_to_last_modified(2017551.49352),
'content_type': 'application/x-delete',
})
self.assertEqual(got['q_policy_index'], 2)
self.assertEqual(got['account'], 'AUTH_bob')
self.assertEqual(got['container'], 'con')
self.assertEqual(got['obj'], 'obj')
self.assertEqual(got['q_ts'], 2017551.49350)
self.assertEqual(got['q_record'], 2017551.49352)
self.assertEqual(got['q_op'], 'DELETE')
got = reconciler.parse_raw_obj({
'name': "1:/AUTH_bob/con/obj",
'hash': Timestamp(1234.20190).internal,
'last_modified': timestamp_to_last_modified(1234.20192),
'content_type': 'application/x-put',
})
self.assertEqual(got['q_policy_index'], 1)
self.assertEqual(got['account'], 'AUTH_bob')
self.assertEqual(got['container'], 'con')
self.assertEqual(got['obj'], 'obj')
self.assertEqual(got['q_ts'], 1234.20190)
self.assertEqual(got['q_record'], 1234.20192)
self.assertEqual(got['q_op'], 'PUT')
# the 'hash' field in object listing has the raw 'created_at' value
# which could be a composite of timestamps
timestamp_str = encode_timestamps(Timestamp(1234.20190),
Timestamp(1245.20190),
Timestamp(1256.20190),
explicit=True)
got = reconciler.parse_raw_obj({
'name': "1:/AUTH_bob/con/obj",
'hash': timestamp_str,
'last_modified': timestamp_to_last_modified(1234.20192),
'content_type': 'application/x-put',
})
self.assertEqual(got['q_policy_index'], 1)
self.assertEqual(got['account'], 'AUTH_bob')
self.assertEqual(got['container'], 'con')
self.assertEqual(got['obj'], 'obj')
self.assertEqual(got['q_ts'], 1234.20190)
self.assertEqual(got['q_record'], 1234.20192)
self.assertEqual(got['q_op'], 'PUT')
# negative test
obj_info = {
'name': "1:/AUTH_bob/con/obj",
'hash': Timestamp(1234.20190).internal,
'last_modified': timestamp_to_last_modified(1234.20192),
}
self.assertRaises(ValueError, reconciler.parse_raw_obj, obj_info)
obj_info['content_type'] = 'foo'
self.assertRaises(ValueError, reconciler.parse_raw_obj, obj_info)
obj_info['content_type'] = 'appliation/x-post'
self.assertRaises(ValueError, reconciler.parse_raw_obj, obj_info)
self.assertRaises(ValueError, reconciler.parse_raw_obj,
{'name': 'bogus'})
self.assertRaises(ValueError, reconciler.parse_raw_obj,
{'name': '-1:/AUTH_test/container'})
self.assertRaises(ValueError, reconciler.parse_raw_obj,
{'name': 'asdf:/AUTH_test/c/obj'})
self.assertRaises(KeyError, reconciler.parse_raw_obj,
{'name': '0:/AUTH_test/c/obj',
'content_type': 'application/x-put'})
def test_get_container_policy_index(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=1,
),
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
]
for permutation in itertools.permutations((0, 1, 2)):
reconciler.direct_get_container_policy_index.reset()
resp_headers = [stub_resp_headers[i] for i in permutation]
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
test_values = [(info['x-storage-policy-index'],
info['x-backend-status-changed-at']) for
info in resp_headers]
self.assertEqual(oldest_spi, 0,
"oldest policy index wrong "
"for permutation %r" % test_values)
def test_get_container_policy_index_with_error(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
container_resp_headers(
status_change_at=next(ts),
storage_policy_index=2,
),
container_resp_headers(
status_changed_at=next(ts),
storage_policy_index=1,
),
# old timestamp, but 500 should be ignored...
ClientException(
'Container Server blew up',
http_status=500, http_reason='Server Error',
http_headers=container_resp_headers(
status_changed_at=Timestamp(0).internal,
storage_policy_index=0,
),
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 2)
def test_get_container_policy_index_with_socket_error(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=1,
),
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 1)
def test_get_container_policy_index_with_too_many_errors(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
ClientException(
'Container Server blew up',
http_status=500, http_reason='Server Error',
http_headers=container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=1,
),
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertIsNone(oldest_spi)
def test_get_container_policy_index_for_deleted(self):
mock_path = 'swift.container.reconciler.direct_head_container'
headers = container_resp_headers(
status_changed_at=Timestamp.now().internal,
storage_policy_index=1,
)
stub_resp_headers = [
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=headers,
),
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=headers,
),
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=headers,
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 1)
def test_get_container_policy_index_for_recently_deleted(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=container_resp_headers(
put_timestamp=next(ts),
delete_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=0,
),
),
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=container_resp_headers(
put_timestamp=next(ts),
delete_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=1,
),
),
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=container_resp_headers(
put_timestamp=next(ts),
delete_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=2,
),
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 2)
def test_get_container_policy_index_for_recently_recreated(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
# old put, no recreate
container_resp_headers(
delete_timestamp=0,
put_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=0,
),
# recently deleted
ClientException(
'Container Not Found',
http_status=404, http_reason='Not Found',
http_headers=container_resp_headers(
put_timestamp=next(ts),
delete_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=1,
),
),
# recently recreated
container_resp_headers(
delete_timestamp=next(ts),
put_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=2,
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 2)
def test_get_container_policy_index_for_recently_split_brain(self):
ts = itertools.count(int(time.time()))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
# oldest put
container_resp_headers(
delete_timestamp=0,
put_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=0,
),
# old recreate
container_resp_headers(
delete_timestamp=next(ts),
put_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=1,
),
# recently put
container_resp_headers(
delete_timestamp=0,
put_timestamp=next(ts),
status_changed_at=next(ts),
storage_policy_index=2,
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 1)
@patch_policies(
[StoragePolicy(0, 'zero', is_default=True),
StoragePolicy(1, 'one'),
StoragePolicy(2, 'two')])
def test_get_container_policy_index_for_recently_split_recreated(self):
# verify that get_container_policy_index reaches same conclusion as a
# container server that receives all requests in chronological order
ts_iter = make_timestamp_iter()
ts = [next(ts_iter) for _ in range(8)]
# make 3 container replicas
device_dirs = [os.path.join(self.tempdir, str(i)) for i in range(3)]
for device_dir in device_dirs:
mkdirs(os.path.join(device_dir, 'sda1'))
controllers = [ContainerController(
{'devices': devices,
'mount_check': 'false',
'replication_server': 'true'})
for devices in device_dirs]
# initial PUT goes to all 3 replicas
responses = []
for controller in controllers:
req = Request.blank('/sda1/p/a/c', method='PUT', headers={
'X-Timestamp': ts[0].internal,
'X-Backend-Storage-Policy-Index': 0,
})
responses.append(req.get_response(controller))
self.assertEqual([resp.status_int for resp in responses],
[201, 201, 201])
# DELETE to all 3 replicas
responses = []
for controller in controllers:
req = Request.blank('/sda1/p/a/c', method='DELETE', headers={
'X-Timestamp': ts[2].internal,
})
responses.append(req.get_response(controller))
self.assertEqual([resp.status_int for resp in responses],
[204, 204, 204])
# first recreate PUT, SPI=1, goes to replicas 0 and 1
responses = []
for controller in controllers[:2]:
req = Request.blank('/sda1/p/a/c', method='PUT', headers={
'X-Timestamp': ts[3].internal,
'X-Backend-Storage-Policy-Index': 1,
})
responses.append(req.get_response(controller))
# all ok, PUT follows DELETE
self.assertEqual([resp.status_int for resp in responses],
[201, 201])
# second recreate PUT, SPI=2, goes to replicas 0 and 2
responses = []
for controller in [controllers[0], controllers[2]]:
req = Request.blank('/sda1/p/a/c', method='PUT', headers={
'X-Timestamp': ts[5].internal,
'X-Backend-Storage-Policy-Index': 2,
})
responses.append(req.get_response(controller))
# note: 409 from replica 0 because PUT follows previous PUT
self.assertEqual([resp.status_int for resp in responses],
[409, 201])
# now do a HEAD on all replicas
responses = []
for controller in controllers:
req = Request.blank('/sda1/p/a/c', method='HEAD')
responses.append(req.get_response(controller))
self.assertEqual([resp.status_int for resp in responses],
[204, 204, 204])
resp_headers = [resp.headers for resp in responses]
# replica 0 should be authoritative because it received all requests
self.assertEqual(ts[3].internal, resp_headers[0]['X-Put-Timestamp'])
self.assertEqual('1',
resp_headers[0]['X-Backend-Storage-Policy-Index'])
self.assertEqual(ts[3].internal, resp_headers[1]['X-Put-Timestamp'])
self.assertEqual('1',
resp_headers[1]['X-Backend-Storage-Policy-Index'])
self.assertEqual(ts[5].internal, resp_headers[2]['X-Put-Timestamp'])
self.assertEqual('2',
resp_headers[2]['X-Backend-Storage-Policy-Index'])
# now feed the headers from each replica to
# direct_get_container_policy_index
mock_path = 'swift.container.reconciler.direct_head_container'
random.shuffle(resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
# expect the same outcome as the authoritative replica 0
self.assertEqual(oldest_spi, 1)
def test_get_container_policy_index_cache(self):
now = time.time()
ts = itertools.count(int(now))
mock_path = 'swift.container.reconciler.direct_head_container'
stub_resp_headers = [
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=1,
),
container_resp_headers(
status_changed_at=Timestamp(next(ts)).internal,
storage_policy_index=0,
),
]
random.shuffle(stub_resp_headers)
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
self.assertEqual(oldest_spi, 0)
# re-mock with errors
stub_resp_headers = [
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
]
with mock.patch('time.time', new=lambda: now):
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
# still cached
self.assertEqual(oldest_spi, 0)
# propel time forward
the_future = now + 31
with mock.patch('time.time', new=lambda: the_future):
with mock.patch(mock_path) as direct_head:
direct_head.side_effect = stub_resp_headers
oldest_spi = reconciler.direct_get_container_policy_index(
self.fake_ring, 'a', 'con')
# expired
self.assertIsNone(oldest_spi)
def test_direct_delete_container_entry(self):
mock_path = 'swift.common.direct_client.http_connect'
connect_args = []
def test_connect(ipaddr, port, device, partition, method, path,
headers=None, query_string=None):
connect_args.append({
'ipaddr': ipaddr, 'port': port, 'device': device,
'partition': partition, 'method': method, 'path': path,
'headers': headers, 'query_string': query_string})
x_timestamp = Timestamp.now()
headers = {'x-timestamp': x_timestamp.internal}
fake_hc = fake_http_connect(200, 200, 200, give_connect=test_connect)
with mock.patch(mock_path, fake_hc):
reconciler.direct_delete_container_entry(
self.fake_ring, 'a', 'c', 'o', headers=headers)
self.assertEqual(len(connect_args), 3)
for args in connect_args:
self.assertEqual(args['method'], 'DELETE')
self.assertEqual(args['path'], '/a/c/o')
self.assertEqual(args['headers'].get('x-timestamp'),
headers['x-timestamp'])
def test_direct_delete_container_entry_with_errors(self):
# setup mock direct_delete
mock_path = \
'swift.container.reconciler.direct_delete_container_object'
stub_resp = [
None,
socket.error(errno.ECONNREFUSED, os.strerror(errno.ECONNREFUSED)),
ClientException(
'Container Server blew up',
'10.0.0.12', 6201, 'sdj', 404, 'Not Found'
),
]
mock_direct_delete = mock.MagicMock()
mock_direct_delete.side_effect = stub_resp
with mock.patch(mock_path, mock_direct_delete), \
mock.patch('eventlet.greenpool.DEBUG', False):
rv = reconciler.direct_delete_container_entry(
self.fake_ring, 'a', 'c', 'o')
self.assertIsNone(rv)
self.assertEqual(len(mock_direct_delete.mock_calls), 3)
def test_add_to_reconciler_queue(self):
mock_path = 'swift.common.direct_client.http_connect'
connect_args = []
def test_connect(ipaddr, port, device, partition, method, path,
headers=None, query_string=None):
connect_args.append({
'ipaddr': ipaddr, 'port': port, 'device': device,
'partition': partition, 'method': method, 'path': path,
'headers': headers, 'query_string': query_string})
fake_hc = fake_http_connect(200, 200, 200, give_connect=test_connect)
with mock.patch(mock_path, fake_hc):
ret = reconciler.add_to_reconciler_queue(
self.fake_ring, 'a', 'c', 'o', 17, 5948918.63946, 'DELETE')
self.assertTrue(ret)
self.assertEqual(ret, str(int(5948918.63946 // 3600 * 3600)))
self.assertEqual(len(connect_args), 3)
required_headers = ('x-content-type', 'x-etag')
for args in connect_args:
self.assertEqual(args['headers']['X-Timestamp'], '5948918.63946')
self.assertEqual(args['path'],
'/.misplaced_objects/5947200/17:/a/c/o')
self.assertEqual(args['headers']['X-Content-Type'],
'application/x-delete')
for header in required_headers:
self.assertTrue(header in args['headers'],
'%r was missing request headers %r' % (
header, args['headers']))
def test_add_to_reconciler_queue_force(self):
mock_path = 'swift.common.direct_client.http_connect'
connect_args = []
def test_connect(ipaddr, port, device, partition, method, path,
headers=None, query_string=None):
connect_args.append({
'ipaddr': ipaddr, 'port': port, 'device': device,
'partition': partition, 'method': method, 'path': path,
'headers': headers, 'query_string': query_string})
fake_hc = fake_http_connect(200, 200, 200, give_connect=test_connect)
now = time.time()
with mock.patch(mock_path, fake_hc), \
mock.patch('swift.container.reconciler.time.time',
lambda: now):
ret = reconciler.add_to_reconciler_queue(
self.fake_ring, 'a', 'c', 'o', 17, 5948918.63946, 'PUT',
force=True)
self.assertTrue(ret)
self.assertEqual(ret, str(int(5948918.63946 // 3600 * 3600)))
self.assertEqual(len(connect_args), 3)
required_headers = ('x-size', 'x-content-type')
for args in connect_args:
self.assertEqual(args['headers']['X-Timestamp'],
Timestamp(now).internal)
self.assertEqual(args['headers']['X-Etag'], '5948918.63946')
self.assertEqual(args['path'],
'/.misplaced_objects/5947200/17:/a/c/o')
for header in required_headers:
self.assertTrue(header in args['headers'],
'%r was missing request headers %r' % (
header, args['headers']))
def test_add_to_reconciler_queue_fails(self):
mock_path = 'swift.common.direct_client.http_connect'
fake_connects = [fake_http_connect(200),
fake_http_connect(200, raise_timeout_exc=True),
fake_http_connect(507)]
def fake_hc(*a, **kw):
return fake_connects.pop()(*a, **kw)
with mock.patch(mock_path, fake_hc):
ret = reconciler.add_to_reconciler_queue(
self.fake_ring, 'a', 'c', 'o', 17, 5948918.63946, 'PUT')
self.assertFalse(ret)
def test_add_to_reconciler_queue_socket_error(self):
mock_path = 'swift.common.direct_client.http_connect'
exc = socket.error(errno.ECONNREFUSED,
os.strerror(errno.ECONNREFUSED))
fake_connects = [fake_http_connect(200),
fake_http_connect(200, raise_timeout_exc=True),
fake_http_connect(500, raise_exc=exc)]
def fake_hc(*a, **kw):
return fake_connects.pop()(*a, **kw)
with mock.patch(mock_path, fake_hc):
ret = reconciler.add_to_reconciler_queue(
self.fake_ring, 'a', 'c', 'o', 17, 5948918.63946, 'DELETE')
self.assertFalse(ret)
def listing_qs(marker):
return helpers.normalize_query_string(
"?format=json&marker=%s&end_marker=&prefix=" %
urllib.parse.quote(marker.encode('utf-8')))
@patch_policies(
[StoragePolicy(0, 'zero', is_default=True),
ECStoragePolicy(1, 'one', ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=6, ec_nparity=2), ],
fake_ring_args=[{}, {'replicas': 8}])
class TestReconciler(unittest.TestCase):
maxDiff = None
def setUp(self):
self.logger = debug_logger()
conf = {}
self.swift = FakeInternalClient()
self.reconciler = reconciler.ContainerReconciler(
conf, logger=self.logger, swift=self.swift)
self.start_interval = int(time.time() // 3600 * 3600)
self.current_container_path = '/v1/.misplaced_objects/%d' % (
self.start_interval) + listing_qs('')
def test_concurrency_config(self):
conf = {}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.concurrency, 1)
conf = {'concurrency': '10'}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.concurrency, 10)
conf = {'concurrency': 48}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.concurrency, 48)
conf = {'concurrency': 0}
self.assertRaises(ValueError, reconciler.ContainerReconciler,
conf, self.logger, self.swift)
conf = {'concurrency': '-1'}
self.assertRaises(ValueError, reconciler.ContainerReconciler,
conf, self.logger, self.swift)
def test_processes_config(self):
conf = {}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.process, 0)
self.assertEqual(r.processes, 0)
conf = {'processes': '1'}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.process, 0)
self.assertEqual(r.processes, 1)
conf = {'processes': 10, 'process': '9'}
r = reconciler.ContainerReconciler(conf, self.logger, self.swift)
self.assertEqual(r.process, 9)
self.assertEqual(r.processes, 10)
conf = {'processes': -1}
self.assertRaises(ValueError, reconciler.ContainerReconciler,
conf, self.logger, self.swift)
conf = {'process': -1}
self.assertRaises(ValueError, reconciler.ContainerReconciler,
conf, self.logger, self.swift)
conf = {'processes': 9, 'process': 9}
self.assertRaises(ValueError, reconciler.ContainerReconciler,
conf, self.logger, self.swift)
def test_init_internal_client_log_name(self):
def _do_test_init_ic_log_name(conf, exp_internal_client_log_name):
with mock.patch(
'swift.container.reconciler.InternalClient') \
as mock_ic:
reconciler.ContainerReconciler(conf)
mock_ic.assert_called_once_with(
'/etc/swift/container-reconciler.conf',
'Swift Container Reconciler', 3,
global_conf={'log_name': exp_internal_client_log_name},
use_replication_network=True)
_do_test_init_ic_log_name({}, 'container-reconciler-ic')
_do_test_init_ic_log_name({'log_name': 'my-container-reconciler'},
'my-container-reconciler-ic')
def _mock_listing(self, objects):
self.swift.parse(objects)
self.fake_swift = self.reconciler.swift.app
def _mock_oldest_spi(self, container_oldest_spi_map):
self.fake_swift._mock_oldest_spi_map = container_oldest_spi_map
def _run_once(self):
"""
Helper method to run the reconciler once with appropriate direct-client
mocks in place.
Returns the list of direct-deleted container entries in the format
[(acc1, con1, obj1), ...]
"""
def mock_oldest_spi(ring, account, container_name):
return self.fake_swift._mock_oldest_spi_map.get(container_name, 0)
items = {
'direct_get_container_policy_index': mock_oldest_spi,
'direct_delete_container_entry': mock.DEFAULT,
}
mock_time_iter = itertools.count(self.start_interval)
with mock.patch.multiple(reconciler, **items) as mocks:
self.mock_delete_container_entry = \
mocks['direct_delete_container_entry']
with mock.patch('time.time', lambda: next(mock_time_iter)):
self.reconciler.run_once()
return [c[1][1:4] for c in
mocks['direct_delete_container_entry'].mock_calls]
def test_no_concurrency(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o2"): 3724.23456,
(1, "/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o2"): 3724.23456,
})
order_recieved = []
def fake_reconcile_object(account, container, obj, q_policy_index,
q_ts, q_op, path, **kwargs):
order_recieved.append(obj)
return True
self.reconciler._reconcile_object = fake_reconcile_object
self.assertEqual(self.reconciler.concurrency, 1) # sanity
deleted_container_entries = self._run_once()
self.assertEqual(order_recieved, ['o1', 'o2'])
# process in order recieved
self.assertEqual(deleted_container_entries, [
('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1'),
('.misplaced_objects', '3600', '1:/AUTH_bob/c/o2'),
])
def test_concurrency(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o2"): 3724.23456,
(1, "/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o2"): 3724.23456,
})
order_recieved = []
def fake_reconcile_object(account, container, obj, q_policy_index,
q_ts, q_op, path, **kwargs):
order_recieved.append(obj)
if obj == 'o1':
# o1 takes longer than o2 for some reason
for i in range(10):
eventlet.sleep(0.0)
return True
self.reconciler._reconcile_object = fake_reconcile_object
self.reconciler.concurrency = 2
deleted_container_entries = self._run_once()
self.assertEqual(order_recieved, ['o1', 'o2'])
# ... and so we finish o2 first
self.assertEqual(deleted_container_entries, [
('.misplaced_objects', '3600', '1:/AUTH_bob/c/o2'),
('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1'),
])
def test_multi_process_should_process(self):
def mkqi(a, c, o):
"make queue item"
return {
'account': a,
'container': c,
'obj': o,
}
queue = [
mkqi('a', 'c', 'o1'),
mkqi('a', 'c', 'o2'),
mkqi('a', 'c', 'o3'),
mkqi('a', 'c', 'o4'),
]
def map_should_process(process, processes):
self.reconciler.process = process
self.reconciler.processes = processes
with mock.patch('swift.common.utils.HASH_PATH_SUFFIX',
b'endcap'), \
mock.patch('swift.common.utils.HASH_PATH_PREFIX', b''):
return [self.reconciler.should_process(q_item)
for q_item in queue]
def check_process(process, processes, expected):
should_process = map_should_process(process, processes)
try:
self.assertEqual(should_process, expected)
except AssertionError as e:
self.fail('unexpected items processed for %s/%s\n%s' % (
process, processes, e))
check_process(0, 0, [True] * 4)
check_process(0, 1, [True] * 4)
check_process(0, 2, [False, True, False, False])
check_process(1, 2, [True, False, True, True])
check_process(0, 4, [False, True, False, False])
check_process(1, 4, [True, False, False, False])
check_process(2, 4, [False] * 4) # lazy
check_process(3, 4, [False, False, True, True])
queue = [mkqi('a%s' % i, 'c%s' % i, 'o%s' % i) for i in range(1000)]
items_handled = [0] * 1000
for process in range(100):
should_process = map_should_process(process, 100)
for i, handled in enumerate(should_process):
if handled:
items_handled[i] += 1
self.assertEqual([1] * 1000, items_handled)
def test_invalid_queue_name(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/bogus"): 3618.84187,
})
deleted_container_entries = self._run_once()
# we try to find something useful
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('bogus'))])
# but only get the bogus record
self.assertEqual(self.reconciler.stats['invalid_record'], 1)
# and just leave it on the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertFalse(deleted_container_entries)
def test_invalid_queue_name_marches_onward(self):
# there's something useful there on the queue
self._mock_listing({
(None, "/.misplaced_objects/3600/00000bogus"): 3600.0000,
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o1"): 3618.84187,
})
self._mock_oldest_spi({'c': 1}) # already in the right spot!
deleted_container_entries = self._run_once()
# we get all the queue entries we can
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# and one is garbage
self.assertEqual(self.reconciler.stats['invalid_record'], 1)
# but the other is workable
self.assertEqual(self.reconciler.stats['noop_object'], 1)
# so pop the queue for that one
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_queue_name_with_policy_index_delimiter_in_name(self):
q_path = '.misplaced_objects/3600'
obj_path = "AUTH_bob/c:sneaky/o1:sneaky"
# there's something useful there on the queue
self._mock_listing({
(None, "/%s/1:/%s" % (q_path, obj_path)): 3618.84187,
(1, '/%s' % obj_path): 3618.84187,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# we find the misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/%s' % obj_path))])
# move it
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/%s' % obj_path),
('DELETE', '/v1/%s' % obj_path)])
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/%s' % obj_path),
('PUT', '/v1/%s' % obj_path)])
# clean up the source
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# we DELETE the object from the wrong place with source_ts + offset 1
# timestamp to make sure the change takes effect
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=1).internal)
# and pop the queue for that one
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries, [(
'.misplaced_objects', '3600', '1:/%s' % obj_path)])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_unable_to_direct_get_oldest_storage_policy(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
})
# the reconciler gets "None" if we can't quorum the container
self._mock_oldest_spi({'c': None})
deleted_container_entries = self._run_once()
# we look for misplaced objects
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# but can't really say where to go looking
self.assertEqual(self.reconciler.stats['unavailable_container'], 1)
# we don't clean up anything
self.assertEqual(self.reconciler.stats['cleanup_object'], 0)
# and we definitely should not pop_queue
self.assertFalse(deleted_container_entries)
self.assertEqual(self.reconciler.stats['retry'], 1)
@patch_policies(
[StoragePolicy(0, 'zero', is_default=True),
StoragePolicy(1, 'one'),
ECStoragePolicy(2, 'two', ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=6, ec_nparity=2)],
fake_ring_args=[
{'next_part_power': 1}, {}, {'next_part_power': 1}])
def test_can_reconcile_policy(self):
for policy_index, expected in ((0, False), (1, True), (2, False),
(3, False), ('apple', False),
(None, False)):
self.assertEqual(
self.reconciler.can_reconcile_policy(policy_index), expected)
@patch_policies(
[StoragePolicy(0, 'zero', is_default=True),
ECStoragePolicy(1, 'one', ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=6, ec_nparity=2), ],
fake_ring_args=[{'next_part_power': 1}, {}])
def test_fail_to_move_if_ppi(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o1"): 3618.84187,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# skipped sending because policy_index 0 is in the middle of a PPI
self.assertFalse(deleted_container_entries)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
self.assertEqual(self.reconciler.stats['ppi_skip'], 1)
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_object_move(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o1"): 3618.84187,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# moves it
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1'),
('DELETE', '/v1/AUTH_bob/c/o1')])
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'),
('PUT', '/v1/AUTH_bob/c/o1')])
put_headers = self.fake_swift.storage_policy[0].headers[1]
# we PUT the object in the right place with q_ts + offset 2
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=2))
# cleans up the old
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# we DELETE the object from the wrong place with source_ts + offset 1
# timestamp to make sure the change takes effect
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=1))
# and when we're done, we pop the entry from the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_the_other_direction(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/0:/AUTH_bob/c/o1"): 3618.84187,
(0, "/AUTH_bob/c/o1"): 3618.84187,
})
self._mock_oldest_spi({'c': 1})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('0:/AUTH_bob/c/o1'))])
# moves it
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('GET', '/v1/AUTH_bob/c/o1'), # 2
('DELETE', '/v1/AUTH_bob/c/o1')]) # 4
delete_headers = self.fake_swift.storage_policy[0].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
put_headers = self.fake_swift.storage_policy[1].headers[1]
# we PUT the object in the right place with q_ts + offset 2
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=2).internal)
# cleans up the old
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# we DELETE the object from the wrong place with source_ts + offset 1
# timestamp to make sure the change takes effect
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=1).internal)
# and when we're done, we pop the entry from the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '0:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_with_unicode_and_spaces(self):
# the "name" in listings and the unicode string passed to all
# functions where we call them with (account, container, obj)
obj_name = u"AUTH_bob/c \u062a/o1 \u062a"
# anytime we talk about a call made to swift for a path
if six.PY2:
obj_path = obj_name.encode('utf-8')
else:
obj_path = obj_name.encode('utf-8').decode('latin-1')
# this mock expects unquoted unicode because it handles container
# listings as well as paths
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/%s" % obj_name): 3618.84187,
(1, "/%s" % obj_name): 3618.84187,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
# listing_qs encodes and quotes - so give it name
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/%s' % obj_name))])
# moves it
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
# these calls are to the real path
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/%s' % obj_path), # 2
('DELETE', '/v1/%s' % obj_path)]) # 4
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/%s' % obj_path), # 1
('PUT', '/v1/%s' % obj_path)]) # 3
put_headers = self.fake_swift.storage_policy[0].headers[1]
# we PUT the object in the right place with q_ts + offset 2
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=2).internal)
# cleans up the old
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# we DELETE the object from the wrong place with source_ts + offset 1
# timestamp to make sure the change takes effect
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3618.84187, offset=1).internal)
self.assertEqual(
delete_headers.get('X-Backend-Storage-Policy-Index'), '1')
# and when we're done, we pop the entry from the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
# this mock received the name, it's encoded down in buffered_http
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/%s' % obj_name)])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_delete(self):
q_ts = time.time()
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): (
Timestamp(q_ts).internal, 'application/x-delete'),
# object exists in "correct" storage policy - slightly older
(0, "/AUTH_bob/c/o1"): Timestamp(q_ts - 1).internal,
})
self._mock_oldest_spi({'c': 0})
# the tombstone exists in the enqueued storage policy
self.fake_swift.storage_policy[1].register(
'GET', '/v1/AUTH_bob/c/o1', swob.HTTPNotFound,
{'X-Backend-Timestamp': Timestamp(q_ts).internal})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# delete it
self.assertEqual(self.reconciler.stats['delete_attempt'], 1)
self.assertEqual(self.reconciler.stats['delete_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1'),
('DELETE', '/v1/AUTH_bob/c/o1')])
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'),
('DELETE', '/v1/AUTH_bob/c/o1')])
reconcile_headers = self.fake_swift.storage_policy[0].headers[1]
# we DELETE the object in the right place with q_ts + offset 2
self.assertEqual(reconcile_headers.get('X-Timestamp'),
Timestamp(q_ts, offset=2).internal)
# cleans up the old
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# we DELETE the object from the wrong place with source_ts + offset 1
# timestamp to make sure the change takes effect
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(q_ts, offset=1))
# and when we're done, we pop the entry from the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_enqueued_for_the_correct_dest_noop(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3618.84187,
(1, "/AUTH_bob/c/o1"): 3618.84187,
})
self._mock_oldest_spi({'c': 1}) # already in the right spot!
deleted_container_entries = self._run_once()
# nothing to see here
self.assertEqual(self.reconciler.stats['noop_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# so we just pop the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_src_object_newer_than_queue_entry(self):
# setup the cluster
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3600.123456,
(1, '/AUTH_bob/c/o1'): 3600.234567, # slightly newer
})
self._mock_oldest_spi({'c': 0}) # destination
# turn the crank
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# proceed with the move
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1'), # 2
('DELETE', '/v1/AUTH_bob/c/o1')]) # 4
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
# .. with source timestamp + offset 2
put_headers = self.fake_swift.storage_policy[0].headers[1]
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(3600.234567, offset=2))
# src object is cleaned up
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# ... with q_ts + offset 1
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3600.123456, offset=1))
# and queue is popped
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_src_object_older_than_queue_entry(self):
# should be some sort of retry case
q_ts = time.time()
container = str(int(q_ts // 3600 * 3600))
q_path = '.misplaced_objects/%s' % container
self._mock_listing({
(None, "/%s/1:/AUTH_bob/c/o1" % q_path): q_ts,
(1, '/AUTH_bob/c/o1'): q_ts - 1, # slightly older
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', '/v1/%s' % q_path + listing_qs('')),
('GET', '/v1/%s' % q_path +
listing_qs('1:/AUTH_bob/c/o1')),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# but no object copy is attempted
self.assertEqual(self.reconciler.stats['unavailable_source'], 1)
self.assertEqual(self.reconciler.stats['copy_attempt'], 0)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')])
# src object is un-modified
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
# queue is un-changed, we'll have to retry
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_src_object_unavailable_with_slightly_newer_tombstone(self):
# should be some sort of retry case
q_ts = float(Timestamp.now())
container = str(int(q_ts // 3600 * 3600))
q_path = '.misplaced_objects/%s' % container
self._mock_listing({
(None, "/%s/1:/AUTH_bob/c/o1" % q_path): q_ts,
})
self._mock_oldest_spi({'c': 0})
self.fake_swift.storage_policy[1].register(
'GET', '/v1/AUTH_bob/c/o1', swob.HTTPNotFound,
{'X-Backend-Timestamp': Timestamp(q_ts, offset=2).internal})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', '/v1/%s' % q_path + listing_qs('')),
('GET', '/v1/%s' % q_path +
listing_qs('1:/AUTH_bob/c/o1')),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# but no object copy is attempted
self.assertEqual(self.reconciler.stats['unavailable_source'], 1)
self.assertEqual(self.reconciler.stats['copy_attempt'], 0)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')])
# src object is un-modified
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
# queue is un-changed, we'll have to retry
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_src_object_unavailable_server_error(self):
# should be some sort of retry case
q_ts = float(Timestamp.now())
container = str(int(q_ts // 3600 * 3600))
q_path = '.misplaced_objects/%s' % container
self._mock_listing({
(None, "/%s/1:/AUTH_bob/c/o1" % q_path): q_ts,
})
self._mock_oldest_spi({'c': 0})
self.fake_swift.storage_policy[1].register(
'GET', '/v1/AUTH_bob/c/o1', swob.HTTPServiceUnavailable, {})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', '/v1/%s' % q_path + listing_qs('')),
('GET', '/v1/%s' % q_path +
listing_qs('1:/AUTH_bob/c/o1')),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# but no object copy is attempted
self.assertEqual(self.reconciler.stats['unavailable_source'], 1)
self.assertEqual(self.reconciler.stats['copy_attempt'], 0)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')])
# src object is un-modified
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
# queue is un-changed, we'll have to retry
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_object_move_fails_preflight(self):
# setup the cluster
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3600.123456,
(1, '/AUTH_bob/c/o1'): 3600.123457, # slightly newer
})
self._mock_oldest_spi({'c': 0}) # destination
# make the HEAD blow up
self.fake_swift.storage_policy[0].register(
'HEAD', '/v1/AUTH_bob/c/o1', swob.HTTPServiceUnavailable, {})
# turn the crank
deleted_container_entries = self._run_once()
# we did some listings...
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# ...but we can't even tell whether anything's misplaced or not
self.assertEqual(self.reconciler.stats['misplaced_object'], 0)
self.assertEqual(self.reconciler.stats['unavailable_destination'], 1)
# so we don't try to do any sort of move or cleanup
self.assertEqual(self.reconciler.stats['copy_attempt'], 0)
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
# and we'll have to try again later
self.assertEqual(self.reconciler.stats['retry'], 1)
self.assertEqual(self.fake_swift.storage_policy[1].calls, [])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
def test_object_move_fails_cleanup(self):
# setup the cluster
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3600.123456,
(1, '/AUTH_bob/c/o1'): 3600.123457, # slightly newer
})
self._mock_oldest_spi({'c': 0}) # destination
# make the DELETE blow up
self.fake_swift.storage_policy[1].register(
'DELETE', '/v1/AUTH_bob/c/o1', swob.HTTPServiceUnavailable, {})
# turn the crank
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# proceed with the move
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1'), # 2
('DELETE', '/v1/AUTH_bob/c/o1')]) # 4
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
# .. with source timestamp + offset 2
put_headers = self.fake_swift.storage_policy[0].headers[1]
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(3600.123457, offset=2))
# we try to cleanup
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
# ... with q_ts + offset 1
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3600.12346, offset=1))
# but cleanup fails!
self.assertEqual(self.reconciler.stats['cleanup_failed'], 1)
# so the queue is not popped
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
# and we'll have to retry
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_object_move_src_object_is_forever_gone(self):
# oh boy, hate to be here - this is an oldy
q_ts = self.start_interval - self.reconciler.reclaim_age - 1
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): q_ts,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# but it's gone :\
self.assertEqual(self.reconciler.stats['lost_source'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')])
# gah, look, even if it was out there somewhere - we've been at this
# two weeks and haven't found it. We can't just keep looking forever,
# so... we're done
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
# dunno if this is helpful, but FWIW we don't throw tombstones?
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
self.assertEqual(self.reconciler.stats['success'], 1) # lol
def test_object_move_dest_already_moved(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3679.2019,
(1, "/AUTH_bob/c/o1"): 3679.2019,
(0, "/AUTH_bob/c/o1"): 3679.2019,
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# we look for misplaced objects
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# but we found it already in the right place!
self.assertEqual(self.reconciler.stats['found_object'], 1)
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# so no attempt to read the source is made, but we do cleanup
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('DELETE', '/v1/AUTH_bob/c/o1')])
delete_headers = self.fake_swift.storage_policy[1].headers[0]
# rather we just clean up the dark matter
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3679.2019, offset=1))
# and wipe our hands of it
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_dest_object_newer_than_queue_entry(self):
self._mock_listing({
(None, "/.misplaced_objects/3600/1:/AUTH_bob/c/o1"): 3679.2019,
(1, "/AUTH_bob/c/o1"): 3679.2019,
(0, "/AUTH_bob/c/o1"): 3679.2019 + 1, # slightly newer
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# we look for misplaced objects...
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('3600')),
('GET', '/v1/.misplaced_objects/3600' + listing_qs('')),
('GET', '/v1/.misplaced_objects/3600' +
listing_qs('1:/AUTH_bob/c/o1'))])
# but we found it already in the right place!
self.assertEqual(self.reconciler.stats['found_object'], 1)
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1')])
# so not attempt to read is made, but we do cleanup
self.assertEqual(self.reconciler.stats['copy_attempt'], 0)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('DELETE', '/v1/AUTH_bob/c/o1')])
delete_headers = self.fake_swift.storage_policy[1].headers[0]
# rather we just clean up the dark matter
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(3679.2019, offset=1))
# and since we cleaned up the old object, so this counts as done
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '3600', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_dest_object_older_than_queue_entry(self):
self._mock_listing({
(None, "/.misplaced_objects/36000/1:/AUTH_bob/c/o1"): 36123.38393,
(1, "/AUTH_bob/c/o1"): 36123.38393,
(0, "/AUTH_bob/c/o1"): 36123.38393 - 1, # slightly older
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
# we found a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('36000')),
('GET', '/v1/.misplaced_objects/36000' + listing_qs('')),
('GET', '/v1/.misplaced_objects/36000' +
listing_qs('1:/AUTH_bob/c/o1'))])
# and since our version is *newer*, we overwrite
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(self.reconciler.stats['copy_success'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1'), # 2
('DELETE', '/v1/AUTH_bob/c/o1')]) # 4
delete_headers = self.fake_swift.storage_policy[1].headers[1]
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
# ... with a q_ts + offset 2
put_headers = self.fake_swift.storage_policy[0].headers[1]
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(36123.38393, offset=2))
# then clean the dark matter
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 1)
self.assertEqual(self.reconciler.stats['cleanup_success'], 1)
# ... with a q_ts + offset 1
self.assertEqual(delete_headers.get('X-Timestamp'),
Timestamp(36123.38393, offset=1))
# and pop the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 1)
self.assertEqual(deleted_container_entries,
[('.misplaced_objects', '36000', '1:/AUTH_bob/c/o1')])
self.assertEqual(self.reconciler.stats['success'], 1)
def test_object_move_put_fails(self):
# setup the cluster
self._mock_listing({
(None, "/.misplaced_objects/36000/1:/AUTH_bob/c/o1"): 36123.383925,
(1, "/AUTH_bob/c/o1"): 36123.383925,
})
self._mock_oldest_spi({'c': 0})
# make the put to dest fail!
self.fake_swift.storage_policy[0].register(
'PUT', '/v1/AUTH_bob/c/o1', swob.HTTPServiceUnavailable, {})
# turn the crank
deleted_container_entries = self._run_once()
# we find a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('36000')),
('GET', '/v1/.misplaced_objects/36000' + listing_qs('')),
('GET', '/v1/.misplaced_objects/36000' +
listing_qs('1:/AUTH_bob/c/o1'))])
# and try to move it, but it fails
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')]) # 2
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
put_headers = self.fake_swift.storage_policy[0].headers[1]
# ...with q_ts + offset 2 (20-microseconds)
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(36123.383925, offset=2))
# but it failed
self.assertEqual(self.reconciler.stats['copy_success'], 0)
self.assertEqual(self.reconciler.stats['copy_failed'], 1)
# ... so we don't clean up the source
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
# and we don't pop the queue
self.assertEqual(deleted_container_entries, [])
self.assertEqual(self.reconciler.stats['unhandled_errors'], 0)
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_object_move_put_blows_up_crazy_town(self):
# setup the cluster
self._mock_listing({
(None, "/.misplaced_objects/36000/1:/AUTH_bob/c/o1"): 36123.383925,
(1, "/AUTH_bob/c/o1"): 36123.383925,
})
self._mock_oldest_spi({'c': 0})
# make the put to dest blow up crazy town
def blow_up(*args, **kwargs):
raise Exception('kaboom!')
self.fake_swift.storage_policy[0].register(
'PUT', '/v1/AUTH_bob/c/o1', blow_up, {})
# turn the crank
deleted_container_entries = self._run_once()
# we find a misplaced object
self.assertEqual(self.reconciler.stats['misplaced_object'], 1)
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs('36000')),
('GET', '/v1/.misplaced_objects/36000' + listing_qs('')),
('GET', '/v1/.misplaced_objects/36000' +
listing_qs('1:/AUTH_bob/c/o1'))])
# and attempt to move it
self.assertEqual(self.reconciler.stats['copy_attempt'], 1)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_bob/c/o1')]) # 2
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_bob/c/o1'), # 1
('PUT', '/v1/AUTH_bob/c/o1')]) # 3
put_headers = self.fake_swift.storage_policy[0].headers[1]
# ...with q_ts + offset 2 (20-microseconds)
self.assertEqual(put_headers.get('X-Timestamp'),
Timestamp(36123.383925, offset=2))
# but it blows up hard
self.assertEqual(self.reconciler.stats['unhandled_error'], 1)
# so we don't cleanup
self.assertEqual(self.reconciler.stats['cleanup_attempt'], 0)
# and we don't pop the queue
self.assertEqual(self.reconciler.stats['pop_queue'], 0)
self.assertEqual(deleted_container_entries, [])
self.assertEqual(self.reconciler.stats['retry'], 1)
def test_object_move_no_such_object_no_tombstone_recent(self):
q_ts = float(Timestamp.now())
container = str(int(q_ts // 3600 * 3600))
q_path = '.misplaced_objects/%s' % container
self._mock_listing({
(None, "/%s/1:/AUTH_jeb/c/o1" % q_path): q_ts
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
self.assertEqual(
self.fake_swift.calls,
[('GET', '/v1/.misplaced_objects/%s' % container + listing_qs('')),
('GET', '/v1/.misplaced_objects/%s' % container +
listing_qs('1:/AUTH_jeb/c/o1')),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_jeb/c/o1')],
)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_jeb/c/o1')],
)
# the queue entry is recent enough that there could easily be
# tombstones on offline nodes or something, so we'll just leave it
# here and try again later
self.assertEqual(deleted_container_entries, [])
def test_object_move_no_such_object_no_tombstone_ancient(self):
queue_ts = float(Timestamp.now()) - \
self.reconciler.reclaim_age * 1.1
container = str(int(queue_ts // 3600 * 3600))
self._mock_listing({
(
None, "/.misplaced_objects/%s/1:/AUTH_jeb/c/o1" % container
): queue_ts
})
self._mock_oldest_spi({'c': 0})
deleted_container_entries = self._run_once()
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container)),
('GET', '/v1/.misplaced_objects/%s' % container + listing_qs('')),
('GET', '/v1/.misplaced_objects/%s' % container +
listing_qs('1:/AUTH_jeb/c/o1'))])
self.assertEqual(
self.fake_swift.storage_policy[0].calls,
[('HEAD', '/v1/AUTH_jeb/c/o1')],
)
self.assertEqual(
self.fake_swift.storage_policy[1].calls,
[('GET', '/v1/AUTH_jeb/c/o1')],
)
# the queue entry is old enough that the tombstones, if any, have
# probably been reaped, so we'll just give up
self.assertEqual(
deleted_container_entries,
[('.misplaced_objects', container, '1:/AUTH_jeb/c/o1')])
def test_delete_old_empty_queue_containers(self):
ts = time.time() - self.reconciler.reclaim_age * 1.1
container = str(int(ts // 3600 * 3600))
older_ts = ts - 3600
older_container = str(int(older_ts // 3600 * 3600))
self._mock_listing({
(None, "/.misplaced_objects/%s/" % container): 0,
(None, "/.misplaced_objects/%s/something" % older_container): 0,
})
deleted_container_entries = self._run_once()
self.assertEqual(deleted_container_entries, [])
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(container)),
('GET', '/v1/.misplaced_objects/%s' % container + listing_qs('')),
('DELETE', '/v1/.misplaced_objects/%s' % container),
('GET', '/v1/.misplaced_objects/%s' % older_container +
listing_qs('')),
('GET', '/v1/.misplaced_objects/%s' % older_container +
listing_qs('something'))])
self.assertEqual(self.reconciler.stats['invalid_record'], 1)
def test_iter_over_old_containers_in_reverse(self):
step = reconciler.MISPLACED_OBJECTS_CONTAINER_DIVISOR
now = self.start_interval
containers = []
for i in range(10):
container_ts = int(now - step * i)
container_name = str(container_ts // 3600 * 3600)
containers.append(container_name)
# add some old containers too
now -= self.reconciler.reclaim_age
old_containers = []
for i in range(10):
container_ts = int(now - step * i)
container_name = str(container_ts // 3600 * 3600)
old_containers.append(container_name)
containers.sort()
old_containers.sort()
all_containers = old_containers + containers
self._mock_listing(dict((
(None, "/.misplaced_objects/%s/" % container), 0
) for container in all_containers))
deleted_container_entries = self._run_once()
self.assertEqual(deleted_container_entries, [])
last_container = all_containers[-1]
account_listing_calls = [
('GET', '/v1/.misplaced_objects' + listing_qs('')),
('GET', '/v1/.misplaced_objects' + listing_qs(last_container)),
]
new_container_calls = [
('GET', '/v1/.misplaced_objects/%s' % container +
listing_qs('')) for container in reversed(containers)
][1:] # current_container get's skipped the second time around...
old_container_listings = [
('GET', '/v1/.misplaced_objects/%s' % container +
listing_qs('')) for container in reversed(old_containers)
]
old_container_deletes = [
('DELETE', '/v1/.misplaced_objects/%s' % container)
for container in reversed(old_containers)
]
old_container_calls = list(itertools.chain(*zip(
old_container_listings, old_container_deletes)))
self.assertEqual(self.fake_swift.calls,
[('GET', self.current_container_path)] +
account_listing_calls + new_container_calls +
old_container_calls)
def test_error_in_iter_containers(self):
self._mock_listing({})
# make the listing return an error
self.fake_swift.storage_policy[None].register(
'GET', '/v1/.misplaced_objects' + listing_qs(''),
swob.HTTPServiceUnavailable, {})
self._run_once()
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs(''))])
self.assertEqual(self.reconciler.stats, {})
errors = self.reconciler.logger.get_lines_for_level('error')
self.assertEqual(errors, [
'Error listing containers in account '
'.misplaced_objects (Unexpected response: '
'503 Service Unavailable)'])
def test_unhandled_exception_in_reconcile(self):
self._mock_listing({})
# make the listing blow up
def blow_up(*args, **kwargs):
raise Exception('kaboom!')
self.fake_swift.storage_policy[None].register(
'GET', '/v1/.misplaced_objects' + listing_qs(''),
blow_up, {})
self._run_once()
self.assertEqual(
self.fake_swift.calls,
[('GET', self.current_container_path),
('GET', '/v1/.misplaced_objects' + listing_qs(''))])
self.assertEqual(self.reconciler.stats, {})
errors = self.reconciler.logger.get_lines_for_level('error')
self.assertEqual(errors,
['Unhandled Exception trying to reconcile: '])
if __name__ == '__main__':
unittest.main()
| openstack/swift | test/unit/container/test_reconciler.py | Python | apache-2.0 | 96,529 |
package org.xtext.example.mydsl.ui.contentassist.antlr.internal;
// Hack: Use our own Lexer superclass by means of import.
// Currently there is no other way to specify the superclass for the lexer.
import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.Lexer;
import org.antlr.runtime.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
@SuppressWarnings("all")
public class InternalMyDslLexer extends Lexer {
public static final int RULE_ID=4;
public static final int RULE_STRING=6;
public static final int T__12=12;
public static final int T__11=11;
public static final int RULE_ANY_OTHER=10;
public static final int RULE_INT=5;
public static final int RULE_WS=9;
public static final int RULE_SL_COMMENT=8;
public static final int EOF=-1;
public static final int RULE_ML_COMMENT=7;
// delegates
// delegators
public InternalMyDslLexer() {;}
public InternalMyDslLexer(CharStream input) {
this(input, new RecognizerSharedState());
}
public InternalMyDslLexer(CharStream input, RecognizerSharedState state) {
super(input,state);
}
public String getGrammarFileName() { return "../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g"; }
// $ANTLR start "T__11"
public final void mT__11() throws RecognitionException {
try {
int _type = T__11;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:11:7: ( 'Hello' )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:11:9: 'Hello'
{
match("Hello");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__11"
// $ANTLR start "T__12"
public final void mT__12() throws RecognitionException {
try {
int _type = T__12;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:12:7: ( '!' )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:12:9: '!'
{
match('!');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__12"
// $ANTLR start "RULE_ID"
public final void mRULE_ID() throws RecognitionException {
try {
int _type = RULE_ID;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:246:9: ( ( '^' )? ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )* )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:246:11: ( '^' )? ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
{
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:246:11: ( '^' )?
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0=='^') ) {
alt1=1;
}
switch (alt1) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:246:11: '^'
{
match('^');
}
break;
}
if ( (input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:246:40: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0>='0' && LA2_0<='9')||(LA2_0>='A' && LA2_0<='Z')||LA2_0=='_'||(LA2_0>='a' && LA2_0<='z')) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:
{
if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop2;
}
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ID"
// $ANTLR start "RULE_INT"
public final void mRULE_INT() throws RecognitionException {
try {
int _type = RULE_INT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:248:10: ( ( '0' .. '9' )+ )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:248:12: ( '0' .. '9' )+
{
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:248:12: ( '0' .. '9' )+
int cnt3=0;
loop3:
do {
int alt3=2;
int LA3_0 = input.LA(1);
if ( ((LA3_0>='0' && LA3_0<='9')) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:248:13: '0' .. '9'
{
matchRange('0','9');
}
break;
default :
if ( cnt3 >= 1 ) break loop3;
EarlyExitException eee =
new EarlyExitException(3, input);
throw eee;
}
cnt3++;
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_INT"
// $ANTLR start "RULE_STRING"
public final void mRULE_STRING() throws RecognitionException {
try {
int _type = RULE_STRING;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:13: ( ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' ) )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:15: ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' )
{
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:15: ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' )
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0=='\"') ) {
alt6=1;
}
else if ( (LA6_0=='\'') ) {
alt6=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:16: '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"'
{
match('\"');
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:20: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )*
loop4:
do {
int alt4=3;
int LA4_0 = input.LA(1);
if ( (LA4_0=='\\') ) {
alt4=1;
}
else if ( ((LA4_0>='\u0000' && LA4_0<='!')||(LA4_0>='#' && LA4_0<='[')||(LA4_0>=']' && LA4_0<='\uFFFF')) ) {
alt4=2;
}
switch (alt4) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:21: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' )
{
match('\\');
if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||(input.LA(1)>='t' && input.LA(1)<='u') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
case 2 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:66: ~ ( ( '\\\\' | '\"' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop4;
}
} while (true);
match('\"');
}
break;
case 2 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:86: '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\''
{
match('\'');
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:91: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )*
loop5:
do {
int alt5=3;
int LA5_0 = input.LA(1);
if ( (LA5_0=='\\') ) {
alt5=1;
}
else if ( ((LA5_0>='\u0000' && LA5_0<='&')||(LA5_0>='(' && LA5_0<='[')||(LA5_0>=']' && LA5_0<='\uFFFF')) ) {
alt5=2;
}
switch (alt5) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:92: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' )
{
match('\\');
if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||(input.LA(1)>='t' && input.LA(1)<='u') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
case 2 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:250:137: ~ ( ( '\\\\' | '\\'' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop5;
}
} while (true);
match('\'');
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_STRING"
// $ANTLR start "RULE_ML_COMMENT"
public final void mRULE_ML_COMMENT() throws RecognitionException {
try {
int _type = RULE_ML_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:252:17: ( '/*' ( options {greedy=false; } : . )* '*/' )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:252:19: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*");
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:252:24: ( options {greedy=false; } : . )*
loop7:
do {
int alt7=2;
int LA7_0 = input.LA(1);
if ( (LA7_0=='*') ) {
int LA7_1 = input.LA(2);
if ( (LA7_1=='/') ) {
alt7=2;
}
else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) {
alt7=1;
}
}
else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) {
alt7=1;
}
switch (alt7) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:252:52: .
{
matchAny();
}
break;
default :
break loop7;
}
} while (true);
match("*/");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ML_COMMENT"
// $ANTLR start "RULE_SL_COMMENT"
public final void mRULE_SL_COMMENT() throws RecognitionException {
try {
int _type = RULE_SL_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:17: ( '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:19: '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )?
{
match("//");
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:24: (~ ( ( '\\n' | '\\r' ) ) )*
loop8:
do {
int alt8=2;
int LA8_0 = input.LA(1);
if ( ((LA8_0>='\u0000' && LA8_0<='\t')||(LA8_0>='\u000B' && LA8_0<='\f')||(LA8_0>='\u000E' && LA8_0<='\uFFFF')) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:24: ~ ( ( '\\n' | '\\r' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop8;
}
} while (true);
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:40: ( ( '\\r' )? '\\n' )?
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0=='\n'||LA10_0=='\r') ) {
alt10=1;
}
switch (alt10) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:41: ( '\\r' )? '\\n'
{
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:41: ( '\\r' )?
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='\r') ) {
alt9=1;
}
switch (alt9) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:254:41: '\\r'
{
match('\r');
}
break;
}
match('\n');
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_SL_COMMENT"
// $ANTLR start "RULE_WS"
public final void mRULE_WS() throws RecognitionException {
try {
int _type = RULE_WS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:256:9: ( ( ' ' | '\\t' | '\\r' | '\\n' )+ )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:256:11: ( ' ' | '\\t' | '\\r' | '\\n' )+
{
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:256:11: ( ' ' | '\\t' | '\\r' | '\\n' )+
int cnt11=0;
loop11:
do {
int alt11=2;
int LA11_0 = input.LA(1);
if ( ((LA11_0>='\t' && LA11_0<='\n')||LA11_0=='\r'||LA11_0==' ') ) {
alt11=1;
}
switch (alt11) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:
{
if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
if ( cnt11 >= 1 ) break loop11;
EarlyExitException eee =
new EarlyExitException(11, input);
throw eee;
}
cnt11++;
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_WS"
// $ANTLR start "RULE_ANY_OTHER"
public final void mRULE_ANY_OTHER() throws RecognitionException {
try {
int _type = RULE_ANY_OTHER;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:258:16: ( . )
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:258:18: .
{
matchAny();
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ANY_OTHER"
public void mTokens() throws RecognitionException {
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:8: ( T__11 | T__12 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER )
int alt12=9;
alt12 = dfa12.predict(input);
switch (alt12) {
case 1 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:10: T__11
{
mT__11();
}
break;
case 2 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:16: T__12
{
mT__12();
}
break;
case 3 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:22: RULE_ID
{
mRULE_ID();
}
break;
case 4 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:30: RULE_INT
{
mRULE_INT();
}
break;
case 5 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:39: RULE_STRING
{
mRULE_STRING();
}
break;
case 6 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:51: RULE_ML_COMMENT
{
mRULE_ML_COMMENT();
}
break;
case 7 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:67: RULE_SL_COMMENT
{
mRULE_SL_COMMENT();
}
break;
case 8 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:83: RULE_WS
{
mRULE_WS();
}
break;
case 9 :
// ../org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDsl.g:1:91: RULE_ANY_OTHER
{
mRULE_ANY_OTHER();
}
break;
}
}
protected DFA12 dfa12 = new DFA12(this);
static final String DFA12_eotS =
"\1\uffff\1\14\1\uffff\1\12\2\uffff\3\12\2\uffff\1\14\7\uffff\2"+
"\14\1\26\1\uffff";
static final String DFA12_eofS =
"\27\uffff";
static final String DFA12_minS =
"\1\0\1\145\1\uffff\1\101\2\uffff\2\0\1\52\2\uffff\1\154\7\uffff"+
"\1\154\1\157\1\60\1\uffff";
static final String DFA12_maxS =
"\1\uffff\1\145\1\uffff\1\172\2\uffff\2\uffff\1\57\2\uffff\1\154"+
"\7\uffff\1\154\1\157\1\172\1\uffff";
static final String DFA12_acceptS =
"\2\uffff\1\2\1\uffff\1\3\1\4\3\uffff\1\10\1\11\1\uffff\1\3\1\2"+
"\1\4\1\5\1\6\1\7\1\10\3\uffff\1\1";
static final String DFA12_specialS =
"\1\0\5\uffff\1\2\1\1\17\uffff}>";
static final String[] DFA12_transitionS = {
"\11\12\2\11\2\12\1\11\22\12\1\11\1\2\1\6\4\12\1\7\7\12\1\10"+
"\12\5\7\12\7\4\1\1\22\4\3\12\1\3\1\4\1\12\32\4\uff85\12",
"\1\13",
"",
"\32\14\4\uffff\1\14\1\uffff\32\14",
"",
"",
"\0\17",
"\0\17",
"\1\20\4\uffff\1\21",
"",
"",
"\1\23",
"",
"",
"",
"",
"",
"",
"",
"\1\24",
"\1\25",
"\12\14\7\uffff\32\14\4\uffff\1\14\1\uffff\32\14",
""
};
static final short[] DFA12_eot = DFA.unpackEncodedString(DFA12_eotS);
static final short[] DFA12_eof = DFA.unpackEncodedString(DFA12_eofS);
static final char[] DFA12_min = DFA.unpackEncodedStringToUnsignedChars(DFA12_minS);
static final char[] DFA12_max = DFA.unpackEncodedStringToUnsignedChars(DFA12_maxS);
static final short[] DFA12_accept = DFA.unpackEncodedString(DFA12_acceptS);
static final short[] DFA12_special = DFA.unpackEncodedString(DFA12_specialS);
static final short[][] DFA12_transition;
static {
int numStates = DFA12_transitionS.length;
DFA12_transition = new short[numStates][];
for (int i=0; i<numStates; i++) {
DFA12_transition[i] = DFA.unpackEncodedString(DFA12_transitionS[i]);
}
}
class DFA12 extends DFA {
public DFA12(BaseRecognizer recognizer) {
this.recognizer = recognizer;
this.decisionNumber = 12;
this.eot = DFA12_eot;
this.eof = DFA12_eof;
this.min = DFA12_min;
this.max = DFA12_max;
this.accept = DFA12_accept;
this.special = DFA12_special;
this.transition = DFA12_transition;
}
public String getDescription() {
return "1:1: Tokens : ( T__11 | T__12 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER );";
}
public int specialStateTransition(int s, IntStream _input) throws NoViableAltException {
IntStream input = _input;
int _s = s;
switch ( s ) {
case 0 :
int LA12_0 = input.LA(1);
s = -1;
if ( (LA12_0=='H') ) {s = 1;}
else if ( (LA12_0=='!') ) {s = 2;}
else if ( (LA12_0=='^') ) {s = 3;}
else if ( ((LA12_0>='A' && LA12_0<='G')||(LA12_0>='I' && LA12_0<='Z')||LA12_0=='_'||(LA12_0>='a' && LA12_0<='z')) ) {s = 4;}
else if ( ((LA12_0>='0' && LA12_0<='9')) ) {s = 5;}
else if ( (LA12_0=='\"') ) {s = 6;}
else if ( (LA12_0=='\'') ) {s = 7;}
else if ( (LA12_0=='/') ) {s = 8;}
else if ( ((LA12_0>='\t' && LA12_0<='\n')||LA12_0=='\r'||LA12_0==' ') ) {s = 9;}
else if ( ((LA12_0>='\u0000' && LA12_0<='\b')||(LA12_0>='\u000B' && LA12_0<='\f')||(LA12_0>='\u000E' && LA12_0<='\u001F')||(LA12_0>='#' && LA12_0<='&')||(LA12_0>='(' && LA12_0<='.')||(LA12_0>=':' && LA12_0<='@')||(LA12_0>='[' && LA12_0<=']')||LA12_0=='`'||(LA12_0>='{' && LA12_0<='\uFFFF')) ) {s = 10;}
if ( s>=0 ) return s;
break;
case 1 :
int LA12_7 = input.LA(1);
s = -1;
if ( ((LA12_7>='\u0000' && LA12_7<='\uFFFF')) ) {s = 15;}
else s = 10;
if ( s>=0 ) return s;
break;
case 2 :
int LA12_6 = input.LA(1);
s = -1;
if ( ((LA12_6>='\u0000' && LA12_6<='\uFFFF')) ) {s = 15;}
else s = 10;
if ( s>=0 ) return s;
break;
}
NoViableAltException nvae =
new NoViableAltException(getDescription(), 12, _s, input);
error(nvae);
throw nvae;
}
}
} | adrian-herscu/experiments | language-workbenches/xtext/org.xtext.example.mydsl.ui/src-gen/org/xtext/example/mydsl/ui/contentassist/antlr/internal/InternalMyDslLexer.java | Java | apache-2.0 | 30,792 |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>模板信息--公共</title>
<link rel="shortcut icon" href="../../img/favicon.ico"/>
<link href="../../css/bootstrap.min.css" rel="stylesheet"/>
<style>
.print-btn {
position: fixed;
top: 30%;
right: 3%;
z-index: 100;
}
</style>
</head>
<body>
<div class="container">
<!--标题信息-->
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">
模板浏览
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="center-block">
<div class="page-header">
<h1 th:text="${displayQuestionnaireVO.questionnaireTitle}" align="center">标题</h1>
</div>
</div>
</div>
<div class="row">
<blockquote class="blockquote-reverse">
<p th:if="${not #strings.isEmpty(displayQuestionnaireVO.questionnaireSubtitle)}"
th:text="${displayQuestionnaireVO.questionnaireSubtitle}">副标题</p><br/>
<p th:if="${not #strings.isEmpty(displayQuestionnaireVO.questionnaireDescription)}"
th:text="${displayQuestionnaireVO.questionnaireDescription}">描述信息</p>
<!--<footer>创建人 创建于 <cite title="Source Title">创建时间</cite></footer>-->
</blockquote>
</div>
<!--问卷中详细问题信息开始-->
<!--遍历问卷题目信息-->
<div class="panel-group" th:if="${#lists.size(displayQuestionnaireVO.questions)>0}"
th:each="curQes,iterStat: ${displayQuestionnaireVO.questions}"
th:switch="${curQes.questionType}">
<!--单选题模板-->
<div class="panel-default" th:case="'单选题'">
<div class="panel-heading">
<div class="panel-title">
第 <span th:text="${iterStat.count}">[题号]</span> 题:
<span th:text="${curQes.questionContext}"></span>
(
<span th:text="${curQes.questionType}">题型</span>
<span th:if="${#bools.isTrue(curQes.must)}" style="color: red;">*</span>
)
</div>
</div>
<div class="panel-body">
<div class="form-inline">
<div class="form-group" th:if="${#lists.size(curQes.options)>0}"
th:each="curQesOption: ${curQes.options}">
<input class="form-control" type="radio" th:name="${iterStat.index}"/>
<label th:text="${curQesOption.option}">选项</label>
</div>
</div>
</div>
</div>
<!--多选题模板-->
<div class="panel-default" th:case="'多选题'">
<div class="panel-heading">
<div class="panel-title">
第 <span th:text="${iterStat.count}">[题号]</span> 题:
<span th:text="${curQes.questionContext}"></span>
(
<span th:text="${curQes.questionType}">题型</span>
<span th:if="${#bools.isTrue(curQes.must)}" style="color: red;">*</span>
)
</div>
</div>
<div class="panel-body">
<div class="form-inline">
<div class="form-group" th:if="${#lists.size(curQes.options)>0}"
th:each="curQesOption: ${curQes.options}">
<input class="form-control" type="checkbox" th:name="${iterStat.index}"/>
<label th:text="${curQesOption.option}">选项</label>
</div>
</div>
</div>
</div>
<!--单项填空题模板-->
<div class="panel-default" th:case="'单项填空题'">
<div class="panel-heading">
<div class="panel-title">
第 <span th:text="${iterStat.count}">[题号]</span> 题:
<span th:text="${curQes.questionContext}"></span>
(
<span th:text="${curQes.questionType}">题型</span>
<span th:if="${#bools.isTrue(curQes.must)}" style="color: red;">*</span>
)
</div>
</div>
<div class="panel-body">
<div class="form-group">
<input class="form-control" disabled/>
</div>
</div>
</div>
<!--多项填空题模板-->
<div class="panel-default" th:case="'多项填空题'">
<div class="panel-heading">
<div class="panel-title">
第 <span th:text="${iterStat.count}">[题号]</span> 题:
<span th:text="${curQes.questionContext}"></span>
(
<span th:text="${curQes.questionType}">题型</span>
<span th:if="${#bools.isTrue(curQes.must)}" style="color: red;">*</span>
)
</div>
</div>
<div class="panel-body">
<div class="form-inline">
<div class="form-group" th:if="${#lists.size(curQes.options)>0}"
th:each="curQesOption: ${curQes.options}">
<div style="size: auto"
th:if="${curQesOption.option!=null && not #strings.isEmpty(curQesOption.option)}">
<label>_______</label>
<label th:text="${curQesOption.option}">问题</label>
</div>
</div>
</div>
</div>
</div>
<!--简答题模板-->
<div class="panel-default" th:case="'简答题'">
<div class="panel-heading">
<div class="panel-title">
第 <span th:text="${iterStat.count}">[题号]</span> 题:
<span th:text="${curQes.questionContext}"></span>
(
<span th:text="${curQes.questionType}">题型</span>
<span th:if="${#bools.isTrue(curQes.must)}" style="color: red;">*</span>
)
</div>
</div>
<div class="panel-body">
<div class="form-group">
<textarea class="form-control" disabled></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<!--打印按钮-->
<div class="row hidden-print print-btn">
<div class="btn-group-lg pull-right">
<button th:disabled="${isOutOfMinIndex == true}" id="prevPaperBtn" class="btn btn-default btn-block"
data-toggle="tooltip" title="上一份">
<i class="glyphicon glyphicon-chevron-up"></i>
</button>
<button id="printQesBtn" class="btn btn-default btn-block">打印</button>
<button th:disabled="${isOutOfMaxIndex == true}" id="nextPaperBtn" class="btn btn-default btn-block"
data-toggle="tooltip" title="下一份">
<i class="glyphicon glyphicon-chevron-down"></i>
</button>
</div>
</div>
</div>
<script src="../../js/jquery.min.js"></script>
<script>
$(function () {
$('#printQesBtn').on('click', function () {
window.print();
});
$('#prevPaperBtn').on('click', function () {
window.location.href = '/publicTemplateManage/displayPrevQesPaper';
});
$('#nextPaperBtn').on('click', function () {
window.location.href = '/publicTemplateManage/displayNextQesPaper';
})
});
</script>
</body>
</html> | Harveychn/questionnaire | src/main/webapp/WEB-INF/view/qesTemplateManage/displayPubTemplate.html | HTML | apache-2.0 | 9,014 |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Interop;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Base class for interop targets.
/// </summary>
internal class PlatformJniTarget : IPlatformTargetInternal
{
/** */
private static readonly Dictionary<Type, FutureType> IgniteFutureTypeMap
= new Dictionary<Type, FutureType>
{
{typeof(bool), FutureType.Bool},
{typeof(byte), FutureType.Byte},
{typeof(char), FutureType.Char},
{typeof(double), FutureType.Double},
{typeof(float), FutureType.Float},
{typeof(int), FutureType.Int},
{typeof(long), FutureType.Long},
{typeof(short), FutureType.Short}
};
/** Unmanaged target. */
private readonly IUnmanagedTarget _target;
/** Marshaller. */
private readonly Marshaller _marsh;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
public PlatformJniTarget(IUnmanagedTarget target, Marshaller marsh)
{
Debug.Assert(target != null);
Debug.Assert(marsh != null);
_target = target;
_marsh = marsh;
}
/// <summary>
/// Gets the target.
/// </summary>
public IUnmanagedTarget Target
{
get { return _target; }
}
/** <inheritdoc /> */
public Marshaller Marshaller { get { return _marsh; } }
/** <inheritdoc /> */
public long InStreamOutLong(int type, Action<IBinaryStream> writeAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
writeAction(stream);
return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
}
}
/** <inheritdoc /> */
public IPlatformTargetInternal InStreamOutObject(int type, Action<IBinaryStream> writeAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
writeAction(stream);
var target = UU.TargetInStreamOutObject(_target, type, stream.SynchronizeOutput());
return target == null ? null : new PlatformJniTarget(target, _marsh);
}
}
/** <inheritdoc /> */
public IPlatformTargetInternal OutObjectInternal(int type)
{
return GetPlatformTarget(UU.TargetOutObject(_target, type));
}
/** <inheritdoc /> */
public T OutStream<T>(int type, Func<IBinaryStream, T> readAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
UU.TargetOutStream(_target, type, stream.MemoryPointer);
stream.SynchronizeInput();
return readAction(stream);
}
}
/** <inheritdoc /> */
public TR InStreamOutStream<TR>(int type, Action<IBinaryStream> writeAction,
Func<IBinaryStream, TR> readAction)
{
using (var outStream = IgniteManager.Memory.Allocate().GetStream())
using (var inStream = IgniteManager.Memory.Allocate().GetStream())
{
writeAction(outStream);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return readAction(inStream);
}
}
/** <inheritdoc /> */
public TR InStreamOutLong<TR>(int type, Action<IBinaryStream> outAction, Func<IBinaryStream, long, TR> inAction,
Func<IBinaryStream, Exception> readErrorAction)
{
Debug.Assert(readErrorAction != null);
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
outAction(stream);
var res = UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
if (res != PlatformTargetAdapter.Error && inAction == null)
return default(TR); // quick path for void operations
stream.SynchronizeInput();
stream.Seek(0, SeekOrigin.Begin);
if (res != PlatformTargetAdapter.Error)
{
return inAction != null ? inAction(stream, res) : default(TR);
}
throw readErrorAction(stream);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public unsafe TR InObjectStreamOutObjectStream<TR>(int type, Action<IBinaryStream> writeAction,
Func<IBinaryStream, IPlatformTargetInternal, TR> readAction, IPlatformTargetInternal arg)
{
PlatformMemoryStream outStream = null;
long outPtr = 0;
PlatformMemoryStream inStream = null;
long inPtr = 0;
try
{
if (writeAction != null)
{
outStream = IgniteManager.Memory.Allocate().GetStream();
writeAction(outStream);
outPtr = outStream.SynchronizeOutput();
}
if (readAction != null)
{
inStream = IgniteManager.Memory.Allocate().GetStream();
inPtr = inStream.MemoryPointer;
}
var res = UU.TargetInObjectStreamOutObjectStream(_target, type,
((PlatformJniTarget)arg).Target.Target, outPtr, inPtr);
if (readAction == null)
return default(TR);
inStream.SynchronizeInput();
var target = res == null ? null : new PlatformJniTarget(res, _marsh);
return readAction(inStream, target);
}
finally
{
try
{
if (inStream != null)
inStream.Dispose();
}
finally
{
if (outStream != null)
outStream.Dispose();
}
}
}
/// <summary>
/// Finish marshaling.
/// </summary>
/// <param name="writer">Writer.</param>
private void FinishMarshal(BinaryWriter writer)
{
_marsh.FinishMarshal(writer);
}
/// <summary>
/// Creates a future and starts listening.
/// </summary>
/// <typeparam name="T">Future result type</typeparam>
/// <param name="listenAction">The listen action.</param>
/// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param>
/// <param name="convertFunc">The function to read future result from stream.</param>
/// <returns>Created future.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private Future<T> GetFuture<T>(Func<long, int, IUnmanagedTarget> listenAction, bool keepBinary = false,
Func<BinaryReader, T> convertFunc = null)
{
var futType = FutureType.Object;
var type = typeof(T);
if (type.IsPrimitive)
IgniteFutureTypeMap.TryGetValue(type, out futType);
var fut = convertFunc == null && futType != FutureType.Object
? new Future<T>()
: new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc));
var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut);
IUnmanagedTarget futTarget;
try
{
futTarget = listenAction(futHnd, (int)futType);
}
catch (Exception)
{
_marsh.Ignite.HandleRegistry.Release(futHnd);
throw;
}
fut.SetTarget(new Listenable(new PlatformJniTarget(futTarget, _marsh)));
return fut;
}
/// <summary>
/// Creates a future and starts listening.
/// </summary>
/// <typeparam name="T">Future result type</typeparam>
/// <param name="listenAction">The listen action.</param>
/// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param>
/// <param name="convertFunc">The function to read future result from stream.</param>
/// <returns>Created future.</returns>
private Future<T> GetFuture<T>(Action<long, int> listenAction, bool keepBinary = false,
Func<BinaryReader, T> convertFunc = null)
{
var futType = FutureType.Object;
var type = typeof(T);
if (type.IsPrimitive)
IgniteFutureTypeMap.TryGetValue(type, out futType);
var fut = convertFunc == null && futType != FutureType.Object
? new Future<T>()
: new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc));
var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut);
try
{
listenAction(futHnd, (int)futType);
}
catch (Exception)
{
_marsh.Ignite.HandleRegistry.Release(futHnd);
throw;
}
return fut;
}
#region IPlatformTarget
/** <inheritdoc /> */
public long InLongOutLong(int type, long val)
{
return UU.TargetInLongOutLong(_target, type, val);
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public long InStreamOutLong(int type, Action<IBinaryRawWriter> writeAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
FinishMarshal(writer);
return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput());
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public T InStreamOutStream<T>(int type, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readAction)
{
using (var outStream = IgniteManager.Memory.Allocate().GetStream())
using (var inStream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(outStream);
writeAction(writer);
FinishMarshal(writer);
UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer);
inStream.SynchronizeInput();
return readAction(_marsh.StartUnmarshal(inStream));
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public IPlatformTarget InStreamOutObject(int type, Action<IBinaryRawWriter> writeAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
FinishMarshal(writer);
return GetPlatformTarget(UU.TargetInStreamOutObject(_target, type, stream.SynchronizeOutput()));
}
}
/** <inheritdoc /> */
public unsafe T InObjectStreamOutObjectStream<T>(int type, IPlatformTarget arg,
Action<IBinaryRawWriter> writeAction, Func<IBinaryRawReader, IPlatformTarget, T> readAction)
{
PlatformMemoryStream outStream = null;
long outPtr = 0;
PlatformMemoryStream inStream = null;
long inPtr = 0;
try
{
if (writeAction != null)
{
outStream = IgniteManager.Memory.Allocate().GetStream();
var writer = _marsh.StartMarshal(outStream);
writeAction(writer);
FinishMarshal(writer);
outPtr = outStream.SynchronizeOutput();
}
if (readAction != null)
{
inStream = IgniteManager.Memory.Allocate().GetStream();
inPtr = inStream.MemoryPointer;
}
var res = UU.TargetInObjectStreamOutObjectStream(_target, type, GetTargetPtr(arg), outPtr, inPtr);
if (readAction == null)
return default(T);
inStream.SynchronizeInput();
return readAction(_marsh.StartUnmarshal(inStream), GetPlatformTarget(res));
}
finally
{
try
{
if (inStream != null)
inStream.Dispose();
}
finally
{
if (outStream != null)
outStream.Dispose();
}
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public T OutStream<T>(int type, Func<IBinaryRawReader, T> readAction)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
UU.TargetOutStream(_target, type, stream.MemoryPointer);
stream.SynchronizeInput();
return readAction(_marsh.StartUnmarshal(stream));
}
}
/** <inheritdoc /> */
public IPlatformTarget OutObject(int type)
{
return OutObjectInternal(type);
}
/** <inheritdoc /> */
public Task<T> DoOutOpAsync<T>(int type, Action<IBinaryRawWriter> writeAction = null,
Func<IBinaryRawReader, T> readAction = null)
{
var convertFunc = readAction != null
? r => readAction(r)
: (Func<BinaryReader, T>)null;
return GetFuture((futId, futType) =>
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
stream.WriteLong(futId);
stream.WriteInt(futType);
if (writeAction != null)
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
FinishMarshal(writer);
}
UU.TargetInStreamAsync(_target, type, stream.SynchronizeOutput());
}
}, false, convertFunc).Task;
}
/** <inheritdoc /> */
public Task<T> DoOutOpAsync<T>(int type, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readAction, CancellationToken cancellationToken)
{
var convertFunc = readAction != null
? r => readAction(r)
: (Func<BinaryReader, T>) null;
return GetFuture((futId, futType) =>
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
stream.WriteLong(futId);
stream.WriteInt(futType);
if (writeAction != null)
{
var writer = _marsh.StartMarshal(stream);
writeAction(writer);
FinishMarshal(writer);
}
return UU.TargetInStreamOutObjectAsync(_target, type, stream.SynchronizeOutput());
}
}, false, convertFunc).GetTask(cancellationToken);
}
/// <summary>
/// Gets the platform target.
/// </summary>
private IPlatformTargetInternal GetPlatformTarget(IUnmanagedTarget target)
{
return target == null ? null : new PlatformJniTarget(target, _marsh);
}
/// <summary>
/// Gets the target pointer.
/// </summary>
private static unsafe void* GetTargetPtr(IPlatformTarget target)
{
return target == null ? null : ((PlatformJniTarget) target)._target.Target;
}
#endregion
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
public void Dispose()
{
if (_target != null)
{
_target.Dispose();
}
}
}
}
| ntikhonov/ignite | modules/platforms/dotnet/Apache.Ignite.Core/Impl/PlatformJniTarget.cs | C# | apache-2.0 | 18,633 |
---
title: "Setup"
linkTitle: "Setup"
weight: 50
date: 2021-08-20
tags:
description: >
---
| gchq/stroom-docs | content/en/docs/install-guide/setup/_index.md | Markdown | apache-2.0 | 97 |
/**
* Copyright 2011 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.bricket.plugin.user.web;
import org.bricket.web.BricketPageParameterDefinition;
/**
* @author Ingo Renner
* @author Henning Teek
*/
public final class UserPageParameterDefinition implements BricketPageParameterDefinition {
public static final String USER_PAGE_PARAMETER = "uid";
private UserPageParameterDefinition() {
super();
}
}
| bricket/bricket | bricket-core/src/main/java/org/bricket/plugin/user/web/UserPageParameterDefinition.java | Java | apache-2.0 | 990 |
/*
* 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.builder;
import com.intellij.psi.PsiType;
import com.intellij.refactoring.typeCook.deductive.resolver.Binding;
/**
* Created by IntelliJ IDEA.
* User: db
* Date: Jul 20, 2004
* Time: 6:02:29 PM
* To change this template use File | Settings | File Templates.
*/
public class Subtype extends Constraint {
public Subtype(PsiType left, PsiType right) {
super(left, right);
}
String relationString() {
return "<:";
}
int relationType() {
return 1;
}
public Constraint apply(final Binding b) {
return new Subtype(b.apply(myLeft), b.apply(myRight));
}
}
| jexp/idea2 | java/java-impl/src/com/intellij/refactoring/typeCook/deductive/builder/Subtype.java | Java | apache-2.0 | 1,243 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticmapreduce.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* StepSummary JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StepSummaryJsonUnmarshaller implements Unmarshaller<StepSummary, JsonUnmarshallerContext> {
public StepSummary unmarshall(JsonUnmarshallerContext context) throws Exception {
StepSummary stepSummary = new StepSummary();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Id", targetDepth)) {
context.nextToken();
stepSummary.setId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
stepSummary.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Config", targetDepth)) {
context.nextToken();
stepSummary.setConfig(HadoopStepConfigJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("ActionOnFailure", targetDepth)) {
context.nextToken();
stepSummary.setActionOnFailure(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
stepSummary.setStatus(StepStatusJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return stepSummary;
}
private static StepSummaryJsonUnmarshaller instance;
public static StepSummaryJsonUnmarshaller getInstance() {
if (instance == null)
instance = new StepSummaryJsonUnmarshaller();
return instance;
}
}
| dagnir/aws-sdk-java | aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/StepSummaryJsonUnmarshaller.java | Java | apache-2.0 | 3,640 |
# AUTOGENERATED FILE
FROM balenalib/imx8m-var-dart-fedora:36-build
ENV GO_VERSION 1.16.14
RUN mkdir -p /usr/local/go \
&& curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \
&& echo "5e59056e36704acb25809bcdb27191f27593cb7aba4d716b523008135a1e764a go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-arm64.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 36 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.14 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | resin-io-library/base-images | balena-base-images/golang/imx8m-var-dart/fedora/36/1.16.14/build/Dockerfile | Dockerfile | apache-2.0 | 1,999 |
/*
* 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.sysml.runtime.instructions.spark;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.Random;
import java.util.stream.LongStream;
import org.apache.commons.math3.distribution.PoissonDistribution;
import org.apache.commons.math3.random.Well1024a;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.util.random.SamplingUtils;
import scala.Tuple2;
import org.apache.sysml.api.DMLScript;
import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
import org.apache.sysml.conf.ConfigurationManager;
import org.apache.sysml.hops.DataGenOp;
import org.apache.sysml.hops.Hop.DataGenMethod;
import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.lops.DataGen;
import org.apache.sysml.lops.Lop;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysml.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.instructions.cp.CPOperand;
import org.apache.sysml.runtime.instructions.spark.utils.RDDConverterUtils;
import org.apache.sysml.runtime.io.IOUtilFunctions;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;
import org.apache.sysml.runtime.matrix.data.LibMatrixDatagen;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.data.MatrixCell;
import org.apache.sysml.runtime.matrix.data.MatrixIndexes;
import org.apache.sysml.runtime.matrix.data.RandomMatrixGenerator;
import org.apache.sysml.runtime.matrix.operators.Operator;
import org.apache.sysml.runtime.util.UtilFunctions;
import org.apache.sysml.utils.Statistics;
public class RandSPInstruction extends UnarySPInstruction
{
//internal configuration
private static final long INMEMORY_NUMBLOCKS_THRESHOLD = 1024 * 1024;
private DataGenMethod method = DataGenMethod.INVALID;
private long rows;
private long cols;
private int rowsInBlock;
private int colsInBlock;
private double minValue;
private double maxValue;
private double sparsity;
private String pdf;
private String pdfParams;
private long seed=0;
private String dir;
private double seq_from;
private double seq_to;
private double seq_incr;
//sample specific attributes
private boolean replace;
public RandSPInstruction (Operator op, DataGenMethod mthd, CPOperand in, CPOperand out, long rows, long cols,
int rpb, int cpb, double minValue, double maxValue, double sparsity, long seed, String dir,
String probabilityDensityFunction, String pdfParams, String opcode, String istr)
{
super(op, in, out, opcode, istr);
this.method = mthd;
this.rows = rows;
this.cols = cols;
this.rowsInBlock = rpb;
this.colsInBlock = cpb;
this.minValue = minValue;
this.maxValue = maxValue;
this.sparsity = sparsity;
this.seed = seed;
this.dir = dir;
this.pdf = probabilityDensityFunction;
this.pdfParams = pdfParams;
}
public RandSPInstruction(Operator op, DataGenMethod mthd, CPOperand in, CPOperand out,
long rows, long cols, int rpb, int cpb, double seqFrom,
double seqTo, double seqIncr, String opcode, String istr)
{
super(op, in, out, opcode, istr);
this.method = mthd;
this.rows = rows;
this.cols = cols;
this.rowsInBlock = rpb;
this.colsInBlock = cpb;
this.seq_from = seqFrom;
this.seq_to = seqTo;
this.seq_incr = seqIncr;
}
public RandSPInstruction(Operator op, DataGenMethod mthd, CPOperand in,
CPOperand out, long rows, long cols, int rpb, int cpb,
double maxValue, boolean replace, long seed, String opcode,
String istr) {
super(op, in, out, opcode, istr);
this.method = mthd;
this.rows = rows;
this.cols = cols;
this.rowsInBlock = rpb;
this.colsInBlock = cpb;
this.maxValue = maxValue;
this.replace = replace;
this.seed = seed;
}
public long getRows() {
return rows;
}
public void setRows(long rows) {
this.rows = rows;
}
public long getCols() {
return cols;
}
public void setCols(long cols) {
this.cols = cols;
}
public int getRowsInBlock() {
return rowsInBlock;
}
public void setRowsInBlock(int rowsInBlock) {
this.rowsInBlock = rowsInBlock;
}
public int getColsInBlock() {
return colsInBlock;
}
public void setColsInBlock(int colsInBlock) {
this.colsInBlock = colsInBlock;
}
public double getMinValue() {
return minValue;
}
public void setMinValue(double minValue) {
this.minValue = minValue;
}
public double getMaxValue() {
return maxValue;
}
public void setMaxValue(double maxValue) {
this.maxValue = maxValue;
}
public double getSparsity() {
return sparsity;
}
public void setSparsity(double sparsity) {
this.sparsity = sparsity;
}
public static RandSPInstruction parseInstruction(String str)
throws DMLRuntimeException
{
String[] s = InstructionUtils.getInstructionPartsWithValueType ( str );
String opcode = s[0];
DataGenMethod method = DataGenMethod.INVALID;
if ( opcode.equalsIgnoreCase(DataGen.RAND_OPCODE) ) {
method = DataGenMethod.RAND;
InstructionUtils.checkNumFields ( str, 12 );
}
else if ( opcode.equalsIgnoreCase(DataGen.SEQ_OPCODE) ) {
method = DataGenMethod.SEQ;
// 8 operands: rows, cols, rpb, cpb, from, to, incr, outvar
InstructionUtils.checkNumFields ( str, 8 );
}
else if ( opcode.equalsIgnoreCase(DataGen.SAMPLE_OPCODE) ) {
method = DataGenMethod.SAMPLE;
// 7 operands: range, size, replace, seed, rpb, cpb, outvar
InstructionUtils.checkNumFields ( str, 7 );
}
Operator op = null;
// output is specified by the last operand
CPOperand out = new CPOperand(s[s.length-1]);
if ( method == DataGenMethod.RAND ) {
long rows = -1, cols = -1;
if (!s[1].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
rows = Double.valueOf(s[1]).longValue();
}
if (!s[2].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
cols = Double.valueOf(s[2]).longValue();
}
int rpb = Integer.parseInt(s[3]);
int cpb = Integer.parseInt(s[4]);
double minValue = -1, maxValue = -1;
if (!s[5].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
minValue = Double.valueOf(s[5]).doubleValue();
}
if (!s[6].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
maxValue = Double.valueOf(s[6]).doubleValue();
}
double sparsity = -1;
if (!s[7].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
sparsity = Double.valueOf(s[7]);
}
long seed = DataGenOp.UNSPECIFIED_SEED;
if (!s[8].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
seed = Long.parseLong(s[8]);
}
String dir = s[9];
String pdf = s[10];
String pdfParams = s[11];
return new RandSPInstruction(op, method, null, out, rows, cols, rpb, cpb, minValue, maxValue, sparsity, seed, dir, pdf, pdfParams, opcode, str);
}
else if ( method == DataGenMethod.SEQ) {
// Example Instruction: CP:seq:11:1:1000:1000:1:0:-0.1:scratch_space/_p7932_192.168.1.120//_t0/:mVar1
long rows = Double.valueOf(s[1]).longValue();
long cols = Double.valueOf(s[2]).longValue();
int rpb = Integer.parseInt(s[3]);
int cpb = Integer.parseInt(s[4]);
double from, to, incr;
from = to = incr = Double.NaN;
if (!s[5].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
from = Double.valueOf(s[5]);
}
if (!s[6].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
to = Double.valueOf(s[6]);
}
if (!s[7].contains( Lop.VARIABLE_NAME_PLACEHOLDER)) {
incr = Double.valueOf(s[7]);
}
CPOperand in = null;
return new RandSPInstruction(op, method, in, out, rows, cols, rpb, cpb, from, to, incr, opcode, str);
}
else if ( method == DataGenMethod.SAMPLE)
{
// Example Instruction: SPARK:sample:10:100:false:1000:1000:_mVar2·MATRIX·DOUBLE
double max = 0;
long rows = 0, cols;
boolean replace = false;
if (!s[1].contains( Lop.VARIABLE_NAME_PLACEHOLDER))
max = Double.valueOf(s[1]);
if (!s[2].contains( Lop.VARIABLE_NAME_PLACEHOLDER))
rows = Double.valueOf(s[2]).longValue();
cols = 1;
if (!s[3].contains( Lop.VARIABLE_NAME_PLACEHOLDER))
replace = Boolean.valueOf(s[3]);
long seed = Long.parseLong(s[4]);
int rpb = Integer.parseInt(s[5]);
int cpb = Integer.parseInt(s[6]);
return new RandSPInstruction(op, method, null, out, rows, cols, rpb, cpb, max, replace, seed, opcode, str);
}
else
throw new DMLRuntimeException("Unrecognized data generation method: " + method);
}
@Override
public void processInstruction( ExecutionContext ec )
throws DMLRuntimeException
{
SparkExecutionContext sec = (SparkExecutionContext)ec;
//process specific datagen operator
switch( method ) {
case RAND: generateRandData(sec); break;
case SEQ: generateSequence(sec); break;
case SAMPLE: generateSample(sec); break;
default:
throw new DMLRuntimeException("Invalid datagen method: "+method);
}
}
private void generateRandData(SparkExecutionContext sec)
throws DMLRuntimeException
{
//step 1: generate pseudo-random seed (because not specified)
long lSeed = seed; //seed per invocation
if( lSeed == DataGenOp.UNSPECIFIED_SEED )
lSeed = DataGenOp.generateRandomSeed();
if( LOG.isTraceEnabled() )
LOG.trace("Process RandSPInstruction rand with seed = "+lSeed+".");
//step 2: potential in-memory rand operations if applicable
if( isMemAvail(rows, cols, sparsity, minValue, maxValue)
&& DMLScript.rtplatform != RUNTIME_PLATFORM.SPARK )
{
RandomMatrixGenerator rgen = LibMatrixDatagen.createRandomMatrixGenerator(
pdf, (int)rows, (int)cols, rowsInBlock, colsInBlock,
sparsity, minValue, maxValue, pdfParams);
MatrixBlock mb = MatrixBlock.randOperations(rgen, lSeed);
sec.setMatrixOutput(output.getName(), mb);
Statistics.decrementNoOfExecutedSPInst();
return;
}
//step 3: seed generation
JavaPairRDD<MatrixIndexes, Tuple2<Long, Long>> seedsRDD = null;
Well1024a bigrand = LibMatrixDatagen.setupSeedsForRand(lSeed);
LongStream nnz = LibMatrixDatagen.computeNNZperBlock(rows, cols, rowsInBlock, colsInBlock, sparsity);
PrimitiveIterator.OfLong nnzIter = nnz.iterator();
double totalSize = OptimizerUtils.estimatePartitionedSizeExactSparsity( rows, cols, rowsInBlock,
colsInBlock, rows*cols*sparsity); //overestimate for on disk, ensures hdfs block per partition
double hdfsBlkSize = InfrastructureAnalyzer.getHDFSBlockSize();
long numBlocks = new MatrixCharacteristics(rows, cols, rowsInBlock, colsInBlock).getNumBlocks();
long numColBlocks = (long)Math.ceil((double)cols/(double)colsInBlock);
//a) in-memory seed rdd construction
if( numBlocks < INMEMORY_NUMBLOCKS_THRESHOLD )
{
ArrayList<Tuple2<MatrixIndexes, Tuple2<Long, Long>>> seeds =
new ArrayList<Tuple2<MatrixIndexes, Tuple2<Long, Long>>>();
for( long i=0; i<numBlocks; i++ ) {
long r = 1 + i/numColBlocks;
long c = 1 + i%numColBlocks;
MatrixIndexes indx = new MatrixIndexes(r, c);
Long seedForBlock = bigrand.nextLong();
seeds.add(new Tuple2<MatrixIndexes, Tuple2<Long, Long>>(indx,
new Tuple2<Long, Long>(seedForBlock, nnzIter.nextLong())));
}
//for load balancing: degree of parallelism such that ~128MB per partition
int numPartitions = (int) Math.max(Math.min(totalSize/hdfsBlkSize, numBlocks), 1);
//create seeds rdd
seedsRDD = sec.getSparkContext().parallelizePairs(seeds, numPartitions);
}
//b) file-based seed rdd construction (for robustness wrt large number of blocks)
else
{
String path = LibMatrixDatagen.generateUniqueSeedPath(dir);
PrintWriter pw = null;
try
{
FileSystem fs = FileSystem.get(ConfigurationManager.getCachedJobConf());
pw = new PrintWriter(fs.create(new Path(path)));
StringBuilder sb = new StringBuilder();
for( long i=0; i<numBlocks; i++ ) {
sb.append(1 + i/numColBlocks);
sb.append(',');
sb.append(1 + i%numColBlocks);
sb.append(',');
sb.append(bigrand.nextLong());
sb.append(',');
sb.append(nnzIter.nextLong());
pw.println(sb.toString());
sb.setLength(0);
}
}
catch( IOException ex ) {
throw new DMLRuntimeException(ex);
}
finally {
IOUtilFunctions.closeSilently(pw);
}
//for load balancing: degree of parallelism such that ~128MB per partition
int numPartitions = (int) Math.max(Math.min(totalSize/hdfsBlkSize, numBlocks), 1);
//create seeds rdd
seedsRDD = sec.getSparkContext()
.textFile(path, numPartitions)
.mapToPair(new ExtractSeedTuple());
}
//step 4: execute rand instruction over seed input
JavaPairRDD<MatrixIndexes, MatrixBlock> out = seedsRDD
.mapToPair(new GenerateRandomBlock(rows, cols, rowsInBlock, colsInBlock,
sparsity, minValue, maxValue, pdf, pdfParams));
//step 5: output handling
MatrixCharacteristics mcOut = sec.getMatrixCharacteristics(output.getName());
if(!mcOut.dimsKnown(true)) {
//note: we cannot compute the nnz from sparsity because this would not reflect the
//actual number of non-zeros, except for extreme values of sparsity equals 0 or 1.
long lnnz = (sparsity==0 || sparsity==1) ? (long) (sparsity*rows*cols) : -1;
mcOut.set(rows, cols, rowsInBlock, colsInBlock, lnnz);
}
sec.setRDDHandleForVariable(output.getName(), out);
}
private void generateSequence(SparkExecutionContext sec)
throws DMLRuntimeException
{
//sanity check valid increment
if(seq_incr == 0) {
throw new DMLRuntimeException("ERROR: While performing seq(" + seq_from + "," + seq_to + "," + seq_incr + ")");
}
//handle default 1 to -1 for special case of from>to
seq_incr = LibMatrixDatagen.updateSeqIncr(seq_from, seq_to, seq_incr);
if( LOG.isTraceEnabled() )
LOG.trace("Process RandSPInstruction seq with seqFrom="+seq_from+", seqTo="+seq_to+", seqIncr"+seq_incr);
//step 1: offset generation
JavaRDD<Double> offsetsRDD = null;
long nnz = (long) Math.abs(Math.round((seq_to - seq_from)/seq_incr)) + 1;
double totalSize = OptimizerUtils.estimatePartitionedSizeExactSparsity( nnz, 1, rowsInBlock,
colsInBlock, nnz); //overestimate for on disk, ensures hdfs block per partition
double hdfsBlkSize = InfrastructureAnalyzer.getHDFSBlockSize();
long numBlocks = (long)Math.ceil(((double)nnz)/rowsInBlock);
//a) in-memory offset rdd construction
if( numBlocks < INMEMORY_NUMBLOCKS_THRESHOLD )
{
ArrayList<Double> offsets = new ArrayList<Double>();
for( long i=0; i<numBlocks; i++ ) {
double off = seq_from + seq_incr*i*rowsInBlock;
offsets.add(off);
}
//for load balancing: degree of parallelism such that ~128MB per partition
int numPartitions = (int) Math.max(Math.min(totalSize/hdfsBlkSize, numBlocks), 1);
//create offset rdd
offsetsRDD = sec.getSparkContext().parallelize(offsets, numPartitions);
}
//b) file-based offset rdd construction (for robustness wrt large number of blocks)
else
{
String path = LibMatrixDatagen.generateUniqueSeedPath(dir);
PrintWriter pw = null;
try
{
FileSystem fs = FileSystem.get(ConfigurationManager.getCachedJobConf());
pw = new PrintWriter(fs.create(new Path(path)));
for( long i=0; i<numBlocks; i++ ) {
double off = seq_from + seq_incr*i*rowsInBlock;
pw.println(off);
}
}
catch( IOException ex ) {
throw new DMLRuntimeException(ex);
}
finally {
IOUtilFunctions.closeSilently(pw);
}
//for load balancing: degree of parallelism such that ~128MB per partition
int numPartitions = (int) Math.max(Math.min(totalSize/hdfsBlkSize, numBlocks), 1);
//create seeds rdd
offsetsRDD = sec.getSparkContext()
.textFile(path, numPartitions)
.map(new ExtractOffsetTuple());
}
//sanity check number of non-zeros
if(nnz != rows && rows != -1) {
throw new DMLRuntimeException("Incorrect number of non-zeros: " + nnz + " != " + rows);
}
//step 2: execute seq instruction over offset input
JavaPairRDD<MatrixIndexes, MatrixBlock> out = offsetsRDD
.mapToPair(new GenerateSequenceBlock(rowsInBlock, seq_from, seq_to, seq_incr));
//step 3: output handling
MatrixCharacteristics mcOut = sec.getMatrixCharacteristics(output.getName());
if(!mcOut.dimsKnown()) {
mcOut.set(nnz, 1, rowsInBlock, colsInBlock, nnz);
}
sec.setRDDHandleForVariable(output.getName(), out);
}
/**
* Helper function to construct a sample.
*
* @param sec spark execution context
* @throws DMLRuntimeException if DMLRuntimeException occurs
*/
private void generateSample(SparkExecutionContext sec)
throws DMLRuntimeException
{
if ( maxValue < rows && !replace )
throw new DMLRuntimeException("Sample (size=" + rows + ") larger than population (size=" + maxValue + ") can only be generated with replacement.");
if( LOG.isTraceEnabled() )
LOG.trace("Process RandSPInstruction sample with range="+ maxValue +", size="+ rows +", replace="+ replace + ", seed=" + seed);
// sampling rate that guarantees a sample of size >= sampleSizeLowerBound 99.99% of the time.
double fraction = SamplingUtils.computeFractionForSampleSize((int)rows, UtilFunctions.toLong(maxValue), replace);
Well1024a bigrand = LibMatrixDatagen.setupSeedsForRand(seed);
// divide the population range across numPartitions by creating SampleTasks
double hdfsBlockSize = InfrastructureAnalyzer.getHDFSBlockSize();
long outputSize = MatrixBlock.estimateSizeDenseInMemory(rows,1);
int numPartitions = (int) Math.ceil((double)outputSize/hdfsBlockSize);
long partitionSize = (long) Math.ceil(maxValue/numPartitions);
ArrayList<SampleTask> offsets = new ArrayList<SampleTask>();
long st = 1;
while ( st <= maxValue ) {
SampleTask s = new SampleTask();
s.range_start = st;
s.seed = bigrand.nextLong();
offsets.add(s);
st = st + partitionSize;
}
JavaRDD<SampleTask> offsetRDD = sec.getSparkContext().parallelize(offsets, numPartitions);
// Construct the sample in a distributed manner
JavaRDD<Double> rdd = offsetRDD.flatMap( (new GenerateSampleBlock(replace, fraction, (long)maxValue, partitionSize)) );
// Randomize the sampled elements
JavaRDD<Double> randomizedRDD = rdd.mapToPair(new AttachRandom()).sortByKey().values();
// Trim the sampled list to required size & attach matrix indexes to randomized elements
JavaPairRDD<MatrixIndexes, MatrixCell> miRDD = randomizedRDD
.zipWithIndex()
.filter( new TrimSample(rows) )
.mapToPair( new Double2MatrixCell() );
MatrixCharacteristics mcOut = new MatrixCharacteristics(rows, 1, rowsInBlock, colsInBlock, rows);
// Construct BinaryBlock representation
JavaPairRDD<MatrixIndexes, MatrixBlock> mbRDD =
RDDConverterUtils.binaryCellToBinaryBlock(sec.getSparkContext(), miRDD, mcOut, true);
MatrixCharacteristics retDims = sec.getMatrixCharacteristics(output.getName());
retDims.setNonZeros(rows);
sec.setRDDHandleForVariable(output.getName(), mbRDD);
}
/**
* Private class that defines a sampling task.
* The task produces a portion of sample from range [range_start, range_start+partitionSize].
*
*/
private static class SampleTask implements Serializable
{
private static final long serialVersionUID = -725284524434342939L;
long seed;
long range_start;
public String toString() { return "(" + seed + "," + range_start +")"; }
}
/**
* Main class to perform distributed sampling.
*
* Each invocation of this FlatMapFunction produces a portion of sample
* to be included in the final output.
*
* The input range from which the sample is constructed is given by
* [range_start, range_start+partitionSize].
*
* When replace=TRUE, the sample is produced by generating Poisson
* distributed counts (denoting the number of occurrences) for each
* element in the input range.
*
* When replace=FALSE, the sample is produced by comparing a generated
* random number against the required sample fraction.
*
* In the special case of fraction=1.0, the permutation of the input
* range is computed, simply by creating RDD of elements from input range.
*
*/
private static class GenerateSampleBlock implements FlatMapFunction<SampleTask, Double>
{
private static final long serialVersionUID = -8211490954143527232L;
private double _frac;
private boolean _replace;
private long _maxValue, _partitionSize;
GenerateSampleBlock(boolean replace, double frac, long max, long psize)
{
_replace = replace;
_frac = frac;
_maxValue = max;
_partitionSize = psize;
}
@Override
public Iterator<Double> call(SampleTask t)
throws Exception {
long st = t.range_start;
long end = Math.min(t.range_start+_partitionSize, _maxValue);
ArrayList<Double> retList = new ArrayList<Double>();
if ( _frac == 1.0 )
{
for(long i=st; i <= end; i++)
retList.add((double)i);
}
else
{
if(_replace)
{
PoissonDistribution pdist = new PoissonDistribution( (_frac > 0.0 ? _frac :1.0) );
for(long i=st; i <= end; i++)
{
int count = pdist.sample();
while(count > 0) {
retList.add((double)i);
count--;
}
}
}
else
{
Random rnd = new Random(t.seed);
for(long i=st; i <=end; i++)
if ( rnd.nextDouble() < _frac )
retList.add((double) i);
}
}
return retList.iterator();
}
}
/**
* Function that filters the constructed sample contain to required number of elements.
*
*/
private static class TrimSample implements Function<Tuple2<Double,Long>, Boolean> {
private static final long serialVersionUID = 6773370625013346530L;
long _max;
TrimSample(long max) {
_max = max;
}
@Override
public Boolean call(Tuple2<Double, Long> v1) throws Exception {
return ( v1._2 < _max );
}
}
/**
* Function to convert JavaRDD of Doubles to {@code JavaPairRDD<MatrixIndexes, MatrixCell>}
*
*/
private static class Double2MatrixCell implements PairFunction<Tuple2<Double, Long>, MatrixIndexes, MatrixCell>
{
private static final long serialVersionUID = -2125669746624320536L;
@Override
public Tuple2<MatrixIndexes, MatrixCell> call(Tuple2<Double, Long> t)
throws Exception {
long rowID = t._2()+1;
MatrixIndexes mi = new MatrixIndexes(rowID, 1);
MatrixCell mc = new MatrixCell(t._1());
return new Tuple2<MatrixIndexes, MatrixCell>(mi, mc);
}
}
/**
* Pair function to attach a random number as a key to input JavaRDD.
* The produced JavaPairRDD is subsequently used to randomize the sampled elements.
*
*/
private static class AttachRandom implements PairFunction<Double, Double, Double> {
private static final long serialVersionUID = -7508858192367406554L;
Random r = null;
AttachRandom() {
r = new Random();
}
@Override
public Tuple2<Double, Double> call(Double t) throws Exception {
return new Tuple2<Double,Double>( r.nextDouble(), t );
}
}
private static class ExtractSeedTuple implements PairFunction<String, MatrixIndexes, Tuple2<Long,Long>> {
private static final long serialVersionUID = 3973794676854157101L;
@Override
public Tuple2<MatrixIndexes, Tuple2<Long, Long>> call(String arg)
throws Exception
{
String[] parts = IOUtilFunctions.split(arg, ",");
MatrixIndexes ix = new MatrixIndexes(
Long.parseLong(parts[0]), Long.parseLong(parts[1]));
Tuple2<Long,Long> seed = new Tuple2<Long,Long>(
Long.parseLong(parts[2]), Long.parseLong(parts[3]));
return new Tuple2<MatrixIndexes, Tuple2<Long, Long>>(ix,seed);
}
}
private static class ExtractOffsetTuple implements Function<String, Double> {
private static final long serialVersionUID = -3980257526545002552L;
@Override
public Double call(String arg) throws Exception {
return Double.parseDouble(arg);
}
}
private static class GenerateRandomBlock implements PairFunction<Tuple2<MatrixIndexes, Tuple2<Long, Long> >, MatrixIndexes, MatrixBlock>
{
private static final long serialVersionUID = 1616346120426470173L;
private long _rlen;
private long _clen;
private int _brlen;
private int _bclen;
private double _sparsity;
private double _min;
private double _max;
private String _pdf;
private String _pdfParams;
public GenerateRandomBlock(long rlen, long clen, int brlen, int bclen, double sparsity, double min, double max, String pdf, String pdfParams) {
_rlen = rlen;
_clen = clen;
_brlen = brlen;
_bclen = bclen;
_sparsity = sparsity;
_min = min;
_max = max;
_pdf = pdf;
_pdfParams = pdfParams;
}
@Override
public Tuple2<MatrixIndexes, MatrixBlock> call(Tuple2<MatrixIndexes, Tuple2<Long, Long>> kv)
throws Exception
{
//compute local block size:
MatrixIndexes ix = kv._1();
long blockRowIndex = ix.getRowIndex();
long blockColIndex = ix.getColumnIndex();
int lrlen = UtilFunctions.computeBlockSize(_rlen, blockRowIndex, _brlen);
int lclen = UtilFunctions.computeBlockSize(_clen, blockColIndex, _bclen);
long seed = kv._2._1;
long blockNNZ = kv._2._2;
MatrixBlock blk = new MatrixBlock();
RandomMatrixGenerator rgen = LibMatrixDatagen.createRandomMatrixGenerator(
_pdf, lrlen, lclen, lrlen, lclen,
_sparsity, _min, _max, _pdfParams );
blk.randOperationsInPlace(rgen, LongStream.of(blockNNZ), null, seed);
return new Tuple2<MatrixIndexes, MatrixBlock>(kv._1, blk);
}
}
private static class GenerateSequenceBlock implements PairFunction<Double, MatrixIndexes, MatrixBlock>
{
private static final long serialVersionUID = 5779681055705756965L;
private int _brlen;
private double _global_seq_start;
private double _global_seq_end;
private double _seq_incr;
public GenerateSequenceBlock(int brlen, double global_seq_start, double global_seq_end, double seq_incr) {
_brlen = brlen;
_global_seq_start = global_seq_start;
_global_seq_end = global_seq_end;
_seq_incr = seq_incr;
}
@Override
public Tuple2<MatrixIndexes, MatrixBlock> call(Double seq_from)
throws Exception
{
double seq_to;
if(_seq_incr > 0) {
seq_to = Math.min(_global_seq_end, seq_from + _seq_incr*(_brlen-1));
}
else {
seq_to = Math.max(_global_seq_end, seq_from + _seq_incr*(_brlen+1));
}
long globalRow = (long) ((seq_from-_global_seq_start)/_seq_incr + 1);
long rowIndex = (long) Math.ceil((double)globalRow/(double)_brlen);
MatrixIndexes indx = new MatrixIndexes(rowIndex, 1);
MatrixBlock blk = MatrixBlock.seqOperations(seq_from, seq_to, _seq_incr);
return new Tuple2<MatrixIndexes, MatrixBlock>(indx, blk);
}
}
/**
* This will check if there is sufficient memory locally.
*
* @param lRows number of rows
* @param lCols number of columns
* @param sparsity sparsity ratio
* @param min minimum value
* @param max maximum value
* @return
*/
private boolean isMemAvail(long lRows, long lCols, double sparsity, double min, double max)
{
double size = (min == 0 && max == 0) ? OptimizerUtils.estimateSizeEmptyBlock(rows, cols):
OptimizerUtils.estimateSizeExactSparsity(rows, cols, sparsity);
return ( OptimizerUtils.isValidCPDimensions(rows, cols)
&& OptimizerUtils.isValidCPMatrixSize(rows, cols, sparsity)
&& size < OptimizerUtils.getLocalMemBudget() );
}
}
| iyounus/incubator-systemml | src/main/java/org/apache/sysml/runtime/instructions/spark/RandSPInstruction.java | Java | apache-2.0 | 28,815 |
--{{{ HEROES REBORN / CLIENT COMMANDS
--{{{ READ info.lua
reb.ABOUT.commands = {
{"heroes", level = 0, desc = "Heroes menu", func = "cl.popHeroes"};
{"myheroes", level = 0, desc = "My heroes menu", func = "cl.popMyHeroes"};
{"clearheroes", level = 0, desc = "Reset heroes", func = "cl.delHeroes"};
{"getstats", "whatstats", level = 0, desc = "Show player stats", func = "cl.getStats"};
{"inform", level = 0, desc = "Ge hero description", func = "cl.heroInfo"};
{"reset", level = 0, desc = "Reset stats", concat = 1, func = "cl.reset"};
{"shop", level = 0, desc = "Shop", func = "cl.popShop"};
{"inventory", level = 0, desc = "Inventory", func = "cl.popInv"};
{"market", level = 0, desc = "Market", func = "cl.popMark"};
{"reborn", level = 0, desc = "Mod info", func = "cl.info"};
} | Yankwerks/reborn | sys/lua/reborn/commands.lua | Lua | apache-2.0 | 792 |
'use strict';
module.exports = function (grunt) {
var appPath = './app/';
var tempPath = './tmp/';
var resourcePath = '../src/main/resources/';
var javaAppArtifactLocation = '../build/libs/';
var javaAppPort = 8080;
var globalConfig = {
generatedAssetDestination: '../src/main/resources/static/',
buildDestination: '../build/resources/main/public/gen/',
resourceDestination: resourcePath,
appPath: appPath,
tempPath: tempPath,
jsPath: appPath + 'js/',
partialsPath: appPath + 'partials/',
lessPath: appPath + 'less/',
};
grunt.initConfig({
globalConfig: globalConfig,
availabletasks: {
tasks: {}
},
uglify: {
manam: {
options: {
compress: {
drop_debugger: false
},
mangle: false,
preserveComments: 'all',
beautify: true,
ASCIIOnly: true,
sourceMap: true,
sourceMapName: '<%= globalConfig.generatedAssetDestination %>manam.js.map',
sourceMapIncludeSources: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>manam.js': [
'<%= globalConfig.jsPath %>ManamCommon.js',
'<%= globalConfig.jsPath %>ManamApp.js',
'<%= globalConfig.jsPath %>manam/**/*.js',
'<%= globalConfig.jsPath %>services/**/*.js',
'<%= globalConfig.jsPath %>repositories/**/*.js',
'<%= globalConfig.jsPath %>directives/**/*.js',
'<%= globalConfig.jsPath %>filters/**/*.js',
'<%= globalConfig.tempPath %>partials.js'
]
}
},
thirdParty: {
options: {
mangle: false,
preserveComments: 'all',
beautify: true,
ASCIIOnly: true,
sourceMap: true,
sourceMapName: '<%= globalConfig.generatedAssetDestination %>thirdParty.js.map',
sourceMapIncludeSources: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>thirdParty.js': [require('./third-party-app-dependencies')]
}
}
},
html2js: {
options: {
module: 'partials',
base: '<%= globalConfig.partialsPath %>'
},
main: {
src: ['<%= globalConfig.partialsPath %>**/*.html'],
dest: '<%= globalConfig.tempPath %>partials.js'
}
},
less: {
manam: {
options: {
paths: ['<%= globalConfig.lessPath %>'],
sourceMap: true,
sourceMapFileInline: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>manam.css': '<%= globalConfig.lessPath %>manam.less'
}
}
},
copy: {
generatedFilesToBuild: {
expand: true,
src: ['**/*'],
cwd: '<%= globalConfig.generatedAssetDestination %>',
dest: '<%= globalConfig.buildDestination %>'
}
}
});
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-available-tasks');
grunt.loadNpmTasks('grunt-html2js');
grunt.registerTask('clean', function () {
grunt.file.delete(globalConfig.buildDestination, {force: true});
});
grunt.registerTask('default', ['clean', 'html2js', 'uglify', 'copy:generatedFilesToBuild']);
grunt.registerTask('task', ['availabletasks']);
} | ManamFoundation/manamfoundation | frontend/Gruntfile.js | JavaScript | apache-2.0 | 3,258 |
/*
Copyright 2007-2011 WebDriver committers
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.openqa.grid.web.servlet.handler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.grid.internal.GridException;
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSession;
import org.openqa.grid.internal.listeners.Prioritizer;
import org.openqa.grid.internal.listeners.TestSessionListener;
import org.openqa.grid.web.Hub;
/**
* Base stuff to handle the request coming from a remote. Ideally, there should
* be only 1 concrete class, but to support both legacy selenium1 and web
* driver, 2 classes are needed.
*
* {@link Selenium1RequestHandler} for the part specific to selenium1 protocol
* {@link WebDriverRequestHandler} for the part specific to webdriver protocol
*
*
*/
public abstract class RequestHandler implements Comparable<RequestHandler> {
private Registry registry;
private HttpServletRequest request;
private HttpServletResponse response;
private String body = null;
private boolean bodyHasBeenRead = false;
private Map<String, Object> desiredCapabilities = null;
private RequestType requestType = null;
private TestSession session = null;
private long created;
private boolean showWarning = true;
private final Lock lock = new ReentrantLock();
private final Condition sessionHasBeenAssigned = lock.newCondition();
private static final Logger log = Logger.getLogger(RequestHandler.class.getName());
/**
* Detect what kind of protocol ( selenium1 vs webdriver ) is used by the
* request and create the associated handler.
*
* @param request
* @param response
* @param registry
* @return
*/
public static RequestHandler createHandler(HttpServletRequest request, HttpServletResponse response, Registry registry) {
if (isSeleniumProtocol(request)) {
return new Selenium1RequestHandler(request, response, registry);
} else {
return new WebDriverRequestHandler(request, response, registry);
}
}
protected RequestHandler(HttpServletRequest request, HttpServletResponse response, Registry registry) {
this.request = request;
this.response = response;
this.registry = registry;
this.created = System.currentTimeMillis();
}
/**
*
* @return the type of the request.
*/
public abstract RequestType extractRequestType();
/**
* Extract the session from the request. This only works for a request that
* has a session already assigned. It shouldn't be called for a new session
* request.
*
* @return the external session id sent by the remote. Null is the session
* cannot be found.
*/
public abstract String extractSession();
/**
* Parse the request to extract the desiredCapabilities. For non web driver
* protocol ( selenium1 ) some mapping will be necessary
*
* @return the desired capabilities requested by the client.
*/
public abstract Map<String, Object> extractDesiredCapability();
/**
* Forward the new session request to the TestSession that has been
* assigned, and parse the response to extract and return the external key
* assigned by the remote.
*
* @param session
* @return the external key sent by the remote, null is something went
* wrong.
* @throws IOException
*/
public abstract String forwardNewSessionRequest(TestSession session);
protected void forwardRequest(TestSession session, RequestHandler handler) throws IOException {
if (bodyHasBeenRead) {
session.forward(request, response, getRequestBody(), false);
} else {
session.forward(request, response);
}
}
/**
* forwards the request to the remote, allocating / releasing the resources
* if necessary.
*/
public void process() {
switch (getRequestType()) {
case START_SESSION:
handleNewSession();
break;
case REGULAR:
case STOP_SESSION:
session = getSession();
if (session == null) {
throw new GridException("Session not available - " + registry.getActiveSessions());
}
try {
forwardRequest(session, this);
} catch (Throwable t) {
log.log(Level.WARNING, "cannot forward the request " + t.getMessage(), t);
session.terminate();
throw new GridException("cannot forward the request " + t.getMessage(), t);
}
if (getRequestType() == RequestType.STOP_SESSION) {
session.terminate();
}
break;
default:
throw new RuntimeException("NI");
}
}
/**
* allocate a new TestSession for the test, forward the request and update
* the resource used.
*/
private void handleNewSession() {
// registry.addNewSessionRequest(this);
try {
lock.lock();
// in the lock on purpose. Need to be stuck on the await first, so
// that the signal of bindSession is done AFTER await is in waiting
// mode.
// if addNewSessionRequest(this) is out of the lock and everythung
// goes fast, there is a chance that bindSession get the lock first,
// signal, and only after that await will be reached, never
// signalled
registry.addNewSessionRequest(this);
// Maintain compatibility with Grid 1.x, which had the ability to
// specify how long to wait before canceling
// a request.
if (registry.getNewSessionWaitTimeout() != -1) {
long startTime = System.currentTimeMillis();
sessionHasBeenAssigned.await(registry.getNewSessionWaitTimeout(), TimeUnit.MILLISECONDS);
long endTime = System.currentTimeMillis();
if ((session == null) && ((endTime - startTime) >= registry.getNewSessionWaitTimeout())) {
throw new RuntimeException("Request timed out waiting for a node to become available.");
}
} else {
// Wait until a proxy becomes available to handle the request.
sessionHasBeenAssigned.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
if (session == null) {
throw new RuntimeException("implementation error or you closed the grid while some tests were still queued on it.");
}
// if the session is on a proxy that implements BeforeSessionListener,
// run the listener first.
RemoteProxy p = session.getSlot().getProxy();
if (p instanceof TestSessionListener) {
if (showWarning && p.getMaxNumberOfConcurrentTestSessions() != 1) {
showWarning = false;
log.warning("WARNING : using a beforeSession on a proxy that can support multiple tests is risky.");
}
try {
((TestSessionListener) p).beforeSession(session);
} catch (Throwable t) {
log.severe("Error running the beforeSessionListener : " + t.getMessage());
t.printStackTrace();
session.terminate();
}
}
String externalKey = forwardNewSessionRequest(session);
if (externalKey == null) {
session.terminate();
// TODO (kmenard 04/10/11): We should indicate what the requested
// session type is.
throw new GridException("Error getting a new session from the remote." + registry.getAllProxies());
} else {
session.setExternalKey(externalKey);
}
}
/**
* return true is the request is using the selenium1 protocol, false if
* that's a web driver protocol.
*
* @param request
* @return
*/
private static boolean isSeleniumProtocol(HttpServletRequest request) {
return "/selenium-server/driver".equals(request.getServletPath());
}
/**
* reads the input stream of the request and returns its content.
*
* @return
*/
protected String getRequestBody() {
if (!bodyHasBeenRead) {
bodyHasBeenRead = true;
StringBuilder sb = new StringBuilder();
String line;
try {
InputStream is = request.getInputStream();
if (is == null) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
// TODO freynaud bug ?
sb.append(line);/* .append("\n"); */
}
is.close();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
body = sb.toString();
}
return body;
}
/**
* the HttpServletRequest this hanlder is processing.
*
* @return
*/
public HttpServletRequest getRequest() {
return request;
}
/**
* the HttpServletResponse the handler is writing to.
*
* @return
*/
public HttpServletResponse getResponse() {
return response;
}
public Map<String, Object> getDesiredCapabilities() {
if (desiredCapabilities == null) {
desiredCapabilities = extractDesiredCapability();
}
return desiredCapabilities;
}
protected void setDesiredCapabilities(Map<String, Object> desiredCapabilities) {
this.desiredCapabilities = desiredCapabilities;
}
public int compareTo(RequestHandler o) {
Prioritizer prioritizer = registry.getPrioritizer();
if (prioritizer != null) {
return prioritizer.compareTo(this.getDesiredCapabilities(), o.getDesiredCapabilities());
} else {
return 0;
}
}
protected RequestType getRequestType() {
if (requestType == null) {
requestType = extractRequestType();
}
return requestType;
}
protected void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
protected void setSession(TestSession session) {
this.session = session;
}
public void bindSession(TestSession session) {
try {
lock.lock();
this.session = session;
sessionHasBeenAssigned.signalAll();
} finally {
lock.unlock();
}
}
protected TestSession getSession() {
if (session == null) {
String externalKey = extractSession();
session = registry.getSession(externalKey);
}
return session;
}
/**
* return the session from the server ( = opaque handle used by the server
* to determine where to route session-specific commands fro mthe JSON wire
* protocol ). will be null until the request has been processed.
*
* @return
*/
public String getServerSession() {
if (session == null) {
return null;
} else {
return session.getExternalKey();
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("session :" + session + " , ");
b.append("cap : " + getDesiredCapabilities());
b.append("\n");
return b.toString();
}
public String debug() {
StringBuilder b = new StringBuilder();
b.append("\nmethod: " + request.getMethod());
b.append("\npathInfo: " + request.getPathInfo());
b.append("\nuri: " + request.getRequestURI());
b.append("\ncontent :" + getRequestBody());
return b.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((session == null) ? 0 : session.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RequestHandler other = (RequestHandler) obj;
if (session == null) {
if (other.session != null)
return false;
} else if (!session.equals(other.session))
return false;
return true;
}
public long getCreated() {
return created;
}
public Registry getRegistry() {
return registry;
}
}
| akiellor/selenium | java/server/src/org/openqa/grid/web/servlet/handler/RequestHandler.java | Java | apache-2.0 | 12,534 |
package com.jjc.mailshop.pojo;
import java.util.Date;
public class Category {
private Integer id;
private Integer parentId;
private String name;
private Boolean status;
private Integer sortOrder;
private Date createTime;
private Date updateTime;
public Category(Integer id, Integer parentId, String name, Boolean status, Integer sortOrder, Date createTime, Date updateTime) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.status = status;
this.sortOrder = sortOrder;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Category() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | aohanyao/CodeMall | code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/pojo/Category.java | Java | apache-2.0 | 1,761 |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>CommandService</title>
<link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../../";</script><script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script><link href="../../../styles/style.css" rel="Stylesheet"><link href="../../../styles/logo-styles.css" rel="Stylesheet"><link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"><link href="../../../styles/main.css" rel="Stylesheet"><script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script><script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script><script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script><script type="text/javascript" src="../../../scripts/main.js" async="async"></script> </head>
<body>
<div id="container">
<div id="leftColumn"><a href="../../../index.html">
<div id="logo"></div>
</a>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="blockball-root::com.github.shynixn.blockball.api.business.service/CommandService///PointingToDeclaration//1513497539">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">blockball-root</a>/<a href="../index.html">com.github.shynixn.blockball.api.business.service</a>/<a href="index.html">CommandService</a></div>
<div class="pull-right d-flex">
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>Command</span><wbr></wbr><span><span>Service</span></span></h1>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":generateJavaDocPages/main"><div class="symbol monospace">interface <a href="index.html">CommandService</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div><p class="paragraph">Created by Shynixn 2019.</p><p>
Version 1.2
<p>
MIT License
<p>
Copyright (c) 2019 by Shynixn
<p>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
<p>
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
<p>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.</div></div>
</div>
<div class="tabbedcontent">
<div class="tabs-section" tabs-section="tabs-section"><button class="section-tab" data-active="" data-togglable="Functions">Functions</button></div>
<div class="tabs-section-body">
<h2 class="">Functions</h2>
<div class="table" data-togglable="Functions"><a data-name="-716158048%2FFunctions%2F1513497539" anchor-label="registerCommandExecutor" id="-716158048%2FFunctions%2F1513497539" data-filterable-set=":generateJavaDocPages/main"></a>
<div class="table-row" data-filterable-current=":generateJavaDocPages/main" data-filterable-set=":generateJavaDocPages/main">
<div class="main-subrow keyValue ">
<div class=""><span class="inline-flex"><a href="register-command-executor.html"><span>register</span><wbr></wbr><span>Command</span><wbr></wbr><span><span>Executor</span></span></a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="-716158048%2FFunctions%2F1513497539"></span>
<div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div>
</span></span></div>
<div>
<div class="title"><div class="divergent-group" data-filterable-current=":generateJavaDocPages/main" data-filterable-set=":generateJavaDocPages/main"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":generateJavaDocPages/main"><div class="symbol monospace">abstract fun <a href="register-command-executor.html">registerCommandExecutor</a>(command: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html">String</a>, commandExecutor: <a href="../../com.github.shynixn.blockball.api.business.executor/-command-executor/index.html">CommandExecutor</a>)<span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<div class="brief "><p class="paragraph">Registers a command executor from a pre defined <a href="register-command-executor.html">command</a> with gets executed by the <a href="register-command-executor.html">commandExecutor</a>.</p></div></div>
<div class="divergent-group" data-filterable-current=":generateJavaDocPages/main" data-filterable-set=":generateJavaDocPages/main"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":generateJavaDocPages/main"><div class="symbol monospace">abstract fun <a href="register-command-executor.html">registerCommandExecutor</a>(commandConfiguration: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html">Map</a><<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html">String</a>, <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html">String</a>>, commandExecutor: <a href="../../com.github.shynixn.blockball.api.business.executor/-command-executor/index.html">CommandExecutor</a>)<span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<div class="brief "><p class="paragraph">Registers a command executor from new <a href="register-command-executor.html">commandConfiguration</a> with gets executed by the <a href="register-command-executor.html">commandExecutor</a>.</p></div></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| Shynixn/BlockBall | docs/apidocs/blockball-root/com.github.shynixn.blockball.api.business.service/-command-service/index.html | HTML | apache-2.0 | 8,145 |
# Diodonta coronata Nutt. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Diodonta/Diodonta coronata/README.md | Markdown | apache-2.0 | 173 |
# Monsonia senegalensis Guill. & Perr. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Monsonia/Monsonia senegalensis/README.md | Markdown | apache-2.0 | 186 |
# Strasseria vincae M.T. Lucas & Sousa da Câmara SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Agron. lusit. 16(2): 97 (1954)
#### Original name
Strasseria vincae M.T. Lucas & Sousa da Câmara
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Strasseria/Strasseria vincae/README.md | Markdown | apache-2.0 | 249 |
# Toxicodendron orientale Greene SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Anacardiaceae/Toxicodendron/Toxicodendron orientale/README.md | Markdown | apache-2.0 | 180 |
# Pithecellobium zuliaense Pittier SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Pithecellobium/Pithecellobium zuliaense/README.md | Markdown | apache-2.0 | 182 |
# Shionodiscus A.J.Alverson, S.H.Kang & E.C.Theriot, 2006 GENUS
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Bacillariophyta/Bacillariophyceae/Thalassiosiraceae/Shionodiscus/README.md | Markdown | apache-2.0 | 204 |
# Noronhia comorensis S.Moore SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Oleaceae/Noronhia/Noronhia comorensis/README.md | Markdown | apache-2.0 | 177 |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.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 org.pentaho.di.trans.steps.webservices;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.trans.steps.webservices.wsdl.XsdType;
public class WebServiceField implements Cloneable
{
private String name;
private String wsName;
private String xsdType;
public WebServiceField clone() {
try {
return (WebServiceField) super.clone();
}
catch(CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
@Override
public String toString() {
return name!=null ? name : super.toString();
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getWsName()
{
return wsName;
}
public void setWsName(String wsName)
{
this.wsName = wsName;
}
public String getXsdType()
{
return xsdType;
}
public void setXsdType(String xsdType)
{
this.xsdType = xsdType;
}
public int getType()
{
return XsdType.xsdTypeToKettleType(xsdType);
}
/**
* We consider a field to be complex if it's a type we don't recognize.
* In that case, we will give back XML as a string.
* @return
*/
public boolean isComplex() {
return getType()==ValueMetaInterface.TYPE_NONE;
}
}
| yintaoxue/read-open-source-code | kettle4.3/src/org/pentaho/di/trans/steps/webservices/WebServiceField.java | Java | apache-2.0 | 2,329 |
/*
* Copyright 2014 Boleslav Bobcik
*
* 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 cz.auderis.tools.config;
import com.google.common.collect.ImmutableMap;
import cz.auderis.tools.config.annotation.ConfigurationEntryName;
import cz.auderis.tools.config.annotation.DefaultConfigurationEntryValue;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PrimitiveDataObjectTest {
public static interface PrimitiveDataObject {
@ConfigurationEntryName(name = "boolItem")
Boolean boolItemObj();
boolean boolItem();
@ConfigurationEntryName(name = "byteItem")
Byte byteItemObj();
byte byteItem();
@ConfigurationEntryName(name = "shortItem")
Short shortItemObj();
short shortItem();
@ConfigurationEntryName(name = "intItem")
Integer intItemObj();
int intItem();
@ConfigurationEntryName(name = "longItem")
Long longItemObj();
long longItem();
@ConfigurationEntryName(name = "floatItem")
Float floatItemObj();
float floatItem();
@ConfigurationEntryName(name = "doubleItem")
Double doubleItemObj();
double doubleItem();
}
public static interface PrimitiveDataObjectWithDefaults {
@DefaultConfigurationEntryValue("true") boolean boolItem();
@DefaultConfigurationEntryValue("12") byte byteItem();
@DefaultConfigurationEntryValue("123") short shortItem();
@DefaultConfigurationEntryValue("1234") int intItem();
@DefaultConfigurationEntryValue("12345") long longItem();
@DefaultConfigurationEntryValue("123.45") float floatItem();
@DefaultConfigurationEntryValue("12345.6789") double doubleItem();
}
private static final double DELTA_DOUBLE = 0.00000001D;
private static final float DELTA_FLOAT = 0.00000001F;
@Test
public void shouldReturnCorrectBoolean() throws Exception {
final boolean[] points = {true, false};
for (boolean point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("boolItem", point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.boolItem());
assertTrue(point == testObject.boolItemObj());
}
}
@Test
public void shouldReturnCorrectBooleanFromText() throws Exception {
final boolean[] points = {true, false};
for (boolean point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("boolItem", Boolean.toString(point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.boolItem());
assertTrue(point == testObject.boolItemObj());
}
}
@Test
public void shouldReturnCorrectByte() throws Exception {
final int[] points = {0, 1, -1, Byte.MIN_VALUE, Byte.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("byteItem", (byte) point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(
data, PrimitiveDataObject.class, getClass().getClassLoader()
);
assertTrue((byte) point == testObject.byteItem());
assertTrue((byte) point == testObject.byteItemObj());
}
}
@Test
public void shouldReturnCorrectByteFromText() throws Exception {
final int[] points = {0, 1, -1, Byte.MIN_VALUE, Byte.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("byteItem", Byte.toString((byte) point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue((byte) point == testObject.byteItem());
assertTrue((byte) point == testObject.byteItemObj());
}
}
@Test
public void shouldReturnCorrectShort() throws Exception {
final int[] points = {0, 1, -1, Byte.MIN_VALUE, Byte.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("shortItem", (short) point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue((short) point == testObject.shortItem());
assertTrue((short) point == testObject.shortItemObj());
}
}
@Test
public void shouldReturnCorrectShortFromText() throws Exception {
final int[] points = {0, 1, -1, Byte.MIN_VALUE, Byte.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("shortItem", Short.toString((short) point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue((short) point == testObject.shortItem());
assertTrue((short) point == testObject.shortItemObj());
}
}
@Test
public void shouldReturnCorrectInt() throws Exception {
final int[] points = {0, 1, -1, 256, -256, Integer.MIN_VALUE, Integer.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("intItem", point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.intItem());
assertTrue(point == testObject.intItemObj());
}
}
@Test
public void shouldReturnCorrectIntFromText() throws Exception {
final int[] points = {0, 1, -1, 256, -256, Integer.MIN_VALUE, Integer.MAX_VALUE};
for (int point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("intItem", Integer.toString(point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.intItem());
assertTrue(point == testObject.intItemObj());
}
}
@Test
public void shouldReturnCorrectLong() throws Exception {
final long[] points = {0L, 1L, -1L, 256L, -256L, Long.MIN_VALUE, Long.MAX_VALUE};
for (long point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("longItem", point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.longItem());
assertTrue(point == testObject.longItemObj());
}
}
@Test
public void shouldReturnCorrectLongFromText() throws Exception {
final long[] points = {0L, 1L, -1L, 256L, -256L, Long.MIN_VALUE, Long.MAX_VALUE};
for (long point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("longItem", Long.toString(point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(point == testObject.longItem());
assertTrue(point == testObject.longItemObj());
}
}
@Test
public void shouldReturnCorrectDouble() throws Exception {
final double[] points = {0.0D, 1.0D, -1.0D, Math.PI, -Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
for (double point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("doubleItem", point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(Double.doubleToLongBits(point) == Double.doubleToLongBits(testObject.doubleItem()));
assertTrue(Double.doubleToLongBits(point) == Double.doubleToLongBits(testObject.doubleItemObj()));
}
}
@Test
public void shouldReturnCorrectDoubleFromText() throws Exception {
final double[] points = {0.0D, 1.0D, -1.0D, Math.PI, -Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
for (double point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("doubleItem", Double.toString(point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertEquals(point, testObject.doubleItem(), DELTA_DOUBLE);
assertEquals(point, testObject.doubleItemObj(), DELTA_DOUBLE);
}
}
@Test
public void shouldReturnCorrectFloat() throws Exception {
final float[] points = {0.0F, 1.0F, -1.0F, (float) Math.PI, (float) -Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
for (float point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("floatItem", point);
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(Float.floatToIntBits(point) == Float.floatToIntBits(testObject.floatItem()));
assertTrue(Float.floatToIntBits(point) == Float.floatToIntBits(testObject.floatItemObj()));
}
}
@Test
public void shouldReturnCorrectFloatFromText() throws Exception {
final float[] points = {0.0F, 1.0F, -1.0F, (float) Math.PI, (float) -Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
for (float point : points) {
final ImmutableMap<String, ?> dataMap = ImmutableMap.of("floatItem", Float.toString(point));
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(dataMap);
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertEquals(point, testObject.floatItem(), DELTA_FLOAT);
assertEquals(point, testObject.floatItemObj(), DELTA_FLOAT);
}
}
@Test
public void shouldReturnDefaultsForUndefinedKeys() throws Exception {
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(Collections.<String, Object>emptyMap());
final PrimitiveDataObject testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObject.class);
assertTrue(false == testObject.boolItem());
assertTrue(null == testObject.boolItemObj());
//
assertTrue((byte) 0 == testObject.byteItem());
assertTrue(null == testObject.byteItemObj());
//
assertTrue((short) 0 == testObject.shortItem());
assertTrue(null == testObject.shortItemObj());
//
assertTrue(0 == testObject.intItem());
assertTrue(null == testObject.intItemObj());
//
assertTrue(0L == testObject.longItem());
assertTrue(null == testObject.longItemObj());
//
assertTrue(0F == testObject.floatItem());
assertTrue(null == testObject.floatItemObj());
//
assertTrue(0D == testObject.doubleItem());
assertTrue(null == testObject.doubleItemObj());
}
@Test
public void shouldReturnAnnotatedDefaultsForUndefinedKeys() throws Exception {
final ConfigurationDataProvider data = ConfigurationData.getMapDataProvider(Collections.<String, Object>emptyMap());
final PrimitiveDataObjectWithDefaults testObject = ConfigurationData.createConfigurationObject(data, PrimitiveDataObjectWithDefaults.class);
assertTrue(true == testObject.boolItem());
//
assertTrue((byte) 12 == testObject.byteItem());
assertTrue((short) 123 == testObject.shortItem());
assertTrue(1234 == testObject.intItem());
assertTrue(12345L == testObject.longItem());
//
assertEquals(123.45F, testObject.floatItem(), DELTA_FLOAT);
assertEquals(12345.6789D, testObject.doubleItem(), DELTA_DOUBLE);
}
} | bbobcik/auderis-tools | config/src/test/java/cz/auderis/tools/config/PrimitiveDataObjectTest.java | Java | apache-2.0 | 12,571 |
package com.example.component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.component.DisposeNotifier;
@ArezComponent
abstract class NonStandardNameFieldDependencyModel
{
@ComponentDependency
public final DisposeNotifier $$time$$ = null;
}
| realityforge/arez | processor/src/test/fixtures/input/com/example/component_dependency/NonStandardNameFieldDependencyModel.java | Java | apache-2.0 | 308 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Sat Apr 25 17:14:54 PDT 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.annotation.JsonSerialize.Typing (jackson-databind 2.11.0 API)</title>
<meta name="date" content="2020-04-25">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.databind.annotation.JsonSerialize.Typing (jackson-databind 2.11.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/annotation/class-use/JsonSerialize.Typing.html" target="_top">Frames</a></li>
<li><a href="JsonSerialize.Typing.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 com.fasterxml.jackson.databind.annotation.JsonSerialize.Typing" class="title">Uses of Class<br>com.fasterxml.jackson.databind.annotation.JsonSerialize.Typing</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.databind">com.fasterxml.jackson.databind</a></td>
<td class="colLast">
<div class="block">Basic data binding (mapping) functionality that
allows for reading JSON content into Java Objects (POJOs)
and JSON Trees (<a href="../../../../../../com/fasterxml/jackson/databind/JsonNode.html" title="class in com.fasterxml.jackson.databind"><code>JsonNode</code></a>), as well as
writing Java Objects and trees as JSON.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.databind.annotation">com.fasterxml.jackson.databind.annotation</a></td>
<td class="colLast">
<div class="block">Annotations that directly depend on classes in databinding bundle
(not just Jackson core) and cannot be included
in Jackson core annotations package (because it cannot have any
external dependencies).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.databind.introspect">com.fasterxml.jackson.databind.introspect</a></td>
<td class="colLast">
<div class="block">Functionality needed for Bean introspection, required for detecting
accessors and mutators for Beans, as well as locating and handling
method annotations.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.databind">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a> in <a href="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</a> that return <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></code></td>
<td class="colLast"><span class="typeNameLabel">AnnotationIntrospector.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.html#findSerializationTyping-com.fasterxml.jackson.databind.introspect.Annotated-">findSerializationTyping</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/introspect/Annotated.html" title="class in com.fasterxml.jackson.databind.introspect">Annotated</a> a)</code>
<div class="block">Method for accessing declared typing mode annotated (if any).</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.databind.annotation">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a> in <a href="../../../../../../com/fasterxml/jackson/databind/annotation/package-summary.html">com.fasterxml.jackson.databind.annotation</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/databind/annotation/package-summary.html">com.fasterxml.jackson.databind.annotation</a> that return <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></code></td>
<td class="colLast"><span class="typeNameLabel">JsonSerialize.Typing.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">JsonSerialize.Typing.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.databind.introspect">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a> in <a href="../../../../../../com/fasterxml/jackson/databind/introspect/package-summary.html">com.fasterxml.jackson.databind.introspect</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/fasterxml/jackson/databind/introspect/package-summary.html">com.fasterxml.jackson.databind.introspect</a> that return <a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></code></td>
<td class="colLast"><span class="typeNameLabel">JacksonAnnotationIntrospector.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.html#findSerializationTyping-com.fasterxml.jackson.databind.introspect.Annotated-">findSerializationTyping</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/introspect/Annotated.html" title="class in com.fasterxml.jackson.databind.introspect">Annotated</a> a)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">JsonSerialize.Typing</a></code></td>
<td class="colLast"><span class="typeNameLabel">AnnotationIntrospectorPair.</span><code><span class="memberNameLink"><a href="../../../../../../com/fasterxml/jackson/databind/introspect/AnnotationIntrospectorPair.html#findSerializationTyping-com.fasterxml.jackson.databind.introspect.Annotated-">findSerializationTyping</a></span>(<a href="../../../../../../com/fasterxml/jackson/databind/introspect/Annotated.html" title="class in com.fasterxml.jackson.databind.introspect">Annotated</a> a)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/fasterxml/jackson/databind/annotation/JsonSerialize.Typing.html" title="enum in com.fasterxml.jackson.databind.annotation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/annotation/class-use/JsonSerialize.Typing.html" target="_top">Frames</a></li>
<li><a href="JsonSerialize.Typing.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2020 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| FasterXML/jackson-databind | docs/javadoc/2.11/com/fasterxml/jackson/databind/annotation/class-use/JsonSerialize.Typing.html | HTML | apache-2.0 | 13,834 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_272) on Sat Nov 28 17:15:55 PST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type (jackson-databind 2.12.0 API)</title>
<meta name="date" content="2020-11-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type (jackson-databind 2.12.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/databind/class-use/AnnotationIntrospector.ReferenceProperty.Type.html" target="_top">Frames</a></li>
<li><a href="AnnotationIntrospector.ReferenceProperty.Type.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 com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type" class="title">Uses of Class<br>com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.databind">com.fasterxml.jackson.databind</a></td>
<td class="colLast">
<div class="block">Basic data binding (mapping) functionality that
allows for reading JSON content into Java Objects (POJOs)
and JSON Trees (<a href="../../../../../com/fasterxml/jackson/databind/JsonNode.html" title="class in com.fasterxml.jackson.databind"><code>JsonNode</code></a>), as well as
writing Java Objects and trees as JSON.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.databind">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a> in <a href="../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</a> that return <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a></code></td>
<td class="colLast"><span class="typeNameLabel">AnnotationIntrospector.ReferenceProperty.</span><code><span class="memberNameLink"><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.html#getType--">getType</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a></code></td>
<td class="colLast"><span class="typeNameLabel">AnnotationIntrospector.ReferenceProperty.Type.</span><code><span class="memberNameLink"><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">AnnotationIntrospector.ReferenceProperty.Type.</span><code><span class="memberNameLink"><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.html#ReferenceProperty-com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty.Type-java.lang.String-">ReferenceProperty</a></span>(<a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">AnnotationIntrospector.ReferenceProperty.Type</a> t,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> n)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/fasterxml/jackson/databind/AnnotationIntrospector.ReferenceProperty.Type.html" title="enum in com.fasterxml.jackson.databind">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/databind/class-use/AnnotationIntrospector.ReferenceProperty.Type.html" target="_top">Frames</a></li>
<li><a href="AnnotationIntrospector.ReferenceProperty.Type.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2020 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| FasterXML/jackson-databind | docs/javadoc/2.12/com/fasterxml/jackson/databind/class-use/AnnotationIntrospector.ReferenceProperty.Type.html | HTML | apache-2.0 | 10,687 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
package aiplatform
import (
"context"
"fmt"
"math"
"net/url"
"time"
"cloud.google.com/go/longrunning"
lroauto "cloud.google.com/go/longrunning/autogen"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
gtransport "google.golang.org/api/transport/grpc"
aiplatformpb "google.golang.org/genproto/googleapis/cloud/aiplatform/v1"
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/proto"
)
var newVizierClientHook clientHook
// VizierCallOptions contains the retry settings for each method of VizierClient.
type VizierCallOptions struct {
CreateStudy []gax.CallOption
GetStudy []gax.CallOption
ListStudies []gax.CallOption
DeleteStudy []gax.CallOption
LookupStudy []gax.CallOption
SuggestTrials []gax.CallOption
CreateTrial []gax.CallOption
GetTrial []gax.CallOption
ListTrials []gax.CallOption
AddTrialMeasurement []gax.CallOption
CompleteTrial []gax.CallOption
DeleteTrial []gax.CallOption
CheckTrialEarlyStoppingState []gax.CallOption
StopTrial []gax.CallOption
ListOptimalTrials []gax.CallOption
}
func defaultVizierGRPCClientOptions() []option.ClientOption {
return []option.ClientOption{
internaloption.WithDefaultEndpoint("aiplatform.googleapis.com:443"),
internaloption.WithDefaultMTLSEndpoint("aiplatform.mtls.googleapis.com:443"),
internaloption.WithDefaultAudience("https://aiplatform.googleapis.com/"),
internaloption.WithDefaultScopes(DefaultAuthScopes()...),
internaloption.EnableJwtWithScope(),
option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(math.MaxInt32))),
}
}
func defaultVizierCallOptions() *VizierCallOptions {
return &VizierCallOptions{
CreateStudy: []gax.CallOption{},
GetStudy: []gax.CallOption{},
ListStudies: []gax.CallOption{},
DeleteStudy: []gax.CallOption{},
LookupStudy: []gax.CallOption{},
SuggestTrials: []gax.CallOption{},
CreateTrial: []gax.CallOption{},
GetTrial: []gax.CallOption{},
ListTrials: []gax.CallOption{},
AddTrialMeasurement: []gax.CallOption{},
CompleteTrial: []gax.CallOption{},
DeleteTrial: []gax.CallOption{},
CheckTrialEarlyStoppingState: []gax.CallOption{},
StopTrial: []gax.CallOption{},
ListOptimalTrials: []gax.CallOption{},
}
}
// internalVizierClient is an interface that defines the methods availaible from Vertex AI API.
type internalVizierClient interface {
Close() error
setGoogleClientInfo(...string)
Connection() *grpc.ClientConn
CreateStudy(context.Context, *aiplatformpb.CreateStudyRequest, ...gax.CallOption) (*aiplatformpb.Study, error)
GetStudy(context.Context, *aiplatformpb.GetStudyRequest, ...gax.CallOption) (*aiplatformpb.Study, error)
ListStudies(context.Context, *aiplatformpb.ListStudiesRequest, ...gax.CallOption) *StudyIterator
DeleteStudy(context.Context, *aiplatformpb.DeleteStudyRequest, ...gax.CallOption) error
LookupStudy(context.Context, *aiplatformpb.LookupStudyRequest, ...gax.CallOption) (*aiplatformpb.Study, error)
SuggestTrials(context.Context, *aiplatformpb.SuggestTrialsRequest, ...gax.CallOption) (*SuggestTrialsOperation, error)
SuggestTrialsOperation(name string) *SuggestTrialsOperation
CreateTrial(context.Context, *aiplatformpb.CreateTrialRequest, ...gax.CallOption) (*aiplatformpb.Trial, error)
GetTrial(context.Context, *aiplatformpb.GetTrialRequest, ...gax.CallOption) (*aiplatformpb.Trial, error)
ListTrials(context.Context, *aiplatformpb.ListTrialsRequest, ...gax.CallOption) *TrialIterator
AddTrialMeasurement(context.Context, *aiplatformpb.AddTrialMeasurementRequest, ...gax.CallOption) (*aiplatformpb.Trial, error)
CompleteTrial(context.Context, *aiplatformpb.CompleteTrialRequest, ...gax.CallOption) (*aiplatformpb.Trial, error)
DeleteTrial(context.Context, *aiplatformpb.DeleteTrialRequest, ...gax.CallOption) error
CheckTrialEarlyStoppingState(context.Context, *aiplatformpb.CheckTrialEarlyStoppingStateRequest, ...gax.CallOption) (*CheckTrialEarlyStoppingStateOperation, error)
CheckTrialEarlyStoppingStateOperation(name string) *CheckTrialEarlyStoppingStateOperation
StopTrial(context.Context, *aiplatformpb.StopTrialRequest, ...gax.CallOption) (*aiplatformpb.Trial, error)
ListOptimalTrials(context.Context, *aiplatformpb.ListOptimalTrialsRequest, ...gax.CallOption) (*aiplatformpb.ListOptimalTrialsResponse, error)
}
// VizierClient is a client for interacting with Vertex AI API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
//
// Vertex AI Vizier API.
//
// Vertex AI Vizier is a service to solve blackbox optimization problems,
// such as tuning machine learning hyperparameters and searching over deep
// learning architectures.
type VizierClient struct {
// The internal transport-dependent client.
internalClient internalVizierClient
// The call options for this service.
CallOptions *VizierCallOptions
// LROClient is used internally to handle long-running operations.
// It is exposed so that its CallOptions can be modified if required.
// Users should not Close this client.
LROClient *lroauto.OperationsClient
}
// Wrapper methods routed to the internal client.
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *VizierClient) Close() error {
return c.internalClient.Close()
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *VizierClient) setGoogleClientInfo(keyval ...string) {
c.internalClient.setGoogleClientInfo(keyval...)
}
// Connection returns a connection to the API service.
//
// Deprecated.
func (c *VizierClient) Connection() *grpc.ClientConn {
return c.internalClient.Connection()
}
// CreateStudy creates a Study. A resource name will be generated after creation of the
// Study.
func (c *VizierClient) CreateStudy(ctx context.Context, req *aiplatformpb.CreateStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
return c.internalClient.CreateStudy(ctx, req, opts...)
}
// GetStudy gets a Study by name.
func (c *VizierClient) GetStudy(ctx context.Context, req *aiplatformpb.GetStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
return c.internalClient.GetStudy(ctx, req, opts...)
}
// ListStudies lists all the studies in a region for an associated project.
func (c *VizierClient) ListStudies(ctx context.Context, req *aiplatformpb.ListStudiesRequest, opts ...gax.CallOption) *StudyIterator {
return c.internalClient.ListStudies(ctx, req, opts...)
}
// DeleteStudy deletes a Study.
func (c *VizierClient) DeleteStudy(ctx context.Context, req *aiplatformpb.DeleteStudyRequest, opts ...gax.CallOption) error {
return c.internalClient.DeleteStudy(ctx, req, opts...)
}
// LookupStudy looks a study up using the user-defined display_name field instead of the
// fully qualified resource name.
func (c *VizierClient) LookupStudy(ctx context.Context, req *aiplatformpb.LookupStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
return c.internalClient.LookupStudy(ctx, req, opts...)
}
// SuggestTrials adds one or more Trials to a Study, with parameter values
// suggested by Vertex AI Vizier. Returns a long-running
// operation associated with the generation of Trial suggestions.
// When this long-running operation succeeds, it will contain
// a SuggestTrialsResponse.
func (c *VizierClient) SuggestTrials(ctx context.Context, req *aiplatformpb.SuggestTrialsRequest, opts ...gax.CallOption) (*SuggestTrialsOperation, error) {
return c.internalClient.SuggestTrials(ctx, req, opts...)
}
// SuggestTrialsOperation returns a new SuggestTrialsOperation from a given name.
// The name must be that of a previously created SuggestTrialsOperation, possibly from a different process.
func (c *VizierClient) SuggestTrialsOperation(name string) *SuggestTrialsOperation {
return c.internalClient.SuggestTrialsOperation(name)
}
// CreateTrial adds a user provided Trial to a Study.
func (c *VizierClient) CreateTrial(ctx context.Context, req *aiplatformpb.CreateTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
return c.internalClient.CreateTrial(ctx, req, opts...)
}
// GetTrial gets a Trial.
func (c *VizierClient) GetTrial(ctx context.Context, req *aiplatformpb.GetTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
return c.internalClient.GetTrial(ctx, req, opts...)
}
// ListTrials lists the Trials associated with a Study.
func (c *VizierClient) ListTrials(ctx context.Context, req *aiplatformpb.ListTrialsRequest, opts ...gax.CallOption) *TrialIterator {
return c.internalClient.ListTrials(ctx, req, opts...)
}
// AddTrialMeasurement adds a measurement of the objective metrics to a Trial. This measurement
// is assumed to have been taken before the Trial is complete.
func (c *VizierClient) AddTrialMeasurement(ctx context.Context, req *aiplatformpb.AddTrialMeasurementRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
return c.internalClient.AddTrialMeasurement(ctx, req, opts...)
}
// CompleteTrial marks a Trial as complete.
func (c *VizierClient) CompleteTrial(ctx context.Context, req *aiplatformpb.CompleteTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
return c.internalClient.CompleteTrial(ctx, req, opts...)
}
// DeleteTrial deletes a Trial.
func (c *VizierClient) DeleteTrial(ctx context.Context, req *aiplatformpb.DeleteTrialRequest, opts ...gax.CallOption) error {
return c.internalClient.DeleteTrial(ctx, req, opts...)
}
// CheckTrialEarlyStoppingState checks whether a Trial should stop or not. Returns a
// long-running operation. When the operation is successful,
// it will contain a
// CheckTrialEarlyStoppingStateResponse.
func (c *VizierClient) CheckTrialEarlyStoppingState(ctx context.Context, req *aiplatformpb.CheckTrialEarlyStoppingStateRequest, opts ...gax.CallOption) (*CheckTrialEarlyStoppingStateOperation, error) {
return c.internalClient.CheckTrialEarlyStoppingState(ctx, req, opts...)
}
// CheckTrialEarlyStoppingStateOperation returns a new CheckTrialEarlyStoppingStateOperation from a given name.
// The name must be that of a previously created CheckTrialEarlyStoppingStateOperation, possibly from a different process.
func (c *VizierClient) CheckTrialEarlyStoppingStateOperation(name string) *CheckTrialEarlyStoppingStateOperation {
return c.internalClient.CheckTrialEarlyStoppingStateOperation(name)
}
// StopTrial stops a Trial.
func (c *VizierClient) StopTrial(ctx context.Context, req *aiplatformpb.StopTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
return c.internalClient.StopTrial(ctx, req, opts...)
}
// ListOptimalTrials lists the pareto-optimal Trials for multi-objective Study or the
// optimal Trials for single-objective Study. The definition of
// pareto-optimal can be checked in wiki page.
// https://en.wikipedia.org/wiki/Pareto_efficiency (at https://en.wikipedia.org/wiki/Pareto_efficiency)
func (c *VizierClient) ListOptimalTrials(ctx context.Context, req *aiplatformpb.ListOptimalTrialsRequest, opts ...gax.CallOption) (*aiplatformpb.ListOptimalTrialsResponse, error) {
return c.internalClient.ListOptimalTrials(ctx, req, opts...)
}
// vizierGRPCClient is a client for interacting with Vertex AI API over gRPC transport.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type vizierGRPCClient struct {
// Connection pool of gRPC connections to the service.
connPool gtransport.ConnPool
// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
disableDeadlines bool
// Points back to the CallOptions field of the containing VizierClient
CallOptions **VizierCallOptions
// The gRPC API client.
vizierClient aiplatformpb.VizierServiceClient
// LROClient is used internally to handle long-running operations.
// It is exposed so that its CallOptions can be modified if required.
// Users should not Close this client.
LROClient **lroauto.OperationsClient
// The x-goog-* metadata to be sent with each request.
xGoogMetadata metadata.MD
}
// NewVizierClient creates a new vizier service client based on gRPC.
// The returned client must be Closed when it is done being used to clean up its underlying connections.
//
// Vertex AI Vizier API.
//
// Vertex AI Vizier is a service to solve blackbox optimization problems,
// such as tuning machine learning hyperparameters and searching over deep
// learning architectures.
func NewVizierClient(ctx context.Context, opts ...option.ClientOption) (*VizierClient, error) {
clientOpts := defaultVizierGRPCClientOptions()
if newVizierClientHook != nil {
hookOpts, err := newVizierClientHook(ctx, clientHookParams{})
if err != nil {
return nil, err
}
clientOpts = append(clientOpts, hookOpts...)
}
disableDeadlines, err := checkDisableDeadlines()
if err != nil {
return nil, err
}
connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
if err != nil {
return nil, err
}
client := VizierClient{CallOptions: defaultVizierCallOptions()}
c := &vizierGRPCClient{
connPool: connPool,
disableDeadlines: disableDeadlines,
vizierClient: aiplatformpb.NewVizierServiceClient(connPool),
CallOptions: &client.CallOptions,
}
c.setGoogleClientInfo()
client.internalClient = c
client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
if err != nil {
// This error "should not happen", since we are just reusing old connection pool
// and never actually need to dial.
// If this does happen, we could leak connp. However, we cannot close conn:
// If the user invoked the constructor with option.WithGRPCConn,
// we would close a connection that's still in use.
// TODO: investigate error conditions.
return nil, err
}
c.LROClient = &client.LROClient
return &client, nil
}
// Connection returns a connection to the API service.
//
// Deprecated.
func (c *vizierGRPCClient) Connection() *grpc.ClientConn {
return c.connPool.Conn()
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *vizierGRPCClient) setGoogleClientInfo(keyval ...string) {
kv := append([]string{"gl-go", versionGo()}, keyval...)
kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version)
c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *vizierGRPCClient) Close() error {
return c.connPool.Close()
}
func (c *vizierGRPCClient) CreateStudy(ctx context.Context, req *aiplatformpb.CreateStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).CreateStudy[0:len((*c.CallOptions).CreateStudy):len((*c.CallOptions).CreateStudy)], opts...)
var resp *aiplatformpb.Study
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.CreateStudy(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) GetStudy(ctx context.Context, req *aiplatformpb.GetStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).GetStudy[0:len((*c.CallOptions).GetStudy):len((*c.CallOptions).GetStudy)], opts...)
var resp *aiplatformpb.Study
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.GetStudy(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) ListStudies(ctx context.Context, req *aiplatformpb.ListStudiesRequest, opts ...gax.CallOption) *StudyIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).ListStudies[0:len((*c.CallOptions).ListStudies):len((*c.CallOptions).ListStudies)], opts...)
it := &StudyIterator{}
req = proto.Clone(req).(*aiplatformpb.ListStudiesRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*aiplatformpb.Study, string, error) {
resp := &aiplatformpb.ListStudiesResponse{}
if pageToken != "" {
req.PageToken = pageToken
}
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else if pageSize != 0 {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.ListStudies(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetStudies(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
func (c *vizierGRPCClient) DeleteStudy(ctx context.Context, req *aiplatformpb.DeleteStudyRequest, opts ...gax.CallOption) error {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).DeleteStudy[0:len((*c.CallOptions).DeleteStudy):len((*c.CallOptions).DeleteStudy)], opts...)
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
_, err = c.vizierClient.DeleteStudy(ctx, req, settings.GRPC...)
return err
}, opts...)
return err
}
func (c *vizierGRPCClient) LookupStudy(ctx context.Context, req *aiplatformpb.LookupStudyRequest, opts ...gax.CallOption) (*aiplatformpb.Study, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).LookupStudy[0:len((*c.CallOptions).LookupStudy):len((*c.CallOptions).LookupStudy)], opts...)
var resp *aiplatformpb.Study
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.LookupStudy(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) SuggestTrials(ctx context.Context, req *aiplatformpb.SuggestTrialsRequest, opts ...gax.CallOption) (*SuggestTrialsOperation, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).SuggestTrials[0:len((*c.CallOptions).SuggestTrials):len((*c.CallOptions).SuggestTrials)], opts...)
var resp *longrunningpb.Operation
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.SuggestTrials(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return &SuggestTrialsOperation{
lro: longrunning.InternalNewOperation(*c.LROClient, resp),
}, nil
}
func (c *vizierGRPCClient) CreateTrial(ctx context.Context, req *aiplatformpb.CreateTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).CreateTrial[0:len((*c.CallOptions).CreateTrial):len((*c.CallOptions).CreateTrial)], opts...)
var resp *aiplatformpb.Trial
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.CreateTrial(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) GetTrial(ctx context.Context, req *aiplatformpb.GetTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).GetTrial[0:len((*c.CallOptions).GetTrial):len((*c.CallOptions).GetTrial)], opts...)
var resp *aiplatformpb.Trial
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.GetTrial(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) ListTrials(ctx context.Context, req *aiplatformpb.ListTrialsRequest, opts ...gax.CallOption) *TrialIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).ListTrials[0:len((*c.CallOptions).ListTrials):len((*c.CallOptions).ListTrials)], opts...)
it := &TrialIterator{}
req = proto.Clone(req).(*aiplatformpb.ListTrialsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*aiplatformpb.Trial, string, error) {
resp := &aiplatformpb.ListTrialsResponse{}
if pageToken != "" {
req.PageToken = pageToken
}
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else if pageSize != 0 {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.ListTrials(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetTrials(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
func (c *vizierGRPCClient) AddTrialMeasurement(ctx context.Context, req *aiplatformpb.AddTrialMeasurementRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "trial_name", url.QueryEscape(req.GetTrialName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).AddTrialMeasurement[0:len((*c.CallOptions).AddTrialMeasurement):len((*c.CallOptions).AddTrialMeasurement)], opts...)
var resp *aiplatformpb.Trial
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.AddTrialMeasurement(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) CompleteTrial(ctx context.Context, req *aiplatformpb.CompleteTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).CompleteTrial[0:len((*c.CallOptions).CompleteTrial):len((*c.CallOptions).CompleteTrial)], opts...)
var resp *aiplatformpb.Trial
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.CompleteTrial(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) DeleteTrial(ctx context.Context, req *aiplatformpb.DeleteTrialRequest, opts ...gax.CallOption) error {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).DeleteTrial[0:len((*c.CallOptions).DeleteTrial):len((*c.CallOptions).DeleteTrial)], opts...)
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
_, err = c.vizierClient.DeleteTrial(ctx, req, settings.GRPC...)
return err
}, opts...)
return err
}
func (c *vizierGRPCClient) CheckTrialEarlyStoppingState(ctx context.Context, req *aiplatformpb.CheckTrialEarlyStoppingStateRequest, opts ...gax.CallOption) (*CheckTrialEarlyStoppingStateOperation, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "trial_name", url.QueryEscape(req.GetTrialName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).CheckTrialEarlyStoppingState[0:len((*c.CallOptions).CheckTrialEarlyStoppingState):len((*c.CallOptions).CheckTrialEarlyStoppingState)], opts...)
var resp *longrunningpb.Operation
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.CheckTrialEarlyStoppingState(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return &CheckTrialEarlyStoppingStateOperation{
lro: longrunning.InternalNewOperation(*c.LROClient, resp),
}, nil
}
func (c *vizierGRPCClient) StopTrial(ctx context.Context, req *aiplatformpb.StopTrialRequest, opts ...gax.CallOption) (*aiplatformpb.Trial, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).StopTrial[0:len((*c.CallOptions).StopTrial):len((*c.CallOptions).StopTrial)], opts...)
var resp *aiplatformpb.Trial
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.StopTrial(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *vizierGRPCClient) ListOptimalTrials(ctx context.Context, req *aiplatformpb.ListOptimalTrialsRequest, opts ...gax.CallOption) (*aiplatformpb.ListOptimalTrialsResponse, error) {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append((*c.CallOptions).ListOptimalTrials[0:len((*c.CallOptions).ListOptimalTrials):len((*c.CallOptions).ListOptimalTrials)], opts...)
var resp *aiplatformpb.ListOptimalTrialsResponse
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.vizierClient.ListOptimalTrials(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// CheckTrialEarlyStoppingStateOperation manages a long-running operation from CheckTrialEarlyStoppingState.
type CheckTrialEarlyStoppingStateOperation struct {
lro *longrunning.Operation
}
// CheckTrialEarlyStoppingStateOperation returns a new CheckTrialEarlyStoppingStateOperation from a given name.
// The name must be that of a previously created CheckTrialEarlyStoppingStateOperation, possibly from a different process.
func (c *vizierGRPCClient) CheckTrialEarlyStoppingStateOperation(name string) *CheckTrialEarlyStoppingStateOperation {
return &CheckTrialEarlyStoppingStateOperation{
lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
}
}
// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *CheckTrialEarlyStoppingStateOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*aiplatformpb.CheckTrialEarlyStoppingStateResponse, error) {
var resp aiplatformpb.CheckTrialEarlyStoppingStateResponse
if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
return nil, err
}
return &resp, nil
}
// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *CheckTrialEarlyStoppingStateOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*aiplatformpb.CheckTrialEarlyStoppingStateResponse, error) {
var resp aiplatformpb.CheckTrialEarlyStoppingStateResponse
if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
return nil, err
}
if !op.Done() {
return nil, nil
}
return &resp, nil
}
// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *CheckTrialEarlyStoppingStateOperation) Metadata() (*aiplatformpb.CheckTrialEarlyStoppingStateMetatdata, error) {
var meta aiplatformpb.CheckTrialEarlyStoppingStateMetatdata
if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
return nil, nil
} else if err != nil {
return nil, err
}
return &meta, nil
}
// Done reports whether the long-running operation has completed.
func (op *CheckTrialEarlyStoppingStateOperation) Done() bool {
return op.lro.Done()
}
// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *CheckTrialEarlyStoppingStateOperation) Name() string {
return op.lro.Name()
}
// SuggestTrialsOperation manages a long-running operation from SuggestTrials.
type SuggestTrialsOperation struct {
lro *longrunning.Operation
}
// SuggestTrialsOperation returns a new SuggestTrialsOperation from a given name.
// The name must be that of a previously created SuggestTrialsOperation, possibly from a different process.
func (c *vizierGRPCClient) SuggestTrialsOperation(name string) *SuggestTrialsOperation {
return &SuggestTrialsOperation{
lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
}
}
// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *SuggestTrialsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*aiplatformpb.SuggestTrialsResponse, error) {
var resp aiplatformpb.SuggestTrialsResponse
if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
return nil, err
}
return &resp, nil
}
// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *SuggestTrialsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*aiplatformpb.SuggestTrialsResponse, error) {
var resp aiplatformpb.SuggestTrialsResponse
if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
return nil, err
}
if !op.Done() {
return nil, nil
}
return &resp, nil
}
// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *SuggestTrialsOperation) Metadata() (*aiplatformpb.SuggestTrialsMetadata, error) {
var meta aiplatformpb.SuggestTrialsMetadata
if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
return nil, nil
} else if err != nil {
return nil, err
}
return &meta, nil
}
// Done reports whether the long-running operation has completed.
func (op *SuggestTrialsOperation) Done() bool {
return op.lro.Done()
}
// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *SuggestTrialsOperation) Name() string {
return op.lro.Name()
}
// StudyIterator manages a stream of *aiplatformpb.Study.
type StudyIterator struct {
items []*aiplatformpb.Study
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*aiplatformpb.Study, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *StudyIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *StudyIterator) Next() (*aiplatformpb.Study, error) {
var item *aiplatformpb.Study
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *StudyIterator) bufLen() int {
return len(it.items)
}
func (it *StudyIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// TrialIterator manages a stream of *aiplatformpb.Trial.
type TrialIterator struct {
items []*aiplatformpb.Trial
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*aiplatformpb.Trial, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *TrialIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *TrialIterator) Next() (*aiplatformpb.Trial, error) {
var item *aiplatformpb.Trial
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *TrialIterator) bufLen() int {
return len(it.items)
}
func (it *TrialIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
| googleapis/google-cloud-go | aiplatform/apiv1/vizier_client.go | GO | apache-2.0 | 38,059 |
#include <stdio.h>
int main()
{
int n;
int i=0;
scanf("%d", &n);
while(n != 1){
if(n % 2 == 0){
n /= 2;
} else {
n = (3*n+1)/2;
}
i++;
}
printf("%d\n", i);
return 0;
}
| XF-zhjnc/PAT-Basic-Practise | 1001.cpp | C++ | apache-2.0 | 189 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class: GridFSBucketReadStream</title>
<meta property="og:title" content="MongoDB Driver API for Node.js"/>
<meta property="og:type" content="website"/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<script src="scripts/jquery.min.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="styles/jaguar.css">
<script>
var config = {"monospaceLinks":true,"cleverLinks":true,"default":{"outputSourceFiles":true},"applicationName":"Node.js MongoDB Driver API","googleAnalytics":"UA-7301842-14","openGraph":{"title":"MongoDB Driver API for Node.js","type":"website","image":"","site_name":"","url":""},"meta":{"title":"","description":"","keyword":""},"linenums":true};
</script>
<script>
(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-7301842-14, 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div id="wrap" class="clearfix" style="width:100%;">
<table style="height:100%;width:100%">
<tr>
<td valign='top' width="1px">
<div class="navigation">
<h3 class="applicationName"><a href="index.html">Node.js MongoDB Driver API</a></h3>
<div class="search">
<input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations">
</div>
<ul class="list">
<li class="item" data-name="Admin">
<span class="title">
<a href="Admin.html">Admin</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="Admin~resultCallback"><a href="Admin.html#~resultCallback">resultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Admin#addUser"><a href="Admin.html#addUser">addUser</a></li>
<li data-name="Admin#buildInfo"><a href="Admin.html#buildInfo">buildInfo</a></li>
<li data-name="Admin#command"><a href="Admin.html#command">command</a></li>
<li data-name="Admin#listDatabases"><a href="Admin.html#listDatabases">listDatabases</a></li>
<li data-name="Admin#ping"><a href="Admin.html#ping">ping</a></li>
<li data-name="Admin#removeUser"><a href="Admin.html#removeUser">removeUser</a></li>
<li data-name="Admin#replSetGetStatus"><a href="Admin.html#replSetGetStatus">replSetGetStatus</a></li>
<li data-name="Admin#serverInfo"><a href="Admin.html#serverInfo">serverInfo</a></li>
<li data-name="Admin#serverStatus"><a href="Admin.html#serverStatus">serverStatus</a></li>
<li data-name="Admin#validateCollection"><a href="Admin.html#validateCollection">validateCollection</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="AggregationCursor">
<span class="title">
<a href="AggregationCursor.html">AggregationCursor</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="AggregationCursor~endCallback"><a href="AggregationCursor.html#~endCallback">endCallback</a></li>
<li data-name="AggregationCursor~iteratorCallback"><a href="AggregationCursor.html#~iteratorCallback">iteratorCallback</a></li>
<li data-name="AggregationCursor~resultCallback"><a href="AggregationCursor.html#~resultCallback">resultCallback</a></li>
<li data-name="AggregationCursor~toArrayResultCallback"><a href="AggregationCursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="AggregationCursor#batchSize"><a href="AggregationCursor.html#batchSize">batchSize</a></li>
<li data-name="AggregationCursor#clone"><a href="AggregationCursor.html#clone">clone</a></li>
<li data-name="AggregationCursor#close"><a href="AggregationCursor.html#close">close</a></li>
<li data-name="AggregationCursor#each"><a href="AggregationCursor.html#each">each</a></li>
<li data-name="AggregationCursor#explain"><a href="AggregationCursor.html#explain">explain</a></li>
<li data-name="AggregationCursor#geoNear"><a href="AggregationCursor.html#geoNear">geoNear</a></li>
<li data-name="AggregationCursor#group"><a href="AggregationCursor.html#group">group</a></li>
<li data-name="AggregationCursor#hasNext"><a href="AggregationCursor.html#hasNext">hasNext</a></li>
<li data-name="AggregationCursor#isClosed"><a href="AggregationCursor.html#isClosed">isClosed</a></li>
<li data-name="AggregationCursor#limit"><a href="AggregationCursor.html#limit">limit</a></li>
<li data-name="AggregationCursor#lookup"><a href="AggregationCursor.html#lookup">lookup</a></li>
<li data-name="AggregationCursor#match"><a href="AggregationCursor.html#match">match</a></li>
<li data-name="AggregationCursor#maxTimeMS"><a href="AggregationCursor.html#maxTimeMS">maxTimeMS</a></li>
<li data-name="AggregationCursor#next"><a href="AggregationCursor.html#next">next</a></li>
<li data-name="AggregationCursor#out"><a href="AggregationCursor.html#out">out</a></li>
<li data-name="AggregationCursor#pause"><a href="AggregationCursor.html#pause">pause</a></li>
<li data-name="AggregationCursor#pipe"><a href="AggregationCursor.html#pipe">pipe</a></li>
<li data-name="AggregationCursor#project"><a href="AggregationCursor.html#project">project</a></li>
<li data-name="AggregationCursor#read"><a href="AggregationCursor.html#read">read</a></li>
<li data-name="AggregationCursor#redact"><a href="AggregationCursor.html#redact">redact</a></li>
<li data-name="AggregationCursor#resume"><a href="AggregationCursor.html#resume">resume</a></li>
<li data-name="AggregationCursor#rewind"><a href="AggregationCursor.html#rewind">rewind</a></li>
<li data-name="AggregationCursor#setEncoding"><a href="AggregationCursor.html#setEncoding">setEncoding</a></li>
<li data-name="AggregationCursor#skip"><a href="AggregationCursor.html#skip">skip</a></li>
<li data-name="AggregationCursor#sort"><a href="AggregationCursor.html#sort">sort</a></li>
<li data-name="AggregationCursor#toArray"><a href="AggregationCursor.html#toArray">toArray</a></li>
<li data-name="AggregationCursor#unpipe"><a href="AggregationCursor.html#unpipe">unpipe</a></li>
<li data-name="AggregationCursor#unshift"><a href="AggregationCursor.html#unshift">unshift</a></li>
<li data-name="AggregationCursor#unwind"><a href="AggregationCursor.html#unwind">unwind</a></li>
<li data-name="AggregationCursor#wrap"><a href="AggregationCursor.html#wrap">wrap</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="AggregationCursor#event:close"><a href="AggregationCursor.html#event:close">close</a></li>
<li data-name="AggregationCursor#event:data"><a href="AggregationCursor.html#event:data">data</a></li>
<li data-name="AggregationCursor#event:end"><a href="AggregationCursor.html#event:end">end</a></li>
<li data-name="AggregationCursor#event:readable"><a href="AggregationCursor.html#event:readable">readable</a></li>
</ul>
</li>
<li class="item" data-name="Binary">
<span class="title">
<a href="Binary.html">Binary</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="Binary.SUBTYPE_BYTE_ARRAY"><a href="Binary.html#.SUBTYPE_BYTE_ARRAY">SUBTYPE_BYTE_ARRAY</a></li>
<li data-name="Binary.SUBTYPE_DEFAULT"><a href="Binary.html#.SUBTYPE_DEFAULT">SUBTYPE_DEFAULT</a></li>
<li data-name="Binary.SUBTYPE_FUNCTION"><a href="Binary.html#.SUBTYPE_FUNCTION">SUBTYPE_FUNCTION</a></li>
<li data-name="Binary.SUBTYPE_MD5"><a href="Binary.html#.SUBTYPE_MD5">SUBTYPE_MD5</a></li>
<li data-name="Binary.SUBTYPE_USER_DEFINED"><a href="Binary.html#.SUBTYPE_USER_DEFINED">SUBTYPE_USER_DEFINED</a></li>
<li data-name="Binary.SUBTYPE_UUID"><a href="Binary.html#.SUBTYPE_UUID">SUBTYPE_UUID</a></li>
<li data-name="Binary.SUBTYPE_UUID_OLD"><a href="Binary.html#.SUBTYPE_UUID_OLD">SUBTYPE_UUID_OLD</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Binary#length"><a href="Binary.html#length">length</a></li>
<li data-name="Binary#put"><a href="Binary.html#put">put</a></li>
<li data-name="Binary#read"><a href="Binary.html#read">read</a></li>
<li data-name="Binary#value"><a href="Binary.html#value">value</a></li>
<li data-name="Binary#write"><a href="Binary.html#write">write</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="BSONRegExp">
<span class="title">
<a href="BSONRegExp.html">BSONRegExp</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="BulkOperationBase">
<span class="title">
<a href="BulkOperationBase.html">BulkOperationBase</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="BulkOperationBase#bulkExecute"><a href="BulkOperationBase.html#bulkExecute">bulkExecute</a></li>
<li data-name="BulkOperationBase#finalOptionsHandler"><a href="BulkOperationBase.html#finalOptionsHandler">finalOptionsHandler</a></li>
<li data-name="BulkOperationBase#find"><a href="BulkOperationBase.html#find">find</a></li>
<li data-name="BulkOperationBase#handleWriteError"><a href="BulkOperationBase.html#handleWriteError">handleWriteError</a></li>
<li data-name="BulkOperationBase#insert"><a href="BulkOperationBase.html#insert">insert</a></li>
<li data-name="BulkOperationBase#raw"><a href="BulkOperationBase.html#raw">raw</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="BulkWriteError">
<span class="title">
<a href="BulkWriteError.html">BulkWriteError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="BulkWriteResult">
<span class="title">
<a href="BulkWriteResult.html">BulkWriteResult</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="BulkWriteResult#nInserted"><a href="BulkWriteResult.html#nInserted">nInserted</a></li>
<li data-name="BulkWriteResult#nMatched"><a href="BulkWriteResult.html#nMatched">nMatched</a></li>
<li data-name="BulkWriteResult#nModified"><a href="BulkWriteResult.html#nModified">nModified</a></li>
<li data-name="BulkWriteResult#nRemoved"><a href="BulkWriteResult.html#nRemoved">nRemoved</a></li>
<li data-name="BulkWriteResult#nUpserted"><a href="BulkWriteResult.html#nUpserted">nUpserted</a></li>
<li data-name="BulkWriteResult#ok"><a href="BulkWriteResult.html#ok">ok</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="BulkWriteResult#getInsertedIds"><a href="BulkWriteResult.html#getInsertedIds">getInsertedIds</a></li>
<li data-name="BulkWriteResult#getLastOp"><a href="BulkWriteResult.html#getLastOp">getLastOp</a></li>
<li data-name="BulkWriteResult#getRawResponse"><a href="BulkWriteResult.html#getRawResponse">getRawResponse</a></li>
<li data-name="BulkWriteResult#getUpsertedIdAt"><a href="BulkWriteResult.html#getUpsertedIdAt">getUpsertedIdAt</a></li>
<li data-name="BulkWriteResult#getUpsertedIds"><a href="BulkWriteResult.html#getUpsertedIds">getUpsertedIds</a></li>
<li data-name="BulkWriteResult#getWriteConcernError"><a href="BulkWriteResult.html#getWriteConcernError">getWriteConcernError</a></li>
<li data-name="BulkWriteResult#getWriteErrorAt"><a href="BulkWriteResult.html#getWriteErrorAt">getWriteErrorAt</a></li>
<li data-name="BulkWriteResult#getWriteErrorCount"><a href="BulkWriteResult.html#getWriteErrorCount">getWriteErrorCount</a></li>
<li data-name="BulkWriteResult#getWriteErrors"><a href="BulkWriteResult.html#getWriteErrors">getWriteErrors</a></li>
<li data-name="BulkWriteResult#hasWriteErrors"><a href="BulkWriteResult.html#hasWriteErrors">hasWriteErrors</a></li>
<li data-name="BulkWriteResult#isOk"><a href="BulkWriteResult.html#isOk">isOk</a></li>
<li data-name="BulkWriteResult#toJSON"><a href="BulkWriteResult.html#toJSON">toJSON</a></li>
<li data-name="BulkWriteResult#toString"><a href="BulkWriteResult.html#toString">toString</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="ChangeStream">
<span class="title">
<a href="ChangeStream.html">ChangeStream</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="ChangeStream~resultCallback"><a href="ChangeStream.html#~resultCallback">resultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="ChangeStream#close"><a href="ChangeStream.html#close">close</a></li>
<li data-name="ChangeStream#hasNext"><a href="ChangeStream.html#hasNext">hasNext</a></li>
<li data-name="ChangeStream#isClosed"><a href="ChangeStream.html#isClosed">isClosed</a></li>
<li data-name="ChangeStream#next"><a href="ChangeStream.html#next">next</a></li>
<li data-name="ChangeStream#pause"><a href="ChangeStream.html#pause">pause</a></li>
<li data-name="ChangeStream#pipe"><a href="ChangeStream.html#pipe">pipe</a></li>
<li data-name="ChangeStream#resume"><a href="ChangeStream.html#resume">resume</a></li>
<li data-name="ChangeStream#stream"><a href="ChangeStream.html#stream">stream</a></li>
<li data-name="ChangeStream#unpipe"><a href="ChangeStream.html#unpipe">unpipe</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="ChangeStream#event:change"><a href="ChangeStream.html#event:change">change</a></li>
<li data-name="ChangeStream#event:close"><a href="ChangeStream.html#event:close">close</a></li>
<li data-name="ChangeStream#event:end"><a href="ChangeStream.html#event:end">end</a></li>
<li data-name="ChangeStream#event:error"><a href="ChangeStream.html#event:error">error</a></li>
</ul>
</li>
<li class="item" data-name="ClientSession">
<span class="title">
<a href="ClientSession.html">ClientSession</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="ClientSession#id"><a href="ClientSession.html#id">id</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="ClientSession#abortTransaction"><a href="ClientSession.html#abortTransaction">abortTransaction</a></li>
<li data-name="ClientSession#advanceOperationTime"><a href="ClientSession.html#advanceOperationTime">advanceOperationTime</a></li>
<li data-name="ClientSession#commitTransaction"><a href="ClientSession.html#commitTransaction">commitTransaction</a></li>
<li data-name="ClientSession#endSession"><a href="ClientSession.html#endSession">endSession</a></li>
<li data-name="ClientSession#equals"><a href="ClientSession.html#equals">equals</a></li>
<li data-name="ClientSession#incrementTransactionNumber"><a href="ClientSession.html#incrementTransactionNumber">incrementTransactionNumber</a></li>
<li data-name="ClientSession#inTransaction"><a href="ClientSession.html#inTransaction">inTransaction</a></li>
<li data-name="ClientSession#startTransaction"><a href="ClientSession.html#startTransaction">startTransaction</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Code">
<span class="title">
<a href="Code.html">Code</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Collection">
<span class="title">
<a href="Collection.html">Collection</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="Collection~aggregationCallback"><a href="Collection.html#~aggregationCallback">aggregationCallback</a></li>
<li data-name="Collection~bulkWriteOpCallback"><a href="Collection.html#~bulkWriteOpCallback">bulkWriteOpCallback</a></li>
<li data-name="Collection~BulkWriteOpResult"><a href="Collection.html#~BulkWriteOpResult">BulkWriteOpResult</a></li>
<li data-name="Collection~collectionResultCallback"><a href="Collection.html#~collectionResultCallback">collectionResultCallback</a></li>
<li data-name="Collection~countCallback"><a href="Collection.html#~countCallback">countCallback</a></li>
<li data-name="Collection~deleteWriteOpCallback"><a href="Collection.html#~deleteWriteOpCallback">deleteWriteOpCallback</a></li>
<li data-name="Collection~deleteWriteOpResult"><a href="Collection.html#~deleteWriteOpResult">deleteWriteOpResult</a></li>
<li data-name="Collection~findAndModifyCallback"><a href="Collection.html#~findAndModifyCallback">findAndModifyCallback</a></li>
<li data-name="Collection~findAndModifyWriteOpResult"><a href="Collection.html#~findAndModifyWriteOpResult">findAndModifyWriteOpResult</a></li>
<li data-name="Collection~insertOneWriteOpCallback"><a href="Collection.html#~insertOneWriteOpCallback">insertOneWriteOpCallback</a></li>
<li data-name="Collection~insertOneWriteOpResult"><a href="Collection.html#~insertOneWriteOpResult">insertOneWriteOpResult</a></li>
<li data-name="Collection~insertWriteOpCallback"><a href="Collection.html#~insertWriteOpCallback">insertWriteOpCallback</a></li>
<li data-name="Collection~insertWriteOpResult"><a href="Collection.html#~insertWriteOpResult">insertWriteOpResult</a></li>
<li data-name="Collection~parallelCollectionScanCallback"><a href="Collection.html#~parallelCollectionScanCallback">parallelCollectionScanCallback</a></li>
<li data-name="Collection~resultCallback"><a href="Collection.html#~resultCallback">resultCallback</a></li>
<li data-name="Collection~updateWriteOpCallback"><a href="Collection.html#~updateWriteOpCallback">updateWriteOpCallback</a></li>
<li data-name="Collection~updateWriteOpResult"><a href="Collection.html#~updateWriteOpResult">updateWriteOpResult</a></li>
<li data-name="Collection~writeOpCallback"><a href="Collection.html#~writeOpCallback">writeOpCallback</a></li>
<li data-name="Collection~WriteOpResult"><a href="Collection.html#~WriteOpResult">WriteOpResult</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Collection#aggregate"><a href="Collection.html#aggregate">aggregate</a></li>
<li data-name="Collection#bulkWrite"><a href="Collection.html#bulkWrite">bulkWrite</a></li>
<li data-name="Collection#count"><a href="Collection.html#count">count</a></li>
<li data-name="Collection#countDocuments"><a href="Collection.html#countDocuments">countDocuments</a></li>
<li data-name="Collection#createIndex"><a href="Collection.html#createIndex">createIndex</a></li>
<li data-name="Collection#createIndexes"><a href="Collection.html#createIndexes">createIndexes</a></li>
<li data-name="Collection#deleteMany"><a href="Collection.html#deleteMany">deleteMany</a></li>
<li data-name="Collection#deleteOne"><a href="Collection.html#deleteOne">deleteOne</a></li>
<li data-name="Collection#distinct"><a href="Collection.html#distinct">distinct</a></li>
<li data-name="Collection#drop"><a href="Collection.html#drop">drop</a></li>
<li data-name="Collection#dropAllIndexes"><a href="Collection.html#dropAllIndexes">dropAllIndexes</a></li>
<li data-name="Collection#dropIndex"><a href="Collection.html#dropIndex">dropIndex</a></li>
<li data-name="Collection#dropIndexes"><a href="Collection.html#dropIndexes">dropIndexes</a></li>
<li data-name="Collection#ensureIndex"><a href="Collection.html#ensureIndex">ensureIndex</a></li>
<li data-name="Collection#estimatedDocumentCount"><a href="Collection.html#estimatedDocumentCount">estimatedDocumentCount</a></li>
<li data-name="Collection#find"><a href="Collection.html#find">find</a></li>
<li data-name="Collection#findAndModify"><a href="Collection.html#findAndModify">findAndModify</a></li>
<li data-name="Collection#findAndRemove"><a href="Collection.html#findAndRemove">findAndRemove</a></li>
<li data-name="Collection#findOne"><a href="Collection.html#findOne">findOne</a></li>
<li data-name="Collection#findOneAndDelete"><a href="Collection.html#findOneAndDelete">findOneAndDelete</a></li>
<li data-name="Collection#findOneAndReplace"><a href="Collection.html#findOneAndReplace">findOneAndReplace</a></li>
<li data-name="Collection#findOneAndUpdate"><a href="Collection.html#findOneAndUpdate">findOneAndUpdate</a></li>
<li data-name="Collection#geoHaystackSearch"><a href="Collection.html#geoHaystackSearch">geoHaystackSearch</a></li>
<li data-name="Collection#group"><a href="Collection.html#group">group</a></li>
<li data-name="Collection#indexes"><a href="Collection.html#indexes">indexes</a></li>
<li data-name="Collection#indexExists"><a href="Collection.html#indexExists">indexExists</a></li>
<li data-name="Collection#indexInformation"><a href="Collection.html#indexInformation">indexInformation</a></li>
<li data-name="Collection#initializeOrderedBulkOp"><a href="Collection.html#initializeOrderedBulkOp">initializeOrderedBulkOp</a></li>
<li data-name="Collection#initializeUnorderedBulkOp"><a href="Collection.html#initializeUnorderedBulkOp">initializeUnorderedBulkOp</a></li>
<li data-name="Collection#insert"><a href="Collection.html#insert">insert</a></li>
<li data-name="Collection#insertMany"><a href="Collection.html#insertMany">insertMany</a></li>
<li data-name="Collection#insertOne"><a href="Collection.html#insertOne">insertOne</a></li>
<li data-name="Collection#isCapped"><a href="Collection.html#isCapped">isCapped</a></li>
<li data-name="Collection#listIndexes"><a href="Collection.html#listIndexes">listIndexes</a></li>
<li data-name="Collection#mapReduce"><a href="Collection.html#mapReduce">mapReduce</a></li>
<li data-name="Collection#options"><a href="Collection.html#options">options</a></li>
<li data-name="Collection#parallelCollectionScan"><a href="Collection.html#parallelCollectionScan">parallelCollectionScan</a></li>
<li data-name="Collection#reIndex"><a href="Collection.html#reIndex">reIndex</a></li>
<li data-name="Collection#remove"><a href="Collection.html#remove">remove</a></li>
<li data-name="Collection#rename"><a href="Collection.html#rename">rename</a></li>
<li data-name="Collection#replaceOne"><a href="Collection.html#replaceOne">replaceOne</a></li>
<li data-name="Collection#save"><a href="Collection.html#save">save</a></li>
<li data-name="Collection#stats"><a href="Collection.html#stats">stats</a></li>
<li data-name="Collection#update"><a href="Collection.html#update">update</a></li>
<li data-name="Collection#updateMany"><a href="Collection.html#updateMany">updateMany</a></li>
<li data-name="Collection#updateOne"><a href="Collection.html#updateOne">updateOne</a></li>
<li data-name="Collection#watch"><a href="Collection.html#watch">watch</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="CommandCursor">
<span class="title">
<a href="CommandCursor.html">CommandCursor</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="CommandCursor~endCallback"><a href="CommandCursor.html#~endCallback">endCallback</a></li>
<li data-name="CommandCursor~iteratorCallback"><a href="CommandCursor.html#~iteratorCallback">iteratorCallback</a></li>
<li data-name="CommandCursor~resultCallback"><a href="CommandCursor.html#~resultCallback">resultCallback</a></li>
<li data-name="CommandCursor~toArrayResultCallback"><a href="CommandCursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="CommandCursor#batchSize"><a href="CommandCursor.html#batchSize">batchSize</a></li>
<li data-name="CommandCursor#clone"><a href="CommandCursor.html#clone">clone</a></li>
<li data-name="CommandCursor#close"><a href="CommandCursor.html#close">close</a></li>
<li data-name="CommandCursor#each"><a href="CommandCursor.html#each">each</a></li>
<li data-name="CommandCursor#hasNext"><a href="CommandCursor.html#hasNext">hasNext</a></li>
<li data-name="CommandCursor#isClosed"><a href="CommandCursor.html#isClosed">isClosed</a></li>
<li data-name="CommandCursor#maxTimeMS"><a href="CommandCursor.html#maxTimeMS">maxTimeMS</a></li>
<li data-name="CommandCursor#next"><a href="CommandCursor.html#next">next</a></li>
<li data-name="CommandCursor#pause"><a href="CommandCursor.html#pause">pause</a></li>
<li data-name="CommandCursor#pipe"><a href="CommandCursor.html#pipe">pipe</a></li>
<li data-name="CommandCursor#read"><a href="CommandCursor.html#read">read</a></li>
<li data-name="CommandCursor#resume"><a href="CommandCursor.html#resume">resume</a></li>
<li data-name="CommandCursor#rewind"><a href="CommandCursor.html#rewind">rewind</a></li>
<li data-name="CommandCursor#setEncoding"><a href="CommandCursor.html#setEncoding">setEncoding</a></li>
<li data-name="CommandCursor#setReadPreference"><a href="CommandCursor.html#setReadPreference">setReadPreference</a></li>
<li data-name="CommandCursor#toArray"><a href="CommandCursor.html#toArray">toArray</a></li>
<li data-name="CommandCursor#unpipe"><a href="CommandCursor.html#unpipe">unpipe</a></li>
<li data-name="CommandCursor#unshift"><a href="CommandCursor.html#unshift">unshift</a></li>
<li data-name="CommandCursor#wrap"><a href="CommandCursor.html#wrap">wrap</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="CommandCursor#event:close"><a href="CommandCursor.html#event:close">close</a></li>
<li data-name="CommandCursor#event:data"><a href="CommandCursor.html#event:data">data</a></li>
<li data-name="CommandCursor#event:end"><a href="CommandCursor.html#event:end">end</a></li>
<li data-name="CommandCursor#event:readable"><a href="CommandCursor.html#event:readable">readable</a></li>
</ul>
</li>
<li class="item" data-name="Cursor">
<span class="title">
<a href="Cursor.html">Cursor</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="Cursor~countResultCallback"><a href="Cursor.html#~countResultCallback">countResultCallback</a></li>
<li data-name="Cursor~endCallback"><a href="Cursor.html#~endCallback">endCallback</a></li>
<li data-name="Cursor~iteratorCallback"><a href="Cursor.html#~iteratorCallback">iteratorCallback</a></li>
<li data-name="Cursor~resultCallback"><a href="Cursor.html#~resultCallback">resultCallback</a></li>
<li data-name="Cursor~toArrayResultCallback"><a href="Cursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Cursor#addCursorFlag"><a href="Cursor.html#addCursorFlag">addCursorFlag</a></li>
<li data-name="Cursor#addQueryModifier"><a href="Cursor.html#addQueryModifier">addQueryModifier</a></li>
<li data-name="Cursor#batchSize"><a href="Cursor.html#batchSize">batchSize</a></li>
<li data-name="Cursor#clone"><a href="Cursor.html#clone">clone</a></li>
<li data-name="Cursor#close"><a href="Cursor.html#close">close</a></li>
<li data-name="Cursor#collation"><a href="Cursor.html#collation">collation</a></li>
<li data-name="Cursor#comment"><a href="Cursor.html#comment">comment</a></li>
<li data-name="Cursor#count"><a href="Cursor.html#count">count</a></li>
<li data-name="Cursor#each"><a href="Cursor.html#each">each</a></li>
<li data-name="Cursor#explain"><a href="Cursor.html#explain">explain</a></li>
<li data-name="Cursor#filter"><a href="Cursor.html#filter">filter</a></li>
<li data-name="Cursor#forEach"><a href="Cursor.html#forEach">forEach</a></li>
<li data-name="Cursor#hasNext"><a href="Cursor.html#hasNext">hasNext</a></li>
<li data-name="Cursor#hint"><a href="Cursor.html#hint">hint</a></li>
<li data-name="Cursor#isClosed"><a href="Cursor.html#isClosed">isClosed</a></li>
<li data-name="Cursor#limit"><a href="Cursor.html#limit">limit</a></li>
<li data-name="Cursor#map"><a href="Cursor.html#map">map</a></li>
<li data-name="Cursor#max"><a href="Cursor.html#max">max</a></li>
<li data-name="Cursor#maxAwaitTimeMS"><a href="Cursor.html#maxAwaitTimeMS">maxAwaitTimeMS</a></li>
<li data-name="Cursor#maxScan"><a href="Cursor.html#maxScan">maxScan</a></li>
<li data-name="Cursor#maxTimeMS"><a href="Cursor.html#maxTimeMS">maxTimeMS</a></li>
<li data-name="Cursor#min"><a href="Cursor.html#min">min</a></li>
<li data-name="Cursor#next"><a href="Cursor.html#next">next</a></li>
<li data-name="Cursor#pause"><a href="Cursor.html#pause">pause</a></li>
<li data-name="Cursor#pipe"><a href="Cursor.html#pipe">pipe</a></li>
<li data-name="Cursor#project"><a href="Cursor.html#project">project</a></li>
<li data-name="Cursor#read"><a href="Cursor.html#read">read</a></li>
<li data-name="Cursor#resume"><a href="Cursor.html#resume">resume</a></li>
<li data-name="Cursor#returnKey"><a href="Cursor.html#returnKey">returnKey</a></li>
<li data-name="Cursor#rewind"><a href="Cursor.html#rewind">rewind</a></li>
<li data-name="Cursor#setCursorOption"><a href="Cursor.html#setCursorOption">setCursorOption</a></li>
<li data-name="Cursor#setEncoding"><a href="Cursor.html#setEncoding">setEncoding</a></li>
<li data-name="Cursor#setReadPreference"><a href="Cursor.html#setReadPreference">setReadPreference</a></li>
<li data-name="Cursor#showRecordId"><a href="Cursor.html#showRecordId">showRecordId</a></li>
<li data-name="Cursor#skip"><a href="Cursor.html#skip">skip</a></li>
<li data-name="Cursor#snapshot"><a href="Cursor.html#snapshot">snapshot</a></li>
<li data-name="Cursor#sort"><a href="Cursor.html#sort">sort</a></li>
<li data-name="Cursor#stream"><a href="Cursor.html#stream">stream</a></li>
<li data-name="Cursor#toArray"><a href="Cursor.html#toArray">toArray</a></li>
<li data-name="Cursor#transformStream"><a href="Cursor.html#transformStream">transformStream</a></li>
<li data-name="Cursor#unpipe"><a href="Cursor.html#unpipe">unpipe</a></li>
<li data-name="Cursor#unshift"><a href="Cursor.html#unshift">unshift</a></li>
<li data-name="Cursor#wrap"><a href="Cursor.html#wrap">wrap</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="Cursor#event:close"><a href="Cursor.html#event:close">close</a></li>
<li data-name="Cursor#event:data"><a href="Cursor.html#event:data">data</a></li>
<li data-name="Cursor#event:end"><a href="Cursor.html#event:end">end</a></li>
<li data-name="Cursor#event:readable"><a href="Cursor.html#event:readable">readable</a></li>
</ul>
</li>
<li class="item" data-name="Db">
<span class="title">
<a href="Db.html">Db</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="Db#profilingInfo"><a href="Db.html#profilingInfo">profilingInfo</a></li>
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="Db~collectionResultCallback"><a href="Db.html#~collectionResultCallback">collectionResultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Db#addUser"><a href="Db.html#addUser">addUser</a></li>
<li data-name="Db#admin"><a href="Db.html#admin">admin</a></li>
<li data-name="Db#collection"><a href="Db.html#collection">collection</a></li>
<li data-name="Db#collections"><a href="Db.html#collections">collections</a></li>
<li data-name="Db#command"><a href="Db.html#command">command</a></li>
<li data-name="Db#createCollection"><a href="Db.html#createCollection">createCollection</a></li>
<li data-name="Db#createIndex"><a href="Db.html#createIndex">createIndex</a></li>
<li data-name="Db#dropCollection"><a href="Db.html#dropCollection">dropCollection</a></li>
<li data-name="Db#dropDatabase"><a href="Db.html#dropDatabase">dropDatabase</a></li>
<li data-name="Db#ensureIndex"><a href="Db.html#ensureIndex">ensureIndex</a></li>
<li data-name="Db#eval"><a href="Db.html#eval">eval</a></li>
<li data-name="Db#executeDbAdminCommand"><a href="Db.html#executeDbAdminCommand">executeDbAdminCommand</a></li>
<li data-name="Db#indexInformation"><a href="Db.html#indexInformation">indexInformation</a></li>
<li data-name="Db#listCollections"><a href="Db.html#listCollections">listCollections</a></li>
<li data-name="Db#profilingLevel"><a href="Db.html#profilingLevel">profilingLevel</a></li>
<li data-name="Db#removeUser"><a href="Db.html#removeUser">removeUser</a></li>
<li data-name="Db#renameCollection"><a href="Db.html#renameCollection">renameCollection</a></li>
<li data-name="Db#setProfilingLevel"><a href="Db.html#setProfilingLevel">setProfilingLevel</a></li>
<li data-name="Db#stats"><a href="Db.html#stats">stats</a></li>
<li data-name="Db#unref"><a href="Db.html#unref">unref</a></li>
<li data-name="Db#watch"><a href="Db.html#watch">watch</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="Db#event:close"><a href="Db.html#event:close">close</a></li>
<li data-name="Db#event:error"><a href="Db.html#event:error">error</a></li>
<li data-name="Db#event:fullsetup"><a href="Db.html#event:fullsetup">fullsetup</a></li>
<li data-name="Db#event:parseError"><a href="Db.html#event:parseError">parseError</a></li>
<li data-name="Db#event:reconnect"><a href="Db.html#event:reconnect">reconnect</a></li>
<li data-name="Db#event:timeout"><a href="Db.html#event:timeout">timeout</a></li>
</ul>
</li>
<li class="item" data-name="DBRef">
<span class="title">
<a href="DBRef.html">DBRef</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Decimal128">
<span class="title">
<a href="Decimal128.html">Decimal128</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Decimal128#toString"><a href="Decimal128.html#toString">toString</a></li>
<li data-name="Decimal128.fromString"><a href="Decimal128.html#.fromString">fromString</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Double">
<span class="title">
<a href="Double.html">Double</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Double#valueOf"><a href="Double.html#valueOf">valueOf</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="FindOperators">
<span class="title">
<a href="FindOperators.html">FindOperators</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="FindOperators#delete"><a href="FindOperators.html#delete">delete</a></li>
<li data-name="FindOperators#deleteOne"><a href="FindOperators.html#deleteOne">deleteOne</a></li>
<li data-name="FindOperators#remove"><a href="FindOperators.html#remove">remove</a></li>
<li data-name="FindOperators#removeOne"><a href="FindOperators.html#removeOne">removeOne</a></li>
<li data-name="FindOperators#replaceOne"><a href="FindOperators.html#replaceOne">replaceOne</a></li>
<li data-name="FindOperators#update"><a href="FindOperators.html#update">update</a></li>
<li data-name="FindOperators#updateOne"><a href="FindOperators.html#updateOne">updateOne</a></li>
<li data-name="FindOperators#upsert"><a href="FindOperators.html#upsert">upsert</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="GridFSBucket">
<span class="title">
<a href="GridFSBucket.html">GridFSBucket</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="GridFSBucket~errorCallback"><a href="GridFSBucket.html#~errorCallback">errorCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="GridFSBucket#delete"><a href="GridFSBucket.html#delete">delete</a></li>
<li data-name="GridFSBucket#drop"><a href="GridFSBucket.html#drop">drop</a></li>
<li data-name="GridFSBucket#find"><a href="GridFSBucket.html#find">find</a></li>
<li data-name="GridFSBucket#openDownloadStream"><a href="GridFSBucket.html#openDownloadStream">openDownloadStream</a></li>
<li data-name="GridFSBucket#openDownloadStreamByName"><a href="GridFSBucket.html#openDownloadStreamByName">openDownloadStreamByName</a></li>
<li data-name="GridFSBucket#openUploadStream"><a href="GridFSBucket.html#openUploadStream">openUploadStream</a></li>
<li data-name="GridFSBucket#openUploadStreamWithId"><a href="GridFSBucket.html#openUploadStreamWithId">openUploadStreamWithId</a></li>
<li data-name="GridFSBucket#rename"><a href="GridFSBucket.html#rename">rename</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="GridFSBucket#event:index"><a href="GridFSBucket.html#event:index">index</a></li>
</ul>
</li>
<li class="item" data-name="GridFSBucketReadStream">
<span class="title">
<a href="GridFSBucketReadStream.html">GridFSBucketReadStream</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="GridFSBucketReadStream#_read"><a href="GridFSBucketReadStream.html#_read">_read</a></li>
<li data-name="GridFSBucketReadStream#abort"><a href="GridFSBucketReadStream.html#abort">abort</a></li>
<li data-name="GridFSBucketReadStream#end"><a href="GridFSBucketReadStream.html#end">end</a></li>
<li data-name="GridFSBucketReadStream#start"><a href="GridFSBucketReadStream.html#start">start</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="GridFSBucketReadStream#event:close"><a href="GridFSBucketReadStream.html#event:close">close</a></li>
<li data-name="GridFSBucketReadStream#event:data"><a href="GridFSBucketReadStream.html#event:data">data</a></li>
<li data-name="GridFSBucketReadStream#event:end"><a href="GridFSBucketReadStream.html#event:end">end</a></li>
<li data-name="GridFSBucketReadStream#event:error"><a href="GridFSBucketReadStream.html#event:error">error</a></li>
<li data-name="GridFSBucketReadStream#event:file"><a href="GridFSBucketReadStream.html#event:file">file</a></li>
</ul>
</li>
<li class="item" data-name="GridFSBucketWriteStream">
<span class="title">
<a href="GridFSBucketWriteStream.html">GridFSBucketWriteStream</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="GridFSBucketWriteStream#abort"><a href="GridFSBucketWriteStream.html#abort">abort</a></li>
<li data-name="GridFSBucketWriteStream#end"><a href="GridFSBucketWriteStream.html#end">end</a></li>
<li data-name="GridFSBucketWriteStream#write"><a href="GridFSBucketWriteStream.html#write">write</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="GridFSBucketWriteStream#event:error"><a href="GridFSBucketWriteStream.html#event:error">error</a></li>
<li data-name="GridFSBucketWriteStream#event:finish"><a href="GridFSBucketWriteStream.html#event:finish">finish</a></li>
</ul>
</li>
<li class="item" data-name="GridStore">
<span class="title">
<a href="GridStore.html">GridStore</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="GridStore.DEFAULT_CONTENT_TYPE"><a href="GridStore.html#.DEFAULT_CONTENT_TYPE">DEFAULT_CONTENT_TYPE</a></li>
<li data-name="GridStore.DEFAULT_ROOT_COLLECTION"><a href="GridStore.html#.DEFAULT_ROOT_COLLECTION">DEFAULT_ROOT_COLLECTION</a></li>
<li data-name="GridStore.IO_SEEK_CUR"><a href="GridStore.html#.IO_SEEK_CUR">IO_SEEK_CUR</a></li>
<li data-name="GridStore.IO_SEEK_END"><a href="GridStore.html#.IO_SEEK_END">IO_SEEK_END</a></li>
<li data-name="GridStore.IO_SEEK_SET"><a href="GridStore.html#.IO_SEEK_SET">IO_SEEK_SET</a></li>
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="GridStore~collectionCallback"><a href="GridStore.html#~collectionCallback">collectionCallback</a></li>
<li data-name="GridStore~gridStoreCallback"><a href="GridStore.html#~gridStoreCallback">gridStoreCallback</a></li>
<li data-name="GridStore~openCallback"><a href="GridStore.html#~openCallback">openCallback</a></li>
<li data-name="GridStore~readCallback"><a href="GridStore.html#~readCallback">readCallback</a></li>
<li data-name="GridStore~readlinesCallback"><a href="GridStore.html#~readlinesCallback">readlinesCallback</a></li>
<li data-name="GridStore~resultCallback"><a href="GridStore.html#~resultCallback">resultCallback</a></li>
<li data-name="GridStore~tellCallback"><a href="GridStore.html#~tellCallback">tellCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="GridStore.exist"><a href="GridStore.html#.exist">exist</a></li>
<li data-name="GridStore.list"><a href="GridStore.html#.list">list</a></li>
<li data-name="GridStore.read"><a href="GridStore.html#.read">read</a></li>
<li data-name="GridStore.readlines"><a href="GridStore.html#.readlines">readlines</a></li>
<li data-name="GridStore.unlink"><a href="GridStore.html#.unlink">unlink</a></li>
<li data-name="GridStore#chunkCollection"><a href="GridStore.html#chunkCollection">chunkCollection</a></li>
<li data-name="GridStore#close"><a href="GridStore.html#close">close</a></li>
<li data-name="GridStore#collection"><a href="GridStore.html#collection">collection</a></li>
<li data-name="GridStore#destroy"><a href="GridStore.html#destroy">destroy</a></li>
<li data-name="GridStore#eof"><a href="GridStore.html#eof">eof</a></li>
<li data-name="GridStore#getc"><a href="GridStore.html#getc">getc</a></li>
<li data-name="GridStore#open"><a href="GridStore.html#open">open</a></li>
<li data-name="GridStore#puts"><a href="GridStore.html#puts">puts</a></li>
<li data-name="GridStore#read"><a href="GridStore.html#read">read</a></li>
<li data-name="GridStore#readlines"><a href="GridStore.html#readlines">readlines</a></li>
<li data-name="GridStore#rewind"><a href="GridStore.html#rewind">rewind</a></li>
<li data-name="GridStore#seek"><a href="GridStore.html#seek">seek</a></li>
<li data-name="GridStore#stream"><a href="GridStore.html#stream">stream</a></li>
<li data-name="GridStore#tell"><a href="GridStore.html#tell">tell</a></li>
<li data-name="GridStore#unlink"><a href="GridStore.html#unlink">unlink</a></li>
<li data-name="GridStore#write"><a href="GridStore.html#write">write</a></li>
<li data-name="GridStore#writeFile"><a href="GridStore.html#writeFile">writeFile</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="GridStoreStream">
<span class="title">
<a href="GridStoreStream.html">GridStoreStream</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="GridStoreStream#end"><a href="GridStoreStream.html#end">end</a></li>
<li data-name="GridStoreStream#pause"><a href="GridStoreStream.html#pause">pause</a></li>
<li data-name="GridStoreStream#pipe"><a href="GridStoreStream.html#pipe">pipe</a></li>
<li data-name="GridStoreStream#read"><a href="GridStoreStream.html#read">read</a></li>
<li data-name="GridStoreStream#resume"><a href="GridStoreStream.html#resume">resume</a></li>
<li data-name="GridStoreStream#setEncoding"><a href="GridStoreStream.html#setEncoding">setEncoding</a></li>
<li data-name="GridStoreStream#unpipe"><a href="GridStoreStream.html#unpipe">unpipe</a></li>
<li data-name="GridStoreStream#unshift"><a href="GridStoreStream.html#unshift">unshift</a></li>
<li data-name="GridStoreStream#wrap"><a href="GridStoreStream.html#wrap">wrap</a></li>
<li data-name="GridStoreStream#write"><a href="GridStoreStream.html#write">write</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="GridStoreStream#event:close"><a href="GridStoreStream.html#event:close">close</a></li>
<li data-name="GridStoreStream#event:data"><a href="GridStoreStream.html#event:data">data</a></li>
<li data-name="GridStoreStream#event:drain"><a href="GridStoreStream.html#event:drain">drain</a></li>
<li data-name="GridStoreStream#event:end"><a href="GridStoreStream.html#event:end">end</a></li>
<li data-name="GridStoreStream#event:error"><a href="GridStoreStream.html#event:error">error</a></li>
<li data-name="GridStoreStream#event:finish"><a href="GridStoreStream.html#event:finish">finish</a></li>
<li data-name="GridStoreStream#event:pipe"><a href="GridStoreStream.html#event:pipe">pipe</a></li>
<li data-name="GridStoreStream#event:readable"><a href="GridStoreStream.html#event:readable">readable</a></li>
<li data-name="GridStoreStream#event:unpipe"><a href="GridStoreStream.html#event:unpipe">unpipe</a></li>
</ul>
</li>
<li class="item" data-name="Int32">
<span class="title">
<a href="Int32.html">Int32</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Int32#valueOf"><a href="Int32.html#valueOf">valueOf</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Logger">
<span class="title">
<a href="Logger.html">Logger</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Logger.currentLogger"><a href="Logger.html#.currentLogger">currentLogger</a></li>
<li data-name="Logger.filter"><a href="Logger.html#.filter">filter</a></li>
<li data-name="Logger.reset"><a href="Logger.html#.reset">reset</a></li>
<li data-name="Logger.setCurrentLogger"><a href="Logger.html#.setCurrentLogger">setCurrentLogger</a></li>
<li data-name="Logger.setLevel"><a href="Logger.html#.setLevel">setLevel</a></li>
<li data-name="Logger#debug"><a href="Logger.html#debug">debug</a></li>
<li data-name="Logger#error"><a href="Logger.html#error">error</a></li>
<li data-name="Logger#info"><a href="Logger.html#info">info</a></li>
<li data-name="Logger#isDebug"><a href="Logger.html#isDebug">isDebug</a></li>
<li data-name="Logger#isError"><a href="Logger.html#isError">isError</a></li>
<li data-name="Logger#isInfo"><a href="Logger.html#isInfo">isInfo</a></li>
<li data-name="Logger#isWarn"><a href="Logger.html#isWarn">isWarn</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Long">
<span class="title">
<a href="Long.html">Long</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="Long.MAX_VALUE"><a href="Long.html#.MAX_VALUE">MAX_VALUE</a></li>
<li data-name="Long.MIN_VALUE"><a href="Long.html#.MIN_VALUE">MIN_VALUE</a></li>
<li data-name="Long.NEG_ONE"><a href="Long.html#.NEG_ONE">NEG_ONE</a></li>
<li data-name="Long.ONE"><a href="Long.html#.ONE">ONE</a></li>
<li data-name="Long.ZERO"><a href="Long.html#.ZERO">ZERO</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Long.fromBits"><a href="Long.html#.fromBits">fromBits</a></li>
<li data-name="Long.fromInt"><a href="Long.html#.fromInt">fromInt</a></li>
<li data-name="Long.fromNumber"><a href="Long.html#.fromNumber">fromNumber</a></li>
<li data-name="Long.fromString"><a href="Long.html#.fromString">fromString</a></li>
<li data-name="Long#add"><a href="Long.html#add">add</a></li>
<li data-name="Long#and"><a href="Long.html#and">and</a></li>
<li data-name="Long#compare"><a href="Long.html#compare">compare</a></li>
<li data-name="Long#div"><a href="Long.html#div">div</a></li>
<li data-name="Long#equals"><a href="Long.html#equals">equals</a></li>
<li data-name="Long#getHighBits"><a href="Long.html#getHighBits">getHighBits</a></li>
<li data-name="Long#getLowBits"><a href="Long.html#getLowBits">getLowBits</a></li>
<li data-name="Long#getLowBitsUnsigned"><a href="Long.html#getLowBitsUnsigned">getLowBitsUnsigned</a></li>
<li data-name="Long#getNumBitsAbs"><a href="Long.html#getNumBitsAbs">getNumBitsAbs</a></li>
<li data-name="Long#greaterThan"><a href="Long.html#greaterThan">greaterThan</a></li>
<li data-name="Long#greaterThanOrEqual"><a href="Long.html#greaterThanOrEqual">greaterThanOrEqual</a></li>
<li data-name="Long#isNegative"><a href="Long.html#isNegative">isNegative</a></li>
<li data-name="Long#isOdd"><a href="Long.html#isOdd">isOdd</a></li>
<li data-name="Long#isZero"><a href="Long.html#isZero">isZero</a></li>
<li data-name="Long#lessThan"><a href="Long.html#lessThan">lessThan</a></li>
<li data-name="Long#lessThanOrEqual"><a href="Long.html#lessThanOrEqual">lessThanOrEqual</a></li>
<li data-name="Long#modulo"><a href="Long.html#modulo">modulo</a></li>
<li data-name="Long#multiply"><a href="Long.html#multiply">multiply</a></li>
<li data-name="Long#negate"><a href="Long.html#negate">negate</a></li>
<li data-name="Long#not"><a href="Long.html#not">not</a></li>
<li data-name="Long#notEquals"><a href="Long.html#notEquals">notEquals</a></li>
<li data-name="Long#or"><a href="Long.html#or">or</a></li>
<li data-name="Long#shiftLeft"><a href="Long.html#shiftLeft">shiftLeft</a></li>
<li data-name="Long#shiftRight"><a href="Long.html#shiftRight">shiftRight</a></li>
<li data-name="Long#shiftRightUnsigned"><a href="Long.html#shiftRightUnsigned">shiftRightUnsigned</a></li>
<li data-name="Long#subtract"><a href="Long.html#subtract">subtract</a></li>
<li data-name="Long#toInt"><a href="Long.html#toInt">toInt</a></li>
<li data-name="Long#toJSON"><a href="Long.html#toJSON">toJSON</a></li>
<li data-name="Long#toNumber"><a href="Long.html#toNumber">toNumber</a></li>
<li data-name="Long#toString"><a href="Long.html#toString">toString</a></li>
<li data-name="Long#xor"><a href="Long.html#xor">xor</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MaxKey">
<span class="title">
<a href="MaxKey.html">MaxKey</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MinKey">
<span class="title">
<a href="MinKey.html">MinKey</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MongoClient">
<span class="title">
<a href="MongoClient.html">MongoClient</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="MongoClient~connectCallback"><a href="MongoClient.html#~connectCallback">connectCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="MongoClient.connect"><a href="MongoClient.html#.connect">connect</a></li>
<li data-name="MongoClient#close"><a href="MongoClient.html#close">close</a></li>
<li data-name="MongoClient#connect"><a href="MongoClient.html#connect">connect</a></li>
<li data-name="MongoClient#db"><a href="MongoClient.html#db">db</a></li>
<li data-name="MongoClient#isConnected"><a href="MongoClient.html#isConnected">isConnected</a></li>
<li data-name="MongoClient#logout"><a href="MongoClient.html#logout">logout</a></li>
<li data-name="MongoClient#startSession"><a href="MongoClient.html#startSession">startSession</a></li>
<li data-name="MongoClient#watch"><a href="MongoClient.html#watch">watch</a></li>
<li data-name="MongoClient#withSession"><a href="MongoClient.html#withSession">withSession</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MongoError">
<span class="title">
<a href="MongoError.html">MongoError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="MongoError.create"><a href="MongoError.html#.create">create</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MongoNetworkError">
<span class="title">
<a href="MongoNetworkError.html">MongoNetworkError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MongoParseError">
<span class="title">
<a href="MongoParseError.html">MongoParseError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Mongos">
<span class="title">
<a href="Mongos.html">Mongos</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="Mongos#event:close"><a href="Mongos.html#event:close">close</a></li>
<li data-name="Mongos#event:commandFailed"><a href="Mongos.html#event:commandFailed">commandFailed</a></li>
<li data-name="Mongos#event:commandStarted"><a href="Mongos.html#event:commandStarted">commandStarted</a></li>
<li data-name="Mongos#event:commandSucceeded"><a href="Mongos.html#event:commandSucceeded">commandSucceeded</a></li>
<li data-name="Mongos#event:connect"><a href="Mongos.html#event:connect">connect</a></li>
<li data-name="Mongos#event:error"><a href="Mongos.html#event:error">error</a></li>
<li data-name="Mongos#event:fullsetup"><a href="Mongos.html#event:fullsetup">fullsetup</a></li>
<li data-name="Mongos#event:ha"><a href="Mongos.html#event:ha">ha</a></li>
<li data-name="Mongos#event:joined"><a href="Mongos.html#event:joined">joined</a></li>
<li data-name="Mongos#event:left"><a href="Mongos.html#event:left">left</a></li>
<li data-name="Mongos#event:open"><a href="Mongos.html#event:open">open</a></li>
<li data-name="Mongos#event:parseError"><a href="Mongos.html#event:parseError">parseError</a></li>
<li data-name="Mongos#event:timeout"><a href="Mongos.html#event:timeout">timeout</a></li>
</ul>
</li>
<li class="item" data-name="MongoTimeoutError">
<span class="title">
<a href="MongoTimeoutError.html">MongoTimeoutError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MongoWriteConcernError">
<span class="title">
<a href="MongoWriteConcernError.html">MongoWriteConcernError</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="ObjectID">
<span class="title">
<a href="ObjectID.html">ObjectID</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="ObjectID.createFromHexString"><a href="ObjectID.html#.createFromHexString">createFromHexString</a></li>
<li data-name="ObjectID.createFromTime"><a href="ObjectID.html#.createFromTime">createFromTime</a></li>
<li data-name="ObjectID.isValid"><a href="ObjectID.html#.isValid">isValid</a></li>
<li data-name="ObjectID#equals"><a href="ObjectID.html#equals">equals</a></li>
<li data-name="ObjectID#generate"><a href="ObjectID.html#generate">generate</a></li>
<li data-name="ObjectID#getTimestamp"><a href="ObjectID.html#getTimestamp">getTimestamp</a></li>
<li data-name="ObjectID#toHexString"><a href="ObjectID.html#toHexString">toHexString</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="OrderedBulkOperation">
<span class="title">
<a href="OrderedBulkOperation.html">OrderedBulkOperation</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="OrderedBulkOperation~resultCallback"><a href="OrderedBulkOperation.html#~resultCallback">resultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="OrderedBulkOperation#execute"><a href="OrderedBulkOperation.html#execute">execute</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="ReplSet">
<span class="title">
<a href="ReplSet.html">ReplSet</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="ReplSet#event:close"><a href="ReplSet.html#event:close">close</a></li>
<li data-name="ReplSet#event:commandFailed"><a href="ReplSet.html#event:commandFailed">commandFailed</a></li>
<li data-name="ReplSet#event:commandStarted"><a href="ReplSet.html#event:commandStarted">commandStarted</a></li>
<li data-name="ReplSet#event:commandSucceeded"><a href="ReplSet.html#event:commandSucceeded">commandSucceeded</a></li>
<li data-name="ReplSet#event:connect"><a href="ReplSet.html#event:connect">connect</a></li>
<li data-name="ReplSet#event:error"><a href="ReplSet.html#event:error">error</a></li>
<li data-name="ReplSet#event:fullsetup"><a href="ReplSet.html#event:fullsetup">fullsetup</a></li>
<li data-name="ReplSet#event:ha"><a href="ReplSet.html#event:ha">ha</a></li>
<li data-name="ReplSet#event:joined"><a href="ReplSet.html#event:joined">joined</a></li>
<li data-name="ReplSet#event:left"><a href="ReplSet.html#event:left">left</a></li>
<li data-name="ReplSet#event:open"><a href="ReplSet.html#event:open">open</a></li>
<li data-name="ReplSet#event:parseError"><a href="ReplSet.html#event:parseError">parseError</a></li>
<li data-name="ReplSet#event:timeout"><a href="ReplSet.html#event:timeout">timeout</a></li>
</ul>
</li>
<li class="item" data-name="Server">
<span class="title">
<a href="Server.html">Server</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li data-name="Server#event:close"><a href="Server.html#event:close">close</a></li>
<li data-name="Server#event:commandFailed"><a href="Server.html#event:commandFailed">commandFailed</a></li>
<li data-name="Server#event:commandStarted"><a href="Server.html#event:commandStarted">commandStarted</a></li>
<li data-name="Server#event:commandSucceeded"><a href="Server.html#event:commandSucceeded">commandSucceeded</a></li>
<li data-name="Server#event:connect"><a href="Server.html#event:connect">connect</a></li>
<li data-name="Server#event:error"><a href="Server.html#event:error">error</a></li>
<li data-name="Server#event:parseError"><a href="Server.html#event:parseError">parseError</a></li>
<li data-name="Server#event:reconnect"><a href="Server.html#event:reconnect">reconnect</a></li>
<li data-name="Server#event:timeout"><a href="Server.html#event:timeout">timeout</a></li>
</ul>
</li>
<li class="item" data-name="Symbol">
<span class="title">
<a href="Symbol.html">Symbol</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Symbol#valueOf"><a href="Symbol.html#valueOf">valueOf</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Timestamp">
<span class="title">
<a href="Timestamp.html">Timestamp</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="Timestamp.MAX_VALUE"><a href="Timestamp.html#.MAX_VALUE">MAX_VALUE</a></li>
<li data-name="Timestamp.MIN_VALUE"><a href="Timestamp.html#.MIN_VALUE">MIN_VALUE</a></li>
<li data-name="Timestamp.NEG_ONE"><a href="Timestamp.html#.NEG_ONE">NEG_ONE</a></li>
<li data-name="Timestamp.ONE"><a href="Timestamp.html#.ONE">ONE</a></li>
<li data-name="Timestamp.ZERO"><a href="Timestamp.html#.ZERO">ZERO</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="Timestamp.fromBits"><a href="Timestamp.html#.fromBits">fromBits</a></li>
<li data-name="Timestamp.fromInt"><a href="Timestamp.html#.fromInt">fromInt</a></li>
<li data-name="Timestamp.fromNumber"><a href="Timestamp.html#.fromNumber">fromNumber</a></li>
<li data-name="Timestamp.fromString"><a href="Timestamp.html#.fromString">fromString</a></li>
<li data-name="Timestamp#add"><a href="Timestamp.html#add">add</a></li>
<li data-name="Timestamp#and"><a href="Timestamp.html#and">and</a></li>
<li data-name="Timestamp#compare"><a href="Timestamp.html#compare">compare</a></li>
<li data-name="Timestamp#div"><a href="Timestamp.html#div">div</a></li>
<li data-name="Timestamp#equals"><a href="Timestamp.html#equals">equals</a></li>
<li data-name="Timestamp#getHighBits"><a href="Timestamp.html#getHighBits">getHighBits</a></li>
<li data-name="Timestamp#getLowBits"><a href="Timestamp.html#getLowBits">getLowBits</a></li>
<li data-name="Timestamp#getLowBitsUnsigned"><a href="Timestamp.html#getLowBitsUnsigned">getLowBitsUnsigned</a></li>
<li data-name="Timestamp#getNumBitsAbs"><a href="Timestamp.html#getNumBitsAbs">getNumBitsAbs</a></li>
<li data-name="Timestamp#greaterThan"><a href="Timestamp.html#greaterThan">greaterThan</a></li>
<li data-name="Timestamp#greaterThanOrEqual"><a href="Timestamp.html#greaterThanOrEqual">greaterThanOrEqual</a></li>
<li data-name="Timestamp#isNegative"><a href="Timestamp.html#isNegative">isNegative</a></li>
<li data-name="Timestamp#isOdd"><a href="Timestamp.html#isOdd">isOdd</a></li>
<li data-name="Timestamp#isZero"><a href="Timestamp.html#isZero">isZero</a></li>
<li data-name="Timestamp#lessThan"><a href="Timestamp.html#lessThan">lessThan</a></li>
<li data-name="Timestamp#lessThanOrEqual"><a href="Timestamp.html#lessThanOrEqual">lessThanOrEqual</a></li>
<li data-name="Timestamp#modulo"><a href="Timestamp.html#modulo">modulo</a></li>
<li data-name="Timestamp#multiply"><a href="Timestamp.html#multiply">multiply</a></li>
<li data-name="Timestamp#negate"><a href="Timestamp.html#negate">negate</a></li>
<li data-name="Timestamp#not"><a href="Timestamp.html#not">not</a></li>
<li data-name="Timestamp#notEquals"><a href="Timestamp.html#notEquals">notEquals</a></li>
<li data-name="Timestamp#or"><a href="Timestamp.html#or">or</a></li>
<li data-name="Timestamp#shiftLeft"><a href="Timestamp.html#shiftLeft">shiftLeft</a></li>
<li data-name="Timestamp#shiftRight"><a href="Timestamp.html#shiftRight">shiftRight</a></li>
<li data-name="Timestamp#shiftRightUnsigned"><a href="Timestamp.html#shiftRightUnsigned">shiftRightUnsigned</a></li>
<li data-name="Timestamp#subtract"><a href="Timestamp.html#subtract">subtract</a></li>
<li data-name="Timestamp#toInt"><a href="Timestamp.html#toInt">toInt</a></li>
<li data-name="Timestamp#toJSON"><a href="Timestamp.html#toJSON">toJSON</a></li>
<li data-name="Timestamp#toNumber"><a href="Timestamp.html#toNumber">toNumber</a></li>
<li data-name="Timestamp#toString"><a href="Timestamp.html#toString">toString</a></li>
<li data-name="Timestamp#xor"><a href="Timestamp.html#xor">xor</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="UnorderedBulkOperation">
<span class="title">
<a href="UnorderedBulkOperation.html">UnorderedBulkOperation</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
<span class="subtitle">Typedefs</span>
<li data-name="UnorderedBulkOperation~resultCallback"><a href="UnorderedBulkOperation.html#~resultCallback">resultCallback</a></li>
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="UnorderedBulkOperation#execute"><a href="UnorderedBulkOperation.html#execute">execute</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="WriteConcernError">
<span class="title">
<a href="WriteConcernError.html">WriteConcernError</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="WriteConcernError#code"><a href="WriteConcernError.html#code">code</a></li>
<li data-name="WriteConcernError#errmsg"><a href="WriteConcernError.html#errmsg">errmsg</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="WriteConcernError#toJSON"><a href="WriteConcernError.html#toJSON">toJSON</a></li>
<li data-name="WriteConcernError#toString"><a href="WriteConcernError.html#toString">toString</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="WriteError">
<span class="title">
<a href="WriteError.html">WriteError</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li data-name="WriteError#code"><a href="WriteError.html#code">code</a></li>
<li data-name="WriteError#errmsg"><a href="WriteError.html#errmsg">errmsg</a></li>
<li data-name="WriteError#index"><a href="WriteError.html#index">index</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li data-name="WriteError#getOperation"><a href="WriteError.html#getOperation">getOperation</a></li>
<li data-name="WriteError#toJSON"><a href="WriteError.html#toJSON">toJSON</a></li>
<li data-name="WriteError#toString"><a href="WriteError.html#toString">toString</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
</ul>
</div>
</td>
<td valign='top'>
<div class="main">
<h1 class="page-title" data-filename="GridFSBucketReadStream.html">Class: GridFSBucketReadStream</h1>
<section>
<header>
<h2>
GridFSBucketReadStream
</h2>
</header>
<article>
<div class="container-overview">
<dt>
<div class="nameContainer">
<h4 class="name" id="GridFSBucketReadStream">
new GridFSBucketReadStream<span class="signature">(chunks, files, readPreference, filter, <span class="optional">options</span>)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{<a href="GridFSBucketReadStream.html">GridFSBucketReadStream</a>}</span>
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line28">line 28</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>A readable stream that enables you to read buffers from GridFS.</p>
<p>Do not instantiate this class directly. Use <code>openDownloadStream()</code> instead.</p>
</div>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>chunks</code></td>
<td class="type">
<span class="param-type"><a href="Collection.html">Collection</a></span>
</td>
<td class="description last">
<p>Handle for chunks collection</p></td>
</tr>
<tr>
<td class="name"><code>files</code></td>
<td class="type">
<span class="param-type"><a href="Collection.html">Collection</a></span>
</td>
<td class="description last">
<p>Handle for files collection</p></td>
</tr>
<tr>
<td class="name"><code>readPreference</code></td>
<td class="type">
<span class="param-type">Object</span>
</td>
<td class="description last">
<p>The read preference to use</p></td>
</tr>
<tr>
<td class="name"><code>filter</code></td>
<td class="type">
<span class="param-type">Object</span>
</td>
<td class="description last">
<p>The query to use to find the file document</p></td>
</tr>
<tr>
<td class="name"><code>options</code></td>
<td class="type">
<span class="param-type">Object</span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>Optional settings.</p>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>sort</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>Optional sort for the file find query</p></td>
</tr>
<tr>
<td class="name"><code>skip</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>Optional skip for the file find query</p></td>
</tr>
<tr>
<td class="name"><code>start</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>Optional 0-based offset in bytes to start streaming from</p></td>
</tr>
<tr>
<td class="name"><code>end</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>Optional 0-based offset in bytes to stop streaming before</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<dl class="details">
</dl>
<h5>Fires:</h5>
<ul>
<li><a href="GridFSBucketReadStream.html#event:error">GridFSBucketReadStream#event:error</a></li>
<li><a href="GridFSBucketReadStream.html#event:file">GridFSBucketReadStream#event:file</a></li>
</ul>
<h5>Returns:</h5>
GridFSBucketReadStream instance.
<br />
</dd>
</div>
<h3 class="subsection-title">Methods</h3>
<dl>
<dt>
<div class="nameContainer">
<h4 class="name" id="_read">
_read<span class="signature">()</span>
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line89">line 89</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Reads from the cursor and pushes to the stream.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="abort">
abort<span class="signature">(<span class="optional">callback</span>)</span>
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line141">line 141</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Marks this stream as aborted (will never push another <code>data</code> event)<br>
and kills the underlying cursor. Will emit the 'end' event, and then<br>
the 'close' event once the cursor is successfully killed.</p>
</div>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>callback</code></td>
<td class="type">
<span class="param-type"><a href="GridFSBucket.html#~errorCallback">GridFSBucket~errorCallback</a></span>
</td>
<td class="description last">
<span class="optional">optional</span>
<p>called when the cursor is successfully closed or an error occurred.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
</dl>
<h5>Fires:</h5>
<ul>
<li>GridFSBucketWriteStream#event:close</li>
<li>GridFSBucketWriteStream#event:end</li>
</ul>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="end">
end<span class="signature">(end)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{<a href="GridFSBucketReadStream.html">GridFSBucketReadStream</a>}</span>
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line124">line 124</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Sets the 0-based offset in bytes to start streaming from. Throws<br>
an error if this stream has entered flowing mode<br>
(e.g. if you've already called <code>on('data')</code>)</p>
</div>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>end</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<p>Offset in bytes to stop reading at</p></td>
</tr>
</tbody>
</table>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="start">
start<span class="signature">(start)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{<a href="GridFSBucketReadStream.html">GridFSBucketReadStream</a>}</span>
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line109">line 109</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Sets the 0-based offset in bytes to start streaming from. Throws<br>
an error if this stream has entered flowing mode<br>
(e.g. if you've already called <code>on('data')</code>)</p>
</div>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>start</code></td>
<td class="type">
<span class="param-type">Number</span>
</td>
<td class="description last">
<p>Offset in bytes to start reading at</p></td>
</tr>
</tbody>
</table>
<dl class="details">
</dl>
</dd>
</dl>
<h3 class="subsection-title">Events</h3>
<dl>
<dt>
<div class="nameContainer">
<h4 class="name" id="event:close">
close
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line77">line 77</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Fired when the stream is exhausted and the underlying cursor is killed</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">object</span>
</li>
</ul>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="event:data">
data
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line63">line 63</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Emitted when a chunk of data is available to be consumed.</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">object</span>
</li>
</ul>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="event:end">
end
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line70">line 70</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Fired when the stream is exhausted (no more data events).</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">object</span>
</li>
</ul>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="event:error">
error
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line48">line 48</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>An error occurred</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">Error</span>
</li>
</ul>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="event:file">
file
</h4>
<div class="tag-source">
<a href="lib_gridfs-stream_download.js.html">lib/gridfs-stream/download.js</a>, <a href="lib_gridfs-stream_download.js.html#line55">line 55</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Fires when the stream loaded the file document corresponding to the<br>
provided id.</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">object</span>
</li>
</ul>
<dl class="details">
</dl>
</dd>
</dl>
</article>
</section>
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.6</a> on Wed Jan 20 2021 10:00:48 GMT-0500 (Eastern Standard Time)
</footer>
</div>
</td>
</tr>
</table>
</div>
<script>prettyPrint();</script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/main.js"></script>
</body>
</html> | mongodb/node-mongodb-native | docs/3.1/api/GridFSBucketReadStream.html | HTML | apache-2.0 | 112,518 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Privileged app</title>
<meta name="description" content="A privileged app stub">
<!--
viewport allows you to control how mobile browsers will render your content.
width=device-width tells mobile browsers to render your content across the
full width of the screen, without being zoomed out (by default it would render
it at a desktop width, then shrink it to fit.)
Read more about it here:
https://developer.mozilla.org/Mozilla/Mobile/Viewport_meta_tag
-->
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/app.css">
<!--
Inline JavaScript code is not allowed for privileged and certified apps,
due to Content Security Policy restrictions.
You can read more about it here: https://developer.mozilla.org/Apps/CSP
Plus keeping your JavaScript separated from your HTML is always a good practice!
We're also using the 'defer' attribute. This allows us to tell the browser that
it should not wait for this file to load before continuing to load the rest of
resources in the page. Then, once everything has been loaded, it will parse and
execute the deferred files.
Read about defer: https://developer.mozilla.org/Web/HTML/Element/script#attr-defer
-->
<script type="text/javascript" src="js/app.js" defer></script>
<!--
The following two lines are for loading the localisations library
and the localisation data-so people can use the app in their
own language (as long as you provide translations).
-->
<link rel="prefetch" type="application/l10n" href="data/locales.ini" />
<script type="text/javascript" src="js/libs/l10n.js" defer></script>
</head>
<body>
<div id="flashLight"></div>
</body>
</html>
| mpizza/torch-demo | index.html | HTML | apache-2.0 | 1,987 |
#
# Cookbook Name:: hybris_app
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
#
# Cookbook Name:: hybris_app
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
localHybrisRoot = "#{node['hybris']['installRootPath']}"
hybris_app_propertyChanger "read last build number" do
propertyFile "#{localHybrisRoot}/lastDeployId"
propertyKey "lastDeployId"
createBackup false
action :read
end
deployNumber = 0.to_i
if node['hybris']['readedValue'].nil? || node['hybris']['readedValue'].empty?
deployNumber = 1.to_i
else
deployNumber = "#{node['hybris']['readedValue']}".to_i + 1
end
hybris_app_propertyChanger "set new build number" do
propertyFile "#{localHybrisRoot}/lastDeployId"
propertyKey "lastDeployId"
propertyValue deployNumber.to_s
createBackup false
action :set
end
node.set['hybris']['deployNumber'] = deployNumber.to_s.rjust(4, "0")
| andreas-winkler/chef | cookbooks/hybris_app/recipes/readlastid.rb | Ruby | apache-2.0 | 979 |
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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
*
*/
import _ from "lodash";
import {initialiseData} from "../common";
import {CORE_API} from "../common/services/core-api-utils";
import template from "./user-management.html";
import roles from "./system-roles";
const initialState = {
numAllowedWithoutFilter: 100,
roles
};
function filterUsers(users = [], qry = null) {
if (_.isEmpty(users) || qry === '') return [];
const qryStr = _.toLower(qry);
return users.filter(user => user.searchStr.indexOf(qryStr) > -1);
}
function enrichUsersWithSearchStr(user) {
const searchStr = _.toLower(user.userName);
return Object.assign({}, user, { searchStr });
}
function controller(serviceBroker) {
const vm = initialiseData(this, initialState);
serviceBroker.loadViewData(CORE_API.UserStore.findAll, [])
.then(result => {
vm.users = _.map(result.data, d => enrichUsersWithSearchStr(d));
if(vm.users.length <= vm.numAllowedWithoutFilter) {
vm.filteredUsers = vm.users;
}
});
serviceBroker.loadViewData(CORE_API.RoleStore.findAllRoles, [])
.then(result => vm.roles = result.data);
const refresh = () => {
vm.filteredUsers=[] = filterUsers(vm.users, vm.qry);
};
vm.onQueryStrChange = (qry) => {
vm.qry = qry;
refresh();
};
vm.dismiss = () => {
vm.newUser = null;
vm.selectedUser = null;
vm.newPassword1 = null;
vm.newPassword2 = null;
};
vm.userSelected = (user) => {
vm.dismiss();
vm.selectedUser = user;
vm.roleSelections = _.reduce(
user.roles,
(acc, role) => { acc[role] = true; return acc; },
{});
};
vm.addUserSelected = () => {
vm.dismiss();
vm.newUser = { userName: "", password: ""};
};
vm.isValidNewUser = (user) => {
return user.userName && user.password;
};
vm.registerUser = (user) => {
serviceBroker
.execute(CORE_API.UserStore.register, [user])
.then(
() => {
vm.userSelected(user);
vm.users = [...vm.users, user];
},
err => {
console.error("Error registering user: ", err);
vm.lastError = err.data;
}
);
};
vm.updateUser = (user, roleSelections, password1, password2) => {
if (password1 !== password2) {
vm.lastError = { id: "MISMATCH", message: "Passwords do not match"};
return;
}
const roles = _.chain(roleSelections)
.map((v, k) => v ? k : null) // get selected key name or null if not selected
.compact() // remove non selected names
.value();
serviceBroker
.execute(CORE_API.UserStore.updateRoles, [user.userName, roles])
.then(
() => {
user.roles = roles;
vm.dismiss();
},
e => {
vm.lastError = e.data;
}
);
if (password1) {
serviceBroker
.execute(CORE_API.UserStore.resetPassword, [user.userName, password1]);
}
};
vm.hasRole = (user, role) => {
const existingRoles = user.roles || [];
return existingRoles.indexOf(role) > -1;
};
vm.deleteUser = (user) => {
serviceBroker
.execute(CORE_API.UserStore.deleteUser, [user.userName])
.then(
() => {
vm.users = _.reject(vm.users, u => u === user);
vm.dismiss();
},
e => vm.lastError = e.data
);
return false; // prevent form submission
};
function setAllSelectionsTo(b) {
vm.roleSelections = _.reduce(
_.map(vm.roles, "key"),
(acc, k) => {
acc[k] = b;
return acc;
},
{});
}
vm.selectAll = () => {
setAllSelectionsTo(true);
};
vm.deselectAll = () => {
setAllSelectionsTo(false);
};
}
controller.$inject = [ "ServiceBroker" ];
export default {
template,
controller,
controllerAs: "ctrl",
bindToController: true,
scope: {}
};
| rovats/waltz | waltz-ng/client/user/user-management.js | JavaScript | apache-2.0 | 5,028 |
const React = require('react');
const classNames = require('classnames');
/**
* Component that renders a day on the calendar.
*/
class CalendarDayRenderer extends React.Component {
render() {
const day = this.props.day;
const month = this.props.month;
const dayClass = day.month() === month.month() ? classNames('calendar-day') : classNames('calendar-day-non-current');
return (
<table>
<tbody>
<tr>
<td className={dayClass}>{day.date()}</td>
</tr>
</tbody>
</table>
);
}
}
CalendarDayRenderer.propTypes = {
month: React.PropTypes.object.isRequired,
day: React.PropTypes.object.isRequired,
};
module.exports = CalendarDayRenderer;
| atsid/react-calendar-render | src/CalendarDayRenderer.js | JavaScript | apache-2.0 | 719 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MyProject01.Util.DllTools
{
class MemoryObject
{
public int Size;
public IntPtr Ptr;
}
class DllMemoryPool
{
private List<MemoryObject> _emptyList;
private int _emptyListCount;
private int _size;
// For debug
private long _bufferMaxCount;
private long _bufferCount;
public int Size
{
get { return _size; }
}
public DllMemoryPool(int size)
{
_bufferCount = _bufferMaxCount = 0;
_emptyListCount = 0;
_size = size;
_emptyList = new List<MemoryObject>();
}
public MemoryObject Get()
{
MemoryObject res;
lock (_emptyList)
{
if (_emptyList.Count > 0)
{
res = _emptyList[0];
_emptyList.RemoveAt(0);
}
else
{
res = new MemoryObject();
res.Size = _size;
res.Ptr = Marshal.AllocHGlobal(res.Size);
}
_bufferCount++;
if (_bufferCount > _bufferMaxCount)
_bufferMaxCount = _bufferCount;
}
return res;
}
public void Free(MemoryObject obj)
{
lock (_emptyList)
{
_emptyList.Add(obj);
}
}
}
class DllMemoryPoolCtrl
{
private List<DllMemoryPool> _poolList;
public DllMemoryPoolCtrl()
{
_poolList = new List<DllMemoryPool>();
}
public MemoryObject Get(int size)
{
MemoryObject res = null;
foreach (DllMemoryPool pool in _poolList)
{
if (pool.Size == size)
{
res = pool.Get();
break;
}
}
if(res == null)
{
DllMemoryPool pool = new DllMemoryPool(size);
_poolList.Add(pool);
res = pool.Get();
}
return res;
}
public void Free(MemoryObject obj)
{
foreach (DllMemoryPool pool in _poolList)
{
if (pool.Size == obj.Size)
{
pool.Free(obj);
break;
}
}
}
}
}
| a7866353/encog-dotnet-core_work01 | MyProject/MyProject01/Util/DllTools/DllMemoryPool.cs | C# | apache-2.0 | 2,668 |
/*
* 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.panorama.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/panorama-2019-07-24/DescribeNode" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeNodeResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The node's asset name.
* </p>
*/
private String assetName;
/**
* <p>
* The node's category.
* </p>
*/
private String category;
/**
* <p>
* When the node was created.
* </p>
*/
private java.util.Date createdTime;
/**
* <p>
* The node's description.
* </p>
*/
private String description;
/**
* <p>
* When the node was updated.
* </p>
*/
private java.util.Date lastUpdatedTime;
/**
* <p>
* The node's name.
* </p>
*/
private String name;
/**
* <p>
* The node's ID.
* </p>
*/
private String nodeId;
/**
* <p>
* The node's interface.
* </p>
*/
private NodeInterface nodeInterface;
/**
* <p>
* The account ID of the node's owner.
* </p>
*/
private String ownerAccount;
/**
* <p>
* The node's ARN.
* </p>
*/
private String packageArn;
/**
* <p>
* The node's package ID.
* </p>
*/
private String packageId;
/**
* <p>
* The node's package name.
* </p>
*/
private String packageName;
/**
* <p>
* The node's package version.
* </p>
*/
private String packageVersion;
/**
* <p>
* The node's patch version.
* </p>
*/
private String patchVersion;
/**
* <p>
* The node's asset name.
* </p>
*
* @param assetName
* The node's asset name.
*/
public void setAssetName(String assetName) {
this.assetName = assetName;
}
/**
* <p>
* The node's asset name.
* </p>
*
* @return The node's asset name.
*/
public String getAssetName() {
return this.assetName;
}
/**
* <p>
* The node's asset name.
* </p>
*
* @param assetName
* The node's asset name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withAssetName(String assetName) {
setAssetName(assetName);
return this;
}
/**
* <p>
* The node's category.
* </p>
*
* @param category
* The node's category.
* @see NodeCategory
*/
public void setCategory(String category) {
this.category = category;
}
/**
* <p>
* The node's category.
* </p>
*
* @return The node's category.
* @see NodeCategory
*/
public String getCategory() {
return this.category;
}
/**
* <p>
* The node's category.
* </p>
*
* @param category
* The node's category.
* @return Returns a reference to this object so that method calls can be chained together.
* @see NodeCategory
*/
public DescribeNodeResult withCategory(String category) {
setCategory(category);
return this;
}
/**
* <p>
* The node's category.
* </p>
*
* @param category
* The node's category.
* @return Returns a reference to this object so that method calls can be chained together.
* @see NodeCategory
*/
public DescribeNodeResult withCategory(NodeCategory category) {
this.category = category.toString();
return this;
}
/**
* <p>
* When the node was created.
* </p>
*
* @param createdTime
* When the node was created.
*/
public void setCreatedTime(java.util.Date createdTime) {
this.createdTime = createdTime;
}
/**
* <p>
* When the node was created.
* </p>
*
* @return When the node was created.
*/
public java.util.Date getCreatedTime() {
return this.createdTime;
}
/**
* <p>
* When the node was created.
* </p>
*
* @param createdTime
* When the node was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withCreatedTime(java.util.Date createdTime) {
setCreatedTime(createdTime);
return this;
}
/**
* <p>
* The node's description.
* </p>
*
* @param description
* The node's description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The node's description.
* </p>
*
* @return The node's description.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The node's description.
* </p>
*
* @param description
* The node's description.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* When the node was updated.
* </p>
*
* @param lastUpdatedTime
* When the node was updated.
*/
public void setLastUpdatedTime(java.util.Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
/**
* <p>
* When the node was updated.
* </p>
*
* @return When the node was updated.
*/
public java.util.Date getLastUpdatedTime() {
return this.lastUpdatedTime;
}
/**
* <p>
* When the node was updated.
* </p>
*
* @param lastUpdatedTime
* When the node was updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withLastUpdatedTime(java.util.Date lastUpdatedTime) {
setLastUpdatedTime(lastUpdatedTime);
return this;
}
/**
* <p>
* The node's name.
* </p>
*
* @param name
* The node's name.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The node's name.
* </p>
*
* @return The node's name.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The node's name.
* </p>
*
* @param name
* The node's name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The node's ID.
* </p>
*
* @param nodeId
* The node's ID.
*/
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
/**
* <p>
* The node's ID.
* </p>
*
* @return The node's ID.
*/
public String getNodeId() {
return this.nodeId;
}
/**
* <p>
* The node's ID.
* </p>
*
* @param nodeId
* The node's ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withNodeId(String nodeId) {
setNodeId(nodeId);
return this;
}
/**
* <p>
* The node's interface.
* </p>
*
* @param nodeInterface
* The node's interface.
*/
public void setNodeInterface(NodeInterface nodeInterface) {
this.nodeInterface = nodeInterface;
}
/**
* <p>
* The node's interface.
* </p>
*
* @return The node's interface.
*/
public NodeInterface getNodeInterface() {
return this.nodeInterface;
}
/**
* <p>
* The node's interface.
* </p>
*
* @param nodeInterface
* The node's interface.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withNodeInterface(NodeInterface nodeInterface) {
setNodeInterface(nodeInterface);
return this;
}
/**
* <p>
* The account ID of the node's owner.
* </p>
*
* @param ownerAccount
* The account ID of the node's owner.
*/
public void setOwnerAccount(String ownerAccount) {
this.ownerAccount = ownerAccount;
}
/**
* <p>
* The account ID of the node's owner.
* </p>
*
* @return The account ID of the node's owner.
*/
public String getOwnerAccount() {
return this.ownerAccount;
}
/**
* <p>
* The account ID of the node's owner.
* </p>
*
* @param ownerAccount
* The account ID of the node's owner.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withOwnerAccount(String ownerAccount) {
setOwnerAccount(ownerAccount);
return this;
}
/**
* <p>
* The node's ARN.
* </p>
*
* @param packageArn
* The node's ARN.
*/
public void setPackageArn(String packageArn) {
this.packageArn = packageArn;
}
/**
* <p>
* The node's ARN.
* </p>
*
* @return The node's ARN.
*/
public String getPackageArn() {
return this.packageArn;
}
/**
* <p>
* The node's ARN.
* </p>
*
* @param packageArn
* The node's ARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withPackageArn(String packageArn) {
setPackageArn(packageArn);
return this;
}
/**
* <p>
* The node's package ID.
* </p>
*
* @param packageId
* The node's package ID.
*/
public void setPackageId(String packageId) {
this.packageId = packageId;
}
/**
* <p>
* The node's package ID.
* </p>
*
* @return The node's package ID.
*/
public String getPackageId() {
return this.packageId;
}
/**
* <p>
* The node's package ID.
* </p>
*
* @param packageId
* The node's package ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withPackageId(String packageId) {
setPackageId(packageId);
return this;
}
/**
* <p>
* The node's package name.
* </p>
*
* @param packageName
* The node's package name.
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
/**
* <p>
* The node's package name.
* </p>
*
* @return The node's package name.
*/
public String getPackageName() {
return this.packageName;
}
/**
* <p>
* The node's package name.
* </p>
*
* @param packageName
* The node's package name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withPackageName(String packageName) {
setPackageName(packageName);
return this;
}
/**
* <p>
* The node's package version.
* </p>
*
* @param packageVersion
* The node's package version.
*/
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
/**
* <p>
* The node's package version.
* </p>
*
* @return The node's package version.
*/
public String getPackageVersion() {
return this.packageVersion;
}
/**
* <p>
* The node's package version.
* </p>
*
* @param packageVersion
* The node's package version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withPackageVersion(String packageVersion) {
setPackageVersion(packageVersion);
return this;
}
/**
* <p>
* The node's patch version.
* </p>
*
* @param patchVersion
* The node's patch version.
*/
public void setPatchVersion(String patchVersion) {
this.patchVersion = patchVersion;
}
/**
* <p>
* The node's patch version.
* </p>
*
* @return The node's patch version.
*/
public String getPatchVersion() {
return this.patchVersion;
}
/**
* <p>
* The node's patch version.
* </p>
*
* @param patchVersion
* The node's patch version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeNodeResult withPatchVersion(String patchVersion) {
setPatchVersion(patchVersion);
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 (getAssetName() != null)
sb.append("AssetName: ").append(getAssetName()).append(",");
if (getCategory() != null)
sb.append("Category: ").append(getCategory()).append(",");
if (getCreatedTime() != null)
sb.append("CreatedTime: ").append(getCreatedTime()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getLastUpdatedTime() != null)
sb.append("LastUpdatedTime: ").append(getLastUpdatedTime()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getNodeId() != null)
sb.append("NodeId: ").append(getNodeId()).append(",");
if (getNodeInterface() != null)
sb.append("NodeInterface: ").append(getNodeInterface()).append(",");
if (getOwnerAccount() != null)
sb.append("OwnerAccount: ").append(getOwnerAccount()).append(",");
if (getPackageArn() != null)
sb.append("PackageArn: ").append(getPackageArn()).append(",");
if (getPackageId() != null)
sb.append("PackageId: ").append(getPackageId()).append(",");
if (getPackageName() != null)
sb.append("PackageName: ").append(getPackageName()).append(",");
if (getPackageVersion() != null)
sb.append("PackageVersion: ").append(getPackageVersion()).append(",");
if (getPatchVersion() != null)
sb.append("PatchVersion: ").append(getPatchVersion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeNodeResult == false)
return false;
DescribeNodeResult other = (DescribeNodeResult) obj;
if (other.getAssetName() == null ^ this.getAssetName() == null)
return false;
if (other.getAssetName() != null && other.getAssetName().equals(this.getAssetName()) == false)
return false;
if (other.getCategory() == null ^ this.getCategory() == null)
return false;
if (other.getCategory() != null && other.getCategory().equals(this.getCategory()) == false)
return false;
if (other.getCreatedTime() == null ^ this.getCreatedTime() == null)
return false;
if (other.getCreatedTime() != null && other.getCreatedTime().equals(this.getCreatedTime()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getLastUpdatedTime() == null ^ this.getLastUpdatedTime() == null)
return false;
if (other.getLastUpdatedTime() != null && other.getLastUpdatedTime().equals(this.getLastUpdatedTime()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getNodeId() == null ^ this.getNodeId() == null)
return false;
if (other.getNodeId() != null && other.getNodeId().equals(this.getNodeId()) == false)
return false;
if (other.getNodeInterface() == null ^ this.getNodeInterface() == null)
return false;
if (other.getNodeInterface() != null && other.getNodeInterface().equals(this.getNodeInterface()) == false)
return false;
if (other.getOwnerAccount() == null ^ this.getOwnerAccount() == null)
return false;
if (other.getOwnerAccount() != null && other.getOwnerAccount().equals(this.getOwnerAccount()) == false)
return false;
if (other.getPackageArn() == null ^ this.getPackageArn() == null)
return false;
if (other.getPackageArn() != null && other.getPackageArn().equals(this.getPackageArn()) == false)
return false;
if (other.getPackageId() == null ^ this.getPackageId() == null)
return false;
if (other.getPackageId() != null && other.getPackageId().equals(this.getPackageId()) == false)
return false;
if (other.getPackageName() == null ^ this.getPackageName() == null)
return false;
if (other.getPackageName() != null && other.getPackageName().equals(this.getPackageName()) == false)
return false;
if (other.getPackageVersion() == null ^ this.getPackageVersion() == null)
return false;
if (other.getPackageVersion() != null && other.getPackageVersion().equals(this.getPackageVersion()) == false)
return false;
if (other.getPatchVersion() == null ^ this.getPatchVersion() == null)
return false;
if (other.getPatchVersion() != null && other.getPatchVersion().equals(this.getPatchVersion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAssetName() == null) ? 0 : getAssetName().hashCode());
hashCode = prime * hashCode + ((getCategory() == null) ? 0 : getCategory().hashCode());
hashCode = prime * hashCode + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getLastUpdatedTime() == null) ? 0 : getLastUpdatedTime().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getNodeId() == null) ? 0 : getNodeId().hashCode());
hashCode = prime * hashCode + ((getNodeInterface() == null) ? 0 : getNodeInterface().hashCode());
hashCode = prime * hashCode + ((getOwnerAccount() == null) ? 0 : getOwnerAccount().hashCode());
hashCode = prime * hashCode + ((getPackageArn() == null) ? 0 : getPackageArn().hashCode());
hashCode = prime * hashCode + ((getPackageId() == null) ? 0 : getPackageId().hashCode());
hashCode = prime * hashCode + ((getPackageName() == null) ? 0 : getPackageName().hashCode());
hashCode = prime * hashCode + ((getPackageVersion() == null) ? 0 : getPackageVersion().hashCode());
hashCode = prime * hashCode + ((getPatchVersion() == null) ? 0 : getPatchVersion().hashCode());
return hashCode;
}
@Override
public DescribeNodeResult clone() {
try {
return (DescribeNodeResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-panorama/src/main/java/com/amazonaws/services/panorama/model/DescribeNodeResult.java | Java | apache-2.0 | 21,744 |
/**
* Was created to test returning IterstorConverter class.
* Created on 08.05.2017.
* @author Matevosyan Vardan
* @version 1.0
*/
package ru.matevosyan; | VardanMatevosyan/Vardan-Git-Repository | CollectionsPro/iteratorOfIteratos/src/test/java/ru/matevosyan/package-info.java | Java | apache-2.0 | 159 |
var data = [
{title:'Basic Information', hasChild:true, test:'../examples/about_troy_more/basic_info.js'},
{title:'Vision Statement', hasChild:true, test:'../examples/about_troy_more/vision.js'},
{title:'ESLRs', hasChild:true, test:'../examples/about_troy_more/eslr_s.js'}
];
var tableview = Titanium.UI.createTableView({
data:data
});
tableview.addEventListener('click', function(e){
if(e.rowData.test){
var win = null;
win = Titanium.UI.createWindow({
url:e.rowData.test,
title:e.rowData.title,
backgroundColor:'#fff',
barColor:'#B22222'
});
if (e.index == 3)
{
win.hideTabBar();
}
Titanium.UI.currentTab.open(win,{animated:true});
}
});
Titanium.UI.currentWindow.add(tableview);
Titanium.UI.currentWindow.addEventListener('focus', function()
{
Ti.API.info('FOCUS RECEIVED IN base_ui');
});
| voidvoxel/troyhigh | Resources/examples/about_troy.js | JavaScript | apache-2.0 | 822 |
"""Test suite for abdt_rbranchnaming."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
# cover those concerns.
#
# Concerns:
# [XB] review names that are globally known to be bad are not accepted
# [XB] tracker names that are globally known to be bad are not accepted
# [XC] names that are known to be potential reviews aren't accepted as trackers
# [XC] names that are known to be potential trackers aren't accepted as reviews
# [XD] ReviewBranches created by the scheme have the expected attributes
# [XD] ReviewBranches created by the scheme can create expected TrackerBranches
# [XD] TrackerBranches created by the scheme have the expected attributes
# [XD] there is a 1-1 relationship between tracker params and tracker names
# -----------------------------------------------------------------------------
# Tests:
# [ A] XXX: test_A_Breathing
# [XA] check_XA_Breathing
# [XB] check_XB_globally_invalid_review_tracker_names
# [XC] check_XC_potentially_valid_review_tracker_names
# [XD] check_XD_valid_reviews
# =============================================================================
from __future__ import absolute_import
import unittest
import abdt_namingtester
import abdt_rbranchnaming
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def make_naming(self):
return abdt_rbranchnaming.Naming()
def test_A_Breathing(self):
pass
def test_XA_Breathing(self):
abdt_namingtester.check_XA_Breathing(self)
def test_XB_globally_invalid_review_tracker_names(self):
abdt_namingtester.check_XB_globally_invalid_review_tracker_names(
self, self.make_naming())
def test_XC_potentially_valid_review_tracker_names(self):
abdt_namingtester.check_XC_potentially_valid_review_tracker_names(
self, self.make_naming())
def test_XD_valid_reviews(self):
names_to_properties = {}
for properties in abdt_namingtester.VALID_REVIEW_PROPERTIES:
name = 'r/{base}/{description}'.format(
description=properties.description,
base=properties.base)
assert name not in names_to_properties
names_to_properties[name] = properties
abdt_namingtester.check_XD_valid_reviews(
self, self.make_naming(), names_to_properties)
# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# 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.
# ------------------------------ END-OF-FILE ----------------------------------
| valhallasw/phabricator-tools | py/abd/abdt_rbranchnaming__t.py | Python | apache-2.0 | 3,352 |
package com.barryzhang.tcontributionsview.adapter;
/**
* https://github.com/barryhappy
* Created by Barry on 2016/11/22
*/
public class IntArraysContributionsViewAdapter extends AbstractArraysContributionsViewAdapter<Integer> {
public IntArraysContributionsViewAdapter() {
super();
}
public IntArraysContributionsViewAdapter(Integer[][] mArrays) {
super(mArrays);
}
@Override
protected int mapLevel(Integer from) {
return from;
}
}
| barryhappy/TContributionsView | tcontributionsview/src/main/java/com/barryzhang/tcontributionsview/adapter/IntArraysContributionsViewAdapter.java | Java | apache-2.0 | 491 |
/*
* Copyright 2012-2013 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 com.concert.domain;
import com.concert.domain.util.CustomDateTimeDeserializer;
import com.concert.domain.util.CustomDateTimeSerializer;
import com.concert.repository.redis.RedisJsonMapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import java.io.IOException;
import java.io.Serializable;
@Data
@Entity
@NoArgsConstructor
@EqualsAndHashCode(callSuper=false)
public class Aggregate extends BaseEntity implements Serializable, RedisJsonMapper<Aggregate>{
private static final long serialVersionUID = 1L;
@Column(nullable = false)
private Long ruleId;
@Column(nullable = false)
private String tenant;
@Column(nullable = false)
private Double score;
@Column(nullable = false)
private String externalId;
@Column(name = "from_date")
@JsonIgnore
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@JsonSerialize(using = CustomDateTimeSerializer.class)
@JsonDeserialize(using = CustomDateTimeDeserializer.class)
@CreatedDate
private DateTime fromDate;
@Column(name = "to_date")
@JsonIgnore
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@JsonSerialize(using = CustomDateTimeSerializer.class)
@JsonDeserialize(using = CustomDateTimeDeserializer.class)
@LastModifiedDate
private DateTime toDate;
@Override
public String toJsonString() {
final ObjectMapper jacksonObjectMapper = new ObjectMapper();
try {
return jacksonObjectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@Override
public Aggregate fromJson(String json) {
final ObjectMapper jacksonObjectMapper = new ObjectMapper();
try {
return jacksonObjectMapper.readValue(json, Aggregate.class);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| himanshuvirmani/concert | src/main/java/com/concert/domain/Aggregate.java | Java | apache-2.0 | 3,189 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.orange.web.exceptions;
/**
*
* @author lining
*/
public class ClassGeneratorException extends AbstractWebException{
/**
*
*/
private static final long serialVersionUID = 91046835177881915L;
public ClassGeneratorException(String message) {
super(message);
}
public ClassGeneratorException(Throwable cause) {
super(cause);
}
public ClassGeneratorException(String message, Throwable cause) {
super(message, cause);
}
}
| 15919873635/OrangeWeb | src/com/orange/web/exceptions/ClassGeneratorException.java | Java | apache-2.0 | 712 |
var VideoStreamUID = null;
var MousePosXY = new Array();
var MailType;
var BrowserVer = new BrowserVerChk();
var MsgArrayMove = new Array();
var unique;
var atmailRoot = '';
var MsgCacheLimit = 100;
var FieldInFocus = false;
var NewHeaderStyle = false;
var ComposeMode;
var ComposeModeStorage = null;
var oEdit1 = null;
var oPopup = null;
var ObjFolderBox;
var ObjMsgListBox;
var GlobalRow;
var Loaded;
var msgwinnum = 1;
window.onresize = FixResize;
// For login-light template
var AppColors = new Array();
//Border Background Txt Background
AppColors["Private"] = new Array("#185aad", "#78aad7", "#d3e3f2");
//AppColors["Private"] = new Array("#185aad", "#719ed7", "#a3c2e9");
AppColors["Shared"] = new Array("#8000ff", "#b95aee", "#dc97ef");
var ColorScheme = "Private";
function FCKeditor_OnComplete( editorInstance )
{
document.getElementById('ComposeMsgText___Frame').style.height = "500px";
}
function FixResize() {
centerObjWindow();
var size = document.body.clientWidth;
}
var MainNav = new Array();
MainNav["GrowTo"] = 12;
MainNav["MainNavCompose"] = new Array();
MainNav["MainNavCompose"]["EnlargeTimeout"] = null;
MainNav["MainNavCompose"]["ShrinkTimeout"] = null;
MainNav["MainNavCompose"]["Increment"] = 0;
MainNav["MainNavCompose"]["Top"] = 118;
MainNav["MainNavCompose"]["Left"] = 4;
MainNav["MainNavCompose"]["Width"] = 51;
MainNav["MainNavCompose"]["Height"] = 44;
MainNav["MainNavCompose"]["SRC"] = "icon_compose";
MainNav["MainNavChkMail"] = new Array();
MainNav["MainNavChkMail"]["EnlargeTimeout"] = null;
MainNav["MainNavChkMail"]["ShrinkTimeout"] = null;
MainNav["MainNavChkMail"]["Increment"] = 0;
MainNav["MainNavChkMail"]["Top"] = 94;
MainNav["MainNavChkMail"]["Left"] = 57;
MainNav["MainNavChkMail"]["Width"] = 64;
MainNav["MainNavChkMail"]["Height"] = 44;
MainNav["MainNavChkMail"]["SRC"] = "icon_chkmail";
MainNav["MainNavSettings"] = new Array();
MainNav["MainNavSettings"]["EnlargeTimeout"] = null;
MainNav["MainNavSettings"]["ShrinkTimeout"] = null;
MainNav["MainNavSettings"]["Increment"] = 0;
MainNav["MainNavSettings"]["Top"] = 50;
MainNav["MainNavSettings"]["Left"] = 99;
MainNav["MainNavSettings"]["Width"] = 49;
MainNav["MainNavSettings"]["Height"] = 44;
MainNav["MainNavSettings"]["SRC"] = "icon_settings";
MainNav["MainNavSearch"] = new Array();
MainNav["MainNavSearch"]["EnlargeTimeout"] = null;
MainNav["MainNavSearch"]["ShrinkTimeout"] = null;
MainNav["MainNavSearch"]["Increment"] = 0;
MainNav["MainNavSearch"]["Top"] = 3;
MainNav["MainNavSearch"]["Left"] = 117;
MainNav["MainNavSearch"]["Width"] = 51;
MainNav["MainNavSearch"]["Height"] = 44;
MainNav["MainNavSearch"]["SRC"] = "icon_search";
var MsgListData = new Array();
MsgListData["Data"] = new Array();
MsgListData["CurrentFolder"] = "";
MsgListData["Folders"] = new Array();
MsgListData["Views"] = new Array();
MsgListData["Views"]["MsgListViewer"] = true;
MsgListData["Views"]["MsgReader"] = false;
MsgListData["Views"]["MsgComposer"] = false;
MsgListData["Ctrl"] = new Array();
MsgListData["Ctrl"]["Initialised"] = false;
MsgListData["Ctrl"]["Timeout"] = null;
MsgListData["Ctrl"]["Selected"] = new Array();
MsgListData["Ctrl"]["SortCol"] = null;
MsgListData["Ctrl"]["SortDescending"] = new Array();
MsgListData["Ctrl"]["Loading"] = false;
MsgListData["Ctrl"]["CtrlKey"] = false;
MsgListData["Ctrl"]["ShiftKey"] = false;
MsgListData["Ctrl"]["DnD"] = new Array();
var MsgReaderData = new Array();
function createXMLHttpRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
alert("XMLHttpRequest not supported");
return null;
}
function ShowEmailSentNotice(Hide) {
document.getElementById("EmailSentNotice").style.display = (Hide) ? "none" : "";
if (!Hide) window.setTimeout("ShowEmailSentNotice(true);", 5000);
}
// Ajax objects
var MessagesReq = false;
var AddAbookReq = false;
var BlockSenderReq = false;
var MoveMessagesReq = false;
var ReadMsgReq = false;
var SendMessagesReq = false;
var MarkMessageReq = false;
var WebMailLoginReq = false;
var ReadMsgFoldersLoaded = false;
var ReadMsgReply = null;
var AddToDicReq = false;
// Spell check vars
var SpellChkWords = new Array();
var AjustedTxtArray = new Array();
var SpellChkReq = false;
// Message row functions
var onClickFunc = "MsgRowCtrl(this.rowIndex, 'Click', this.id);";
var onDblClickFunc = "MsgRowCtrl(this.rowIndex, 'DblClick', this.id);";
var onMouseOverFunc = "MsgRowCtrl(this.rowIndex, 'Over');";
var onMouseOutFunc = "MsgRowCtrl(this.rowIndex, 'Out');";
var onMouseDownFunc = "MsgRowCtrl(this.rowIndex, 'Down');";
var onMouseUpFunc = "MsgRowCtrl(this.rowIndex, 'Up');";
var onMouseMoveFunc = "MsgRowCtrl(this.rowIndex, 'Move');";
var onContextMenuFunc = "LoadContextMenu;";
// Return null for onselect
function filtervs() { return false; }
function MousePos(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft;
posy = e.clientY + document.body.scrollTop;
}
MousePosXY[0] = posx;
MousePosXY[1] = posy;
}
var prevComposeHeight = 0;
// Calculate the height for the HTML editor in Firefox
function CalcMsgComposeHeight(live) {
if(!live)
live = '';
// Don't run for IE, it supports height 100%
if (window.ActiveXObject) {
return;
}
// Find the height, minus our offset
var ComposeHeight = window.innerHeight - 250;
// Firefox should do height 100% - Calculate the offset below, temp workaround
if(document.getElementById('ComposeMsgTo').style.height == '40px') {
ComposeHeight = ComposeHeight - 20;
}
if(document.getElementById('ComposeMsgCc').style.height == '40px') {
ComposeHeight = ComposeHeight - 20;
}
if(document.getElementById('ComposeMsgBcc').style.height == '40px') {
ComposeHeight = ComposeHeight - 20;
}
// If BCC is enabled
if(document.getElementById('ComposeMsgBcc').style.display == "") {
ComposeHeight = ComposeHeight - 30;
}
if(document.getElementById('ComposeMsgAttachmentsRow').style.display == "") {
ComposeHeight = ComposeHeight - 30;
}
//if (ComposeHeight < 490) ComposeHeight = 400;
if(live && document.getElementById("MsgComposer").style.display == "") {
// Don't update if the same height
if(prevComposeHeight == ComposeHeight)
return;
oEdit1.height = ComposeHeight + "px";
//oEdit1.fullScreen();
//oEdit1.fullScreen();
prevComposeHeight = ComposeHeight;
} else {
return ComposeHeight + "px";
}
}
function CalcMsgRowHeight() {
// Compose page, resize the height for FF
//if(document.getElementById("MsgComposer").style.display == "") {
//oEdit1.height = CalcMsgComposeHeight();
//oEdit1.fullScreen();
//oEdit1.fullScreen();
//oEdit1.focus();
//}
var MsgHeight = (document.body.offsetHeight - 155 - document.body.scrollTop);
if (MsgHeight < 370) MsgHeight = 370;
// Calculate our row height, set the scrollbars on
MsgRowHeight = 18 * MsgListData["Ctrl"]["Increment"];
if(MsgRowHeight > MsgHeight)
ObjMsgListBox.style.overflowY = "scroll";
else
ObjMsgListBox.style.overflowY = "auto";
}
// Onresize event loader - Resize the content
function FixShowMail() {
centerObjAdvancedWindow();
if (navigator.userAgent.indexOf("Safari") != -1) {
var ReadWidth = document.body.offsetWidth - 190;
ObjMsgListBox.style.width = ReadWidth + 'px';
}
if (!window.ActiveXObject) {
document.getElementById("MsgListViewer").style.height = "";
document.body.scrollTop = "99999";
// Show mail box
var MsgHeight = (document.body.offsetHeight - 155 - document.body.scrollTop);
if (MsgHeight < 370) MsgHeight = 370;
ObjMsgListBox.style.height = MsgHeight + "px";
// Read mail boxs
var ReadHeight = (document.body.offsetHeight - 150 - document.body.scrollTop);
if (ReadHeight < 500) ReadHeight = 500;
document.getElementById("MsgReader").style.height = ReadHeight + "px";
if (document.getElementById("MsgReaderData")) document.getElementById("MsgReaderData").style.height = (ReadHeight - 60) + "px";
// Compose page
CalcMsgRowHeight();
document.body.scrollTop = "0";
}
}
function GrowPNG(ImageID, Action) {
if (Action == true) {
window.clearTimeout(MainNav[ImageID]["ShrinkTimeout"]);
MainNav[ImageID]["Increment"] ++;
} else {
window.clearTimeout(MainNav[ImageID]["EnlargeTimeout"]);
MainNav[ImageID]["Increment"] --;
}
ObjImage = document.getElementById(ImageID);
ObjImage.style.top = (MainNav[ImageID]["Top"] - (MainNav[ImageID]["Increment"] / 2)) + "px";
ObjImage.style.left = (MainNav[ImageID]["Left"] - (MainNav[ImageID]["Increment"] / 2)) + "px";
ObjImage.style.width = (MainNav[ImageID]["Width"] + MainNav[ImageID]["Increment"]) + "px";
ObjImage.style.height = (MainNav[ImageID]["Height"] + MainNav[ImageID]["Increment"]) + "px";
if (!window.ActiveXObject) {
ObjImage = document.getElementById(ImageID + "Img");
ObjImage.style.width = MainNav[ImageID]["Width"] + MainNav[ImageID]["Increment"];
ObjImage.style.height = MainNav[ImageID]["Height"] + MainNav[ImageID]["Increment"];
}
if (Action == true && MainNav[ImageID]["Increment"] < MainNav["GrowTo"]) {
MainNav[ImageID]["EnlargeTimeout"] = window.setTimeout("GrowPNG('" + ImageID + "', true)", 0);
} else if (Action == true) {
if (window.ActiveXObject) {
ObjImage.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/" + MainNav[ImageID]["SRC"] + "_big.png', sizingMethod='scale');";
} else {
ObjImage.src = "imgs/simple/" + MainNav[ImageID]["SRC"] + "_big.png";
}
}
if (Action == false && MainNav[ImageID]["Increment"] > 0) {
MainNav[ImageID]["ShrinkTimeout"] = window.setTimeout("GrowPNG('" + ImageID + "', false)", 10);
} else if (Action == false) {
if (window.ActiveXObject) {
ObjImage.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/" + MainNav[ImageID]["SRC"] + ".png', sizingMethod='scale');";
} else {
ObjImage.src = "imgs/simple/" + MainNav[ImageID]["SRC"] + ".png";
}
}
}
function MultiSelectDown(e) {
var EventTest = window.event ? event : e;
var WhichKey = EventTest.charCode? EventTest.charCode : EventTest.keyCode;
// Turn off for compose panel
if(document.getElementById("MsgComposer").style.display == "")
return WhichKey;
// If We are using Safari, the keycodes are different
//if(navigator.userAgent.indexOf("Safari") == -1) {
if(EventTest.shiftKey && !WhichKey) {
WhichKey = 16;
} else if(EventTest.altKey && !WhichKey) {
WhichKey = 17;
} else {
MsgListData["Ctrl"]["ShiftKey"] = false;
MsgListData["Ctrl"]["CtrlKey"] = false;
}
if (WhichKey && FieldInFocus == false) {
if (WhichKey == 16) { // Capture and remap Shift
MsgListData["Ctrl"]["ShiftKey"] = true;
} else if (WhichKey == 17) { // Capture and remap Ctrl
MsgListData["Ctrl"]["CtrlKey"] = true;
} else if ( WhichKey == 8 && FieldInFocus == false) { // Capture and remap backspace if not in text field
WhichKey = 505;
}
if (WhichKey != 505) {
WhichKey = ListBoxKeyCtrl(WhichKey);
}
if (WhichKey == 505) {
return false;
}
}
}
function MultiSelectUp(e) {
var EventTest = window.event ? event : e;
var WhichKey = EventTest.charCode? EventTest.charCode : EventTest.keyCode;
if (WhichKey && FieldInFocus == false) {
if (WhichKey == 16) { // Capture and remap Shift
MsgListData["Ctrl"]["ShiftKey"] = false;
} else if (WhichKey == 17) { // Capture and remap Ctrl
MsgListData["Ctrl"]["CtrlKey"] = false;
}
}
}
function NoSelectText() {
if (FieldInFocus == false) return false;
}
function SelectText() {
return true;
}
var ChkMailTimeout = null;
var LastUnreadMsgCount = 999999;
var PlaySound = false;
function ChMailInterval() {
// We are are viewing the calendar, do not show! Breaks the calendar UI
try {
if(CalendarInOperation == true) {
ChkMailTimeout = window.setTimeout("ChMailInterval()", MailRefreshTime);
return;
}
} catch(e) { }
// Reload the mailbox if no messages are selected to move, and the results are not the search window Trac #671 issue
if (MsgListData["Ctrl"]["Initialised"] == true && MsgListData["Ctrl"]["Loading"] == false && MsgListData["Views"]["MsgListViewer"] == true && MsgListData["Ctrl"]["Selected"].length == 0 && MsgListData["Ctrl"]["CtrlKey"] == false && MsgListData["Ctrl"]["ShiftKey"] == false && MsgListData["CurrentFolder"] != 'Search') {
PlaySound = true;
LoadMsgs(MsgListData["CurrentFolder"]);
ChkMailTimeout = window.setTimeout("ChMailInterval()", MailRefreshTime);
} else {
ChkMailTimeout = window.setTimeout("ChMailInterval()", 60000);
}
}
var ObjFadeWindow = null;
function PageLoaded(func, To, Cc, Bcc) {
if (func == "login") {
ObjFadeWindow = createObjFadeWindow();
document.body.appendChild(ObjFadeWindow);
}
if (MailRefreshTime < 60) MailRefreshTime = 60;
MailRefreshTime = MailRefreshTime * 1000;
ChkMailTimeout = window.setTimeout("ChMailInterval()", MailRefreshTime);
document.body.onmousemove = MousePos;
// Detect which Compose editor we are using ( HTML or Plain ) from the settings panel
if(!allow_HtmlEditor) {
ComposeMode = "Text";
} else if (document.getElementById("HtmlEditor").value == 1) {
ComposeMode = "HTML";
} else {
ComposeMode = "Text";
}
// Get which MailType we are ( POP3, IMAP, SQL, FILE )
MailType = document.getElementById("MailType").value;
// If we are first load from the login page, toggle showmail.php to query a list of IMAP servers
var FolderLoad = document.getElementById("FolderLoad").value;
if(FolderLoad == '1')
document.getElementById("FolderLoad").value = 0;
ObjMsgListBox = document.getElementById("MsgListBox");
liveSearchInit();
if (func == 'login') {
LoadLoginPage();
} else if(func == 'Compose') {
LoadMsgs();
ComposeMsg('', To, Cc, Bcc);
} else if(func == 'Search') {
LoadMsgs();
ToggleSearchRow();
} else if(To) {
LoadMsgs(To);
} else if(func == 'LoadCalendar') {
LoadMsgs();
Loaded = "Calendar";
} else {
LoadMsgs('', '', FolderLoad);
}
}
function DataIsLoading(ToDo, Message) {
if (!Message) {
Message = "Connecting";
document.getElementById('Connecting').innerText = Message;
document.body.style.cursor = 'wait';
}
if (ToDo == true) {
setOpacity(document.getElementById("Connecting"), "100");
setOpacity(document.getElementById("LoadingImage"), "100");
document.getElementById("LoadingText").style.display = "";
document.getElementById("LoadingIcon").style.display = "";
document.getElementById("BrandingLogo").style.display = "none";
} else {
LoadingFade();
}
}
function LoadMsgs(Folder, Start, FolderLoad) {
if(!FolderLoad)
FolderLoad = 0;
// Only capture these events on the showmail panel
document.onkeydown = MultiSelectDown;
if(navigator.userAgent.indexOf("Safari") != -1) {
document.onmousemove = MultiSelectDown;
}
document.onkeyup = MultiSelectUp;
document.onselectstart = NoSelectText;
// Check we are within the Ajax frame
if(TestAjaxFrameNull()) return;
// If we are using firefox, disable selection so users can toggle rows
document.body.setAttribute("style","-moz-user-select: none;");
if (MsgListData["CurrentFolder"] != Folder) LastUnreadMsgCount = 999999;
if (MsgListData["Views"]["MsgListViewer"] == true || MsgListData["CurrentFolder"] != Folder) {
DataIsLoading(true);
window.clearTimeout(MsgListData["Ctrl"]["Timeout"]);
if (!Folder) Folder = "Inbox";
if (!Start || Start < 0) Start = 0;
MsgListData["CurrentFolder"] = Folder;
MessagesReq = false;
if (MessagesReq && MessagesReq.readyState < 4) MessagesReq.abort();
MessagesReq = createXMLHttpRequest();
MessagesReq.onreadystatechange = MessagesReqChange;
if (Folder == "Search") {
var SearchFrom = document.getElementById("SearchFrom").value;
var SearchTo = document.getElementById("SearchTo").value;
var SearchSubject = document.getElementById("SearchSubject").value;
var SearchMessage = document.getElementById("SearchMessage").value;
var EmailAttach = '';
if(document.getElementById("SearchAttachments").checked == true)
EmailAttach = '1';
var EmailFlag = '';
if(document.getElementById("SearchFlagged").checked == true)
EmailFlag = '1';
var SearchLocation = document.getElementById("SearchLocation").options[document.getElementById("SearchLocation").selectedIndex].value;
// Get message dates, before
var SearchBeforeDay = document.getElementById("SearchBeforeDay").options[document.getElementById("SearchBeforeDay").selectedIndex].value || '';
var SearchBeforeMonth = document.getElementById("SearchBeforeMonth").options[document.getElementById("SearchBeforeMonth").selectedIndex].value || '';
var SearchBeforeYear = document.getElementById("SearchBeforeYear").options[document.getElementById("SearchBeforeYear").selectedIndex].value || '';
// Get message dates, after
var SearchAfterDay = document.getElementById("SearchAfterDay").options[document.getElementById("SearchAfterDay").selectedIndex].value || '';
var SearchAfterMonth = document.getElementById("SearchAfterMonth").options[document.getElementById("SearchAfterMonth").selectedIndex].value || '';
var SearchAfterYear = document.getElementById("SearchAfterYear").options[document.getElementById("SearchAfterYear").selectedIndex].value || '';
if (SearchFrom || SearchTo || SearchSubject || SearchMessage || EmailAttach || EmailFlag || SearchAfterYear || SearchAfterMonth || SearchAfterDay ) {
ToggleSearchRow(true);
MessagesReq.open("GET", "search.php?ajax=1&EmailFrom=" + encodeURIComponent(SearchFrom) + "&EmailTo=" + encodeURIComponent(SearchTo) + "&EmailSubject=" + encodeURIComponent(SearchSubject) + "&EmailMessage=" + encodeURIComponent(SearchMessage) + "&EmailBox=" + encodeURIComponent(SearchLocation) + "&EmailAttach=" + encodeURIComponent(EmailAttach) + "&EmailFlag=" + encodeURIComponent(EmailFlag) + "&BeforeDay=" + encodeURIComponent(SearchBeforeDay) + "&BeforeMonth=" + encodeURIComponent(SearchBeforeMonth) + '&BeforeYear=' + encodeURIComponent(SearchBeforeYear) + "&AfterDay=" + encodeURIComponent(SearchAfterDay) + "&AfterMonth=" + encodeURIComponent(SearchAfterMonth) + "&AfterYear=" + encodeURIComponent(SearchAfterYear) + "&start=" + encodeURIComponent(Start) + "&func=start", true);
MessagesReq.send(null);
} else {
MessagesReq.abort();
DataIsLoading(false);
alert("You must first enter in your search criteria.");
}
} else {
ClearListBoxData();
MessagesReq.open("GET", atmailRoot + "showmail.php?ajax=1&Folder=" + encodeURIComponent(Folder) + "&start=" + encodeURIComponent(Start) + "&LoadFolder=" + encodeURIComponent(FolderLoad), true );
MessagesReq.send(null);
if(Folder == 'Sent') {
document.getElementById('FromToField').innerHTML = Lang_To;
} else {
document.getElementById('FromToField').innerHTML = Lang_From;
}
}
}
if (MsgListData["Views"]["MsgListViewer"] == false) {
document.getElementById("MsgListViewer").style.display = "";
MsgListData["Views"]["MsgListViewer"] = true;
document.getElementById("MsgReader").style.display = "none";
MsgListData["Views"]["MsgReader"] = false;
document.getElementById("MsgComposer").style.display = "none";
MsgListData["Views"]["MsgComposer"] = false;
}
atmailRoot = '';
}
function MessagesReqChange() {
if (MessagesReq.readyState == 4 && MessagesReq.status == 200) {
if ( MessagesReq.responseXML && CheckXMLError(MessagesReq) ) {
// Refresh our moved message array, since indexes will change
MsgArrayMove = new Array();
// We are the search results, just push the last array
try
{
if(MessagesReq.responseXML.getElementsByTagName("Fol").length > 1) {
MsgListData["Folders"].length = 0;
for (var i = 0; i < MessagesReq.responseXML.getElementsByTagName("Fol").length; i ++) {
MsgListData["Folders"][i] = new Array();
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[i].getAttribute("Name"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[i].getAttribute("Icon"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[i].getAttribute("Count"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[i].getAttribute("State"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[i].getAttribute("Display"));
}
} else {
var i = MsgListData["Folders"].length;
if(MsgListData["Folders"][i-1][0] == 'Search')
i--;
MsgListData["Folders"][i] = new Array();
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[0].getAttribute("Name"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[0].getAttribute("Icon"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[0].getAttribute("Count"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[0].getAttribute("State"));
MsgListData["Folders"][i].push(MessagesReq.responseXML.getElementsByTagName("Fol")[0].getAttribute("Display"));
}
if (document.getElementById("MsgListViewer").style.display == "") LoadFolders();
ClearListBoxData();
}
catch (e)
{
// check for session timeout
try
{
if (MessagesReq.responseXML.getElementsByTagName('error')[0].firstChild.data == 2) {
alert('Your Session Has Timed Out');
document.location = 'index.php';
return;
}
} catch (e) {}
alert('Message loading failed - Please check the remote mail-server is responding correctly, remote mail-server online, no network timeouts, authentication error or mailbox lock');
}
for (var i = 0; i < MessagesReq.responseXML.getElementsByTagName("Msg").length; i ++) {
MsgListData["Data"][i] = new Array();
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("ID"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Folder")[i].firstChild.data);
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Subject")[i].firstChild.data);
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("From")[i].firstChild.data);
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("Attach"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("Epoch"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("Date"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("Priority"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("Size"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("MsgIcon"));
if (IsMsgLoaded(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("ID")) != "false") {
MsgListData["Data"][i].push(true);
} else {
MsgListData["Data"][i].push(false);
}
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("SizeRaw"));
MsgListData["Data"][i].push(MessagesReq.responseXML.getElementsByTagName("Msg")[i].getAttribute("EmailCache"));
}
ObjMsgPageListRow = document.getElementById("MsgPageListRow");
var MsgNavTotal = MessagesReq.responseXML.getElementsByTagName("MsgNav")[0].getAttribute("Total") * 1;
var MsgNavView = MessagesReq.responseXML.getElementsByTagName("MsgNav")[0].getAttribute("View") * 1;
var MsgNavStart = MessagesReq.responseXML.getElementsByTagName("MsgNav")[0].getAttribute("Start") * 1;
// Make a master array with our folders, to calculate msg-id sequence when emails are moved
for(var i = 1; i <= MsgNavTotal; i++) MsgArrayMove.push(i);
var ViewingTo = MsgNavStart + MsgNavView;
if (ViewingTo > MsgNavTotal) ViewingTo = MsgNavTotal;
document.getElementById("TotalMsgsStatus").innerHTML = Lang_Viewing + " " + ( MsgNavStart || '1') + " " + Lang_To.toLowerCase() + " " + ViewingTo + " " + Lang_Of + " " + MsgNavTotal + " " + Lang_Messages;
document.getElementById("MsgPageListPrevious").style.display = "none";
document.getElementById("MsgPageListPrevious").title = Lang_PrevMsg;
document.getElementById("MsgPageListNext").style.display = "none";
document.getElementById("MsgPageListNext").title = Lang_NextMsg;
if (MsgNavStart > 0) {
document.getElementById("MsgPageListPrevious").style.display = "";
}
if (MsgNavStart + MsgNavView < MsgNavTotal) {
document.getElementById("MsgPageListNext").style.display = "";
}
if (MsgNavTotal > MsgNavView) {
ObjMsgPageListRow.style.display = "";
ObjMsgPageListSelect = document.getElementById("MsgPageList");
ObjMsgPageListSelect.length = 0;
var HowManyPages = Math.ceil(MsgNavTotal / MsgNavView);
var LoopFrom = (MsgNavStart / MsgNavView) - 1;
var LoopTo = LoopFrom + 7;
if (LoopTo > HowManyPages) {
LoopFrom = HowManyPages - 8;
LoopTo = HowManyPages;
}
if (LoopFrom < 0) LoopFrom = 0;
if (LoopFrom > 0) {
ObjMsgPageListSelectOption.className = "ObjMsgPageListSelectOption";
ObjMsgPageListSelectOption = document.createElement("option");
ObjMsgPageListSelectOption.value = 0;
ObjMsgPageListSelectOption.appendChild(document.createTextNode(Lang_First + " " + Lang_Page + " 1"));
ObjMsgPageListSelect.appendChild(ObjMsgPageListSelectOption);
ObjMsgPageListSelectOption = document.createElement("option");
ObjMsgPageListSelectOption.value = 0;
ObjMsgPageListSelectOption.appendChild(document.createTextNode("-------------"));
ObjMsgPageListSelect.appendChild(ObjMsgPageListSelectOption);
}
for (var i = LoopFrom; i < LoopTo; i++) {
ObjMsgPageListSelectOption = document.createElement("option");
ObjMsgPageListSelectOption.value = i * MsgNavView;
if ((MsgNavView * i) == MsgNavStart) {
ObjMsgPageListSelectOption.selected = 1;
} else {
ObjMsgPageListSelectOption.className = "ObjMsgPageListSelectOption";
}
ObjMsgPageListSelectOption.appendChild(document.createTextNode(Lang_Page + " " + (i + 1)));
ObjMsgPageListSelect.appendChild(ObjMsgPageListSelectOption);
}
if (HowManyPages > 8 && LoopTo < HowManyPages) {
ObjMsgPageListSelectOption = document.createElement("option");
ObjMsgPageListSelectOption.value = (HowManyPages - 1) * MsgNavView;
ObjMsgPageListSelectOption.appendChild(document.createTextNode("-------------"));
ObjMsgPageListSelectOption.className = "ObjMsgPageListSelectOption";
ObjMsgPageListSelect.appendChild(ObjMsgPageListSelectOption);
ObjMsgPageListSelectOption = document.createElement("option");
ObjMsgPageListSelectOption.value = (HowManyPages - 1) * MsgNavView;
ObjMsgPageListSelectOption.appendChild(document.createTextNode(Lang_Last + " " + Lang_Page + " " + HowManyPages));
ObjMsgPageListSelectOption.className = "ObjMsgPageListSelectOption";
ObjMsgPageListSelect.appendChild(ObjMsgPageListSelectOption);
}
ObjMsgPageListRow.style.display = "";
} else {
ObjMsgPageListRow.style.display = "none";
}
DataIsLoading(false);
SortMsgsBy();
}
}
if(Loaded == 'Calendar') {
setTimeout("LoadCalendar()", 5000);
Loaded = '';
}
}
function BlockSender() {
DataIsLoading(true);
BlockSenderReq = false;
if (BlockSenderReq && BlockSenderReq.readyState < 4) BlockSenderReq.abort();
BlockSenderReq = createXMLHttpRequest();
BlockSenderReq.onreadystatechange = BlockSenderReqChange;
var AddRecipients = "";
for (var i in MsgListData["Ctrl"]["Selected"]) {
AddRecipients += escape(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][3]) + ",";
}
AddRecipients = AddRecipients.substring(0, AddRecipients.length - 1);
var LocalAccount = document.getElementById('LocalAccount').value;
if(LocalAccount) {
BlockSenderReq.open("GET", "util.php?func=spamsettings&Filter=1&Header=blacklist_from&Type=1&Add=Add&Refresh=1&Value=" + AddRecipients, true);
BlockSenderReq.send(null);
} else {
BlockSenderReq.open("GET", "util.php?func=info&spamadd=1&SpamEmail=" + AddRecipients, true);
BlockSenderReq.send(null);
}
}
function BlockSenderReqChange() {
if (BlockSenderReq.readyState == 4 && BlockSenderReq.status == 200) {
if (BlockSenderReq.responseText) {
DataIsLoading(false);
alert(Lang_BlackListAdded);
}
}
}
function AddAbook() {
DataIsLoading(true);
AddAbookReq = false;
if (AddAbookReq && AddAbookReq.readyState < 4) AddAbookReq.abort();
AddAbookReq = createXMLHttpRequest();
AddAbookReq.onreadystatechange = AddAbookReqChange;
var AddRecipients = "";
for (var i in MsgListData["Ctrl"]["Selected"]) {
AddRecipients += escape(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][3]) + ",";
}
AddRecipients = AddRecipients.substring(0, AddRecipients.length - 1);
AddAbookReq.open("GET", "abook.php?func=quicksearch&add=1&AddRecipients=" + AddRecipients, true);
AddAbookReq.send(null);
}
function AddAbookReqChange() {
if (AddAbookReq.readyState == 4 && AddAbookReq.status == 200) {
if (AddAbookReq.responseXML) {
DataIsLoading(false);
alert(Lang_AbookAdded);
}
}
}
function PrintEmail() {
ShowMsg = IsMsgLoaded(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]);
ObjReadMsgInfoTable = document.getElementById("ReadMsgInfoTableHeading");
ObjReadMsgInfoTableCopy = ObjReadMsgInfoTable.cloneNode(true);
ObjMsgData = document.createElement("div");
ObjMsgData.appendChild(ObjReadMsgInfoTableCopy);
win = open("html/blankiframe.html", "_blank");
win.document.open();
win.document.write("<HTML><BODY onload='setTimeout(\"print();\", 1000)'><table width='100%' cellpadding='2' cellspacing='2'><tr><td><input type=button name=Close value=Close onclick='window.close()' style='' id='closebutton'></td><td align='right'>" + document.getElementById('BrandingLogo').innerHTML + "</td></tr></table>" + ObjMsgData.innerHTML + "<link rel='stylesheet' href='html/ajax-int.css' type='text/css'><style> BODY { font-family:Arial, Helvetica, sans-serif;font-size:9pt;color:#000000; padding: 5px;} </style><br>" + MsgReaderData[ShowMsg][8] + "</BODY></HTML>");
win.document.close();
}
function ViewHeaders() {
ObjMRTableTbodyHeadersRow = document.getElementById("ReadMsgInfoTableTbodyHeadersRow");
if (ObjMRTableTbodyHeadersRow) {
ObjMRTableTbodyHeadersRow.parentNode.removeChild(ObjMRTableTbodyHeadersRow);
} else {
ShowMsg = IsMsgLoaded(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]);
var MsgHeader = MsgReaderData[ShowMsg][15].split("<br>");
for (var i in MsgHeader) {
MsgHeader[i] = MsgHeader[i].replace(/\s+/gi, " ");
}
ObjMRTableTbody = document.getElementById("ReadMsgInfoTableTbody");
ObjMRTableTbodyFirstRow = document.getElementById("ReadMsgInfoTableTbodyFirstRow");
ObjMRTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTr.id = "ReadMsgInfoTableTbodyHeadersRow";
ObjMRTableTbodyTrTd = document.createElement("td");
if (MsgReaderData[ShowMsg][17] != "") ObjMRTableTbodyTrTd.colSpan = "2";
if (NewHeaderStyle == true) ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd";
ObjMRTableTbodyTrTdTable = document.createElement("table");
ObjMRTableTbodyTrTdTable.width = "100%";
ObjMRTableTbodyTrTdTable.height = "100%";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTable.cellSpacing = "5";
ObjMRTableTbodyTrTdTable.cellPadding = "0";
} else {
ObjMRTableTbodyTrTdTable.cellSpacing = "0";
ObjMRTableTbodyTrTdTable.cellPadding = "5";
}
ObjMRTableTbodyTrTdTable.border = "0";
ObjMRTableTbodyTrTdTable.style.tableLayout = "fixed";
ObjMRTableTbodyTrTdTableTbody = document.createElement("tbody");
// Start New Msg Headers Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd7";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Headers + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd8";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "3";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv = document.createElement("div");
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.className = "ObjMRTableTbodyTrTdTableTbodyTrTdDiv9";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.innerHTML = MsgHeader.join("<br>");
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdDiv);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
ObjMRTableTbodyTrTdTable.appendChild(ObjMRTableTbodyTrTdTableTbody);
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTable);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
ObjMRTableTbody.insertBefore(ObjMRTableTbodyTr, ObjMRTableTbodyFirstRow);
}
}
function LoadMsgListBox(Increment) {
MsgListData["Ctrl"]["Increment"] = Increment;
if (MsgListData["Ctrl"]["Initialised"] == false) {
MsgListData["Ctrl"]["Initialised"] = true;
MsgListData["Ctrl"]["Loading"] = true;
if(navigator.userAgent.indexOf("Safari") == -1) ObjMsgListBox.style.width = "100%";
ObjMsgListBox.style.height = "100%";
FixShowMail();
ObjMsgListBox.style.overflowY = "hidden";
ObjMsgListBox.style.overflowX = "hidden";
ObjMLTable = document.createElement("table");
ObjMLTable.width = "100%";
ObjMLTable.cellSpacing = "0";
ObjMLTable.cellPadding = "1";
ObjMLTable.border = "0";
ObjMLTable.style.tableLayout = "fixed";
ObjMsgListBox.appendChild(ObjMLTable);
ObjMLTableTbody = document.createElement("tbody");
ObjMLTable.appendChild(ObjMLTableTbody);
}
// Calculate our row height, set the scrollbars on
var MsgHeight = (document.body.offsetHeight - 155 - document.body.scrollTop);
MsgRowHeight = 23 * Increment;
if (MsgListData["CurrentFolder"] == 'Search') {
MsgHeight -= 43;
}
if(MsgRowHeight > MsgHeight && ObjMsgListBox.style.overflowY != "scroll")
ObjMsgListBox.style.overflowY = "scroll";
ObjMLTableTbodyTr = document.createElement("tr");
// If the folder contains messages, not a "folder has no messages" warning
if(MsgListData["Data"][Increment][9] != 'object_close') {
ObjMLTableTbodyTr.onclick = new Function(onClickFunc);
ObjMLTableTbodyTr.ondblclick = new Function(onDblClickFunc);
ObjMLTableTbodyTr.onmouseover = new Function(onMouseOverFunc);
ObjMLTableTbodyTr.onmouseout = new Function(onMouseOutFunc);
ObjMLTableTbodyTr.onmousedown = new Function(onMouseDownFunc);
ObjMLTableTbodyTr.onmouseup = new Function(onMouseUpFunc);
ObjMLTableTbodyTr.onmousemove = new Function(onMouseMoveFunc);
// Need to call oncontextmenu directly, otherwise e blank
ObjMLTableTbodyTr.oncontextmenu = LoadContextMenu;
ObjMLTableTbodyTr.className = "ObjMLTableTbodyTr";
}
ObjMLTableTbody.appendChild(ObjMLTableTbodyTr);
// Loaded Status
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.title = Lang_CacheStatus;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv3";
ObjMLTableTbodyTrTdImg = document.createElement("img");
ObjMLTableTbodyTrTdImg.id = "ListBoxMsgLoadedIcon" + ObjMLTableTbodyTr.rowIndex;
// Need to save the reference of the name above, otherwise we can't access the icon if msg sequence changes
ObjMLTableTbodyTr.id = ObjMLTableTbodyTr.rowIndex;
if (MsgListData["Data"][Increment][10] == true) {
if (window.ActiveXObject) {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjMLTableTbodyTrTdImg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_msg_loaded.png', sizingMethod='image')";
} else {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/icon_msg_loaded.png";
}
} else {
if (window.ActiveXObject) {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjMLTableTbodyTrTdImg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_msg_notloaded.png', sizingMethod='image')";
} else {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/icon_msg_notloaded.png";
}
}
ObjMLTableTbodyTrTdImg.width = "15";
ObjMLTableTbodyTrTdImg.height = "14";
ObjMLTableTbodyTrTdImg.border = "0";
ObjMLTableTbodyTrTdDiv.appendChild(ObjMLTableTbodyTrTdImg);
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// Attachment
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.title = Lang_DoubleClick;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv4";
ObjMLTableTbodyTrTdImg = document.createElement("img");
if (MsgListData["Data"][Increment][4] > 0) {
if (window.ActiveXObject) {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/attachment.gif";
} else {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/icon_attachment.png";
}
} else {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
}
ObjMLTableTbodyTrTdImg.width = "12";
ObjMLTableTbodyTrTdImg.height = "14";
ObjMLTableTbodyTrTdImg.border = "0";
ObjMLTableTbodyTrTdDiv.appendChild(ObjMLTableTbodyTrTdImg);
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// MsgIcon
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.title = Lang_DoubleClick;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv5";
ObjMLTableTbodyTrTdImg = document.createElement("img");
ObjMLTableTbodyTrTdImg.id = "ListBoxMsgIcon" + ObjMLTableTbodyTr.rowIndex;
if (window.ActiveXObject) {
ObjMLTableTbodyTrTdImg.src = "imgs/xp/" + MsgListData["Data"][Increment][9] + ".gif";
} else {
if (MsgListData["Data"][Increment][9] != 'move') {
ObjMLTableTbodyTrTdImg.src = "imgs/simple/icon_" + MsgListData["Data"][Increment][9] + ".png";
} else {
ObjMLTableTbodyTrTdImg.src = "imgs/xp/" + MsgListData["Data"][Increment][9] + ".gif";
}
}
if( MsgListData["Data"][Increment][9] == 'object_close' ) {
ObjMLTableTbodyTrTdImg.width = "13";
ObjMLTableTbodyTrTdImg.height = "13";
ObjMLTableTbodyTrTdImg.border = "0";
} else {
ObjMLTableTbodyTrTdImg.width = "16";
ObjMLTableTbodyTrTdImg.height = "14";
ObjMLTableTbodyTrTdImg.border = "0";
}
ObjMLTableTbodyTrTdDiv.appendChild(ObjMLTableTbodyTrTdImg);
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// From
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd2";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.id = "ListBoxMsgFrom" + ObjMLTableTbodyTr.rowIndex;
ObjMLTableTbodyTrTdDiv.title = Lang_DoubleClick;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv2";
if (MsgListData["Data"][Increment][9] == "unread") ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDivBold";
ObjMLTableTbodyTrTdDiv.appendChild(document.createTextNode(MsgListData["Data"][Increment][3]));
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// Subject
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd3";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.id = "ListBoxMsgSubject" + ObjMLTableTbodyTr.rowIndex;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv2";
ObjMLTableTbodyTrTdDiv.title = Lang_DragDrop;
ObjMLTableTbodyTrTdDiv.style.padding = "2px 4px 2px 15px";
if (MsgListData["Data"][Increment][9] == "unread") ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDivBold";
ObjMLTableTbodyTrTdDiv.appendChild(document.createTextNode(MsgListData["Data"][Increment][2]));
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// Date
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd2";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.id = "ListBoxMsgDate" + ObjMLTableTbodyTr.rowIndex;
ObjMLTableTbodyTrTdDiv.title = Lang_DragDrop;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv2";
ObjMLTableTbodyTrTdDiv.style.padding = "2px 4px 2px 30px";
if (MsgListData["Data"][Increment][9] == "unread") ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDivBold";
ObjMLTableTbodyTrTdDiv.appendChild(document.createTextNode(MsgListData["Data"][Increment][6]));
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
// Size
ObjMLTableTbodyTrTd = document.createElement("td");
ObjMLTableTbodyTrTd.className = "ObjMLTableTbodyTrTd4";
ObjMLTableTbodyTrTdDiv = document.createElement("div");
ObjMLTableTbodyTrTdDiv.title = Lang_DragDrop;
ObjMLTableTbodyTrTdDiv.id = "ListBoxMsgSize" + ObjMLTableTbodyTr.rowIndex;
ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDiv";
if (MsgListData["Data"][Increment][9] == "unread") ObjMLTableTbodyTrTdDiv.className = "ObjMLTableTbodyTrTdDivBoldSize";
ObjMLTableTbodyTrTdDiv.appendChild(document.createTextNode(MsgListData["Data"][Increment][8]));
ObjMLTableTbodyTrTd.appendChild(ObjMLTableTbodyTrTdDiv);
ObjMLTableTbodyTr.appendChild(ObjMLTableTbodyTrTd);
if ((Increment + 1) < MsgListData["Data"].length) {
MsgListData["Ctrl"]["Timeout"] = window.setTimeout("LoadMsgListBox(" + (Increment + 1) + ", false)", 0);
} else {
MsgListData["Ctrl"]["Loading"] = false;
}
}
function ListBoxKeyCtrl(WhichKey) {
if (WhichKey == 13) {
MsgRowCtrl(null, "DblClick");
WhichKey = 505;
} else if (WhichKey == 46) {
MoveMsgs('Trash');
WhichKey = 505;
} else if (WhichKey == 38 || WhichKey == 40) {
var Increment = MsgListData["Ctrl"]["Selected"][MsgListData["Ctrl"]["Selected"].length - 1];
var DataLength = MsgListData["Data"].length;
if ((WhichKey == 38 && Increment > 0) || (WhichKey == 40 && Increment < (DataLength - 1) && Increment < MsgListData["Ctrl"]["Increment"])) {
var MaskHeightScroll = ObjMsgListBox.scrollHeight;
var MaskHeightBox = ObjMsgListBox.clientHeight;
var MaskTop = ObjMsgListBox.scrollTop;
if(WhichKey == 38) {
Increment --;
} else if(WhichKey == 40) {
Increment ++;
}
var RowHeight = 18;
var MoveAmount = Increment * RowHeight;
if (MoveAmount > MaskTop && (MoveAmount + RowHeight) < (MaskTop + MaskHeightBox)) {
} else {
ObjMsgListBox.scrollTop = MoveAmount;
}
MsgRowCtrl(Increment, "Click");
}
WhichKey = 505;
}
return WhichKey;
}
function MultiArraySort(a, b) {
if (MsgListData["Ctrl"]["SortCol"] == 5 || MsgListData["Ctrl"]["SortCol"] == 11) {
aa = parseFloat(a[MsgListData["Ctrl"]["SortCol"]]);
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[MsgListData["Ctrl"]["SortCol"]]);
if (isNaN(bb)) bb = 0;
return aa-bb;
} else {
if (a[MsgListData["Ctrl"]["SortCol"]] < b[MsgListData["Ctrl"]["SortCol"]]) return -1;
if (a[MsgListData["Ctrl"]["SortCol"]] > b[MsgListData["Ctrl"]["SortCol"]]) return 1;
return 0;
}
}
function SortMsgsBy(Column) {
if (Column || MsgListData["Ctrl"]["LastSorted"]) {
if (!Column) {
Column = MsgListData["Ctrl"]["LastSorted"];
MsgListData["Ctrl"]["LastSorted"] = null;
if (MsgListData["Ctrl"]["SortColReverse"] == true) {
MsgListData["Ctrl"]["SortCol"] = Column;
}
}
if (MsgListData["Ctrl"]["Loading"] == false && MsgListData["Data"].length > 1) {
ObjMsgListBox.innerHTML = "";
MsgListData["Ctrl"]["Initialised"] = false;
if(MsgListData["Ctrl"]["LastSorted"]) {
document.getElementById("MsgListBoxSort" + MsgListData["Ctrl"]["LastSorted"] + "Img").src = "imgs/simple/shim.gif";
}
MsgListData["Ctrl"]["LastSorted"] = Column;
if (MsgListData["Ctrl"]["SortCol"] == Column) {
document.getElementById("MsgListBoxSort" + Column + "Img").src = "imgs/simple/listbox_header_sort_down.gif";
MsgListData["Ctrl"]["SortDescending"][Column] = true;
MsgListData["Ctrl"]["SortCol"] = Column;
MsgListData["Ctrl"]["SortColReverse"] = true;
MsgListData["Data"].sort(MultiArraySort);
MsgListData["Data"].reverse();
MsgListData["Ctrl"]["SortCol"] = null;
LoadMsgListBox(0);
} else {
document.getElementById("MsgListBoxSort" + Column + "Img").src = "imgs/simple/listbox_header_sort_up.gif";
MsgListData["Ctrl"]["SortDescending"][Column] = false;
MsgListData["Ctrl"]["SortCol"] = Column;
MsgListData["Ctrl"]["SortColReverse"] = false;
MsgListData["Data"].sort(MultiArraySort);
LoadMsgListBox(0);
}
}
} else {
LoadMsgListBox(0);
}
}
function NumericSort(a, b) {
return a - b;
}
function ClearListBoxData() {
MsgListData["Data"].length = 0;
ObjMsgListBox.innerHTML = "";
MsgListData["Ctrl"]["Initialised"] = false;
MsgListData["Ctrl"]["Timeout"] = null;
MsgListData["Ctrl"]["Increment"] = null;
MsgListData["Ctrl"]["Selected"].length = 0;
MsgListData["Ctrl"]["SortCol"] = null;
MsgListData["Ctrl"]["SortDescending"].length = 0;
MsgListData["Ctrl"]["CtrlKey"] = false;
MsgListData["Ctrl"]["ShiftKey"] = false;
MsgListData["Ctrl"]["DnD"].length = 0;
// If we are using the single login window, open-src copy, remove it from successful login
try {
document.getElementById('ObjAdvancedWindow').style.display = "none";
} catch(e) {
}
}
function ToggleSearchRow(Override) {
if(TestAjaxFrame('Search'))
return;
if(MsgListData["Views"]["MsgListViewer"] == false) {
LoadFolders(); LoadMsgs();
}
// Make the select box with search results
var index = '1';
document.getElementById('SearchLocation').options.length = 0;
var opt = document.createElement('OPTION');
opt.value = '';
opt.text = Lang_AllFolders;
opt.className = "opt";
document.getElementById('SearchLocation').options[document.getElementById('SearchLocation').options.length] = opt;
for (i in MsgListData["Folders"]) {
// Disable searching Inbox for POP3
if(MailType == 'pop3' && MsgListData["Folders"][i][0] == 'Inbox') {
} else {
var opt = document.createElement('OPTION');
opt.value = MsgListData["Folders"][i][0];
opt.text = MsgListData["Folders"][i][4];
document.getElementById('SearchLocation').options[document.getElementById('SearchLocation').options.length] = opt;
if(opt.value == 'Inbox')
document.getElementById('SearchLocation').options[index].selected = true;
index++;
}
}
ObjSearchRow = document.getElementById("MsgSearchRow");
if (Override == true) {
ObjSearchRow.style.display = "none";
} else {
if (ObjSearchRow.style.display == "none") {
ObjSearchRow.style.display = "";
} else {
ObjSearchRow.style.display = "none";
}
}
}
function ToggleSearchRowMore(Override) {
ObjSearchRow = document.getElementById("MsgSearchRowMore");
var MsgSearchButton = document.getElementById("MsgSearchButton");
if (Override == true) {
ObjSearchRow.style.display = "none";
} else {
if (ObjSearchRow.style.display == "none") {
ObjSearchRow.style.display = "";
MsgSearchButton.text = "Less";
} else {
ObjSearchRow.style.display = "none";
MsgSearchButton.text = "More";
}
}
}
function FolderHighlight(Folder, Action, MainFolders) {
if (MainFolders == true) {
if (MsgListData["Folders"][Folder][0] != MsgListData["CurrentFolder"]) {
if (Action == "Over") {
document.getElementById("FolderIcon" + MsgListData["Folders"][Folder][0]).src = "imgs/simple/sidebar_" + MsgListData["Folders"][Folder][1] + "_on.gif";
document.getElementById("FolderIcon" + MsgListData["Folders"][Folder][0]).className="FolderHighlightIconOn";
document.getElementById("Folder" + MsgListData["Folders"][Folder][0]).className="FolderHighlightOn";
} else if (Action == "Out") {
document.getElementById("FolderIcon" + MsgListData["Folders"][Folder][0]).src = "imgs/simple/sidebar_" + MsgListData["Folders"][Folder][1] + "_off.gif";
document.getElementById("FolderIcon" + MsgListData["Folders"][Folder][0]).className="FolderHighlightIconOff";
document.getElementById("Folder" + MsgListData["Folders"][Folder][0]).className="FolderHighlightOff";
}
}
} else {
if (Action == "Over") {
document.getElementById("Folder" + Folder).className="FolderHighlightOver";
} else if (Action == "Out") {
document.getElementById("Folder" + Folder).className="FolderHighlightOut";
}
}
}
function ToggleVideo() {
if (document.getElementById("ComposeMsgVideoContainer").style.display == "none") {
document.getElementById("ComposeMsgTextContainer").colSpan = "2";
document.getElementById("ComposeMsgVideoContainer").style.display = "";
if (document.getElementById("ComposeMsgVideoIFrame").src.substring(document.getElementById("ComposeMsgVideoIFrame").src.length - 4, document.getElementById("ComposeMsgVideoIFrame").src.length) == "html") {
VideoStreamUID = GetVideoID(true);
document.getElementById("ComposeMsgVideoIFrame").src = "http://" + document.getElementById('VideoMailServer').value + "/videomail/record.pl?UniqueID=" + VideoStreamUID;
}
document.getElementById("VideoMovedOptionsSource1").style.display = "none";
document.getElementById("VideoMovedOptionsSource2").style.display = "none";
document.getElementById("VideoMovedOptionsSource3").style.display = "none";
document.getElementById("VideoMovedOptionsSource4").style.display = "none";
document.getElementById("VideoMovedOptionsSource5").style.display = "none";
document.getElementById("VideoMovedOptionsSource6").style.display = "none";
document.getElementById("VideoMovedOptionsWidth1").style.width = "100%";
document.getElementById("VideoMovedOptionsWidth2").style.width = "100%";
document.getElementById("VideoMovedOptionsWidth3").style.width = "100%";
document.getElementById("VideoMovedOptionsDestination").style.display = "";
document.getElementById("VideoMovedHelpDestination").style.display = "";
if (document.getElementById("VideoMovedOptionsColSpan")) document.getElementById("VideoMovedOptionsColSpan").colSpan = "1";
document.getElementById("VideoMovedOptionsColSpan1").colSpan = "1";
document.getElementById("VideoMovedOptionsColSpan2").colSpan = "1";
document.getElementById("VideoMovedOptionsColSpan3").colSpan = "1";
} else {
document.getElementById("ComposeMsgTextContainer").colSpan = "1";
document.getElementById("ComposeMsgVideoContainer").style.display = "none";
document.getElementById("VideoMovedOptionsSource1").style.display = "";
document.getElementById("VideoMovedOptionsSource2").style.display = "";
document.getElementById("VideoMovedOptionsSource3").style.display = "";
document.getElementById("VideoMovedOptionsSource4").style.display = "";
document.getElementById("VideoMovedOptionsSource5").style.display = "";
document.getElementById("VideoMovedOptionsSource6").style.display = "";
document.getElementById("VideoMovedOptionsWidth1").style.width = "70%";
document.getElementById("VideoMovedOptionsWidth2").style.width = "70%";
document.getElementById("VideoMovedOptionsWidth3").style.width = "70%";
document.getElementById("VideoMovedOptionsDestination").style.display = "none";
document.getElementById("VideoMovedHelpDestination").style.display = "none";
if (document.getElementById("VideoMovedOptionsColSpan")) document.getElementById("VideoMovedOptionsColSpan").colSpan = "3";
document.getElementById("VideoMovedOptionsColSpan1").colSpan = "3";
document.getElementById("VideoMovedOptionsColSpan2").colSpan = "3";
document.getElementById("VideoMovedOptionsColSpan3").colSpan = "3";
}
}
function LoadFolders(FolderSet) {
if (!FolderSet) FolderSet = "";
//FolderSet = Url.decode(FolderSet);
if (TestAjaxFrame("Inbox", "To=" + Url.encode(FolderSet))) return;
ObjFolderBox = document.getElementById("FolderBox");
ObjFolderBox.innerHTML = '';
ObjFLTable = document.createElement("table");
ObjFLTable.width = "150";
ObjFLTable.cellSpacing = "0";
ObjFLTable.cellPadding = "0";
ObjFLTable.border = "0";
ObjFLTable.style.tableLayout = "fixed";
ObjFolderBox.appendChild(ObjFLTable);
ObjFLTableTbody = document.createElement("tbody");
ObjFLTable.appendChild(ObjFLTableTbody);
if (FolderSet) {
FieldInFocus = true;
var Folders = new Array();
Folders["ReadMsg"] = new Array();
Folders["ReadMsg"]["Selected"] = null;
Folders["ReadMsg"].push(new Array(Lang_Back, "back", "LoadFolders(); LoadMsgs('" + MsgListData["CurrentFolder"] + "'); FixShowMail();"));
if (MsgListData["CurrentFolder"] == "Drafts") {
Folders["ReadMsg"].push(new Array(Lang_Open, "open", "ReadMsg(null, null, 'Open');"));
} else {
Folders["ReadMsg"].push(new Array(Lang_Reply, "reply", "ReadMsg(null, null, 'Reply');"));
Folders["ReadMsg"].push(new Array(Lang_ReplyAll, "replyall", "ReadMsg(null, null, 'ReplyAll');"));
Folders["ReadMsg"].push(new Array(Lang_Forward, "forward", "ReadMsg(null, null, 'Forward');"));
}
Folders["ReadMsg"].push(new Array(Lang_Delete, "delete", "LoadFolders(); LoadMsgs('" + MsgListData["CurrentFolder"] + "'); MoveMsgs('Trash');"));
if (MsgListData["CurrentFolder"] != "Drafts") Folders["ReadMsg"].push(new Array(Lang_Abook, "address", "AddAbook();"));
Folders["ReadMsg"].push(new Array(Lang_Print, "print", "PrintEmail();"));
if (MsgListData["CurrentFolder"] != "Drafts") Folders["ReadMsg"].push(new Array(Lang_BlockSender, "block", "BlockSender()"));
Folders["ReadMsg"].push(new Array(Lang_ViewHeaders, "search", "ViewHeaders();"));
Folders["ReadMsg"].push(new Array(Lang_Next, "next", "NextMsg();"));
Folders["ReadMsg"].push(new Array(Lang_Prev, "previous", "PreviousMsg();"));
Folders["ComposeMsg"] = new Array();
// Generate our unique ID for the attachments to upload
unique = Math.round(Math.random()*99999);
Folders["ComposeMsg"].push(new Array(Lang_Send, "send", "SendMsg('" + unique + "');"));
Folders["ComposeMsg"].push(new Array(Lang_Back, "back", "LoadFolders(); LoadMsgs('" + MsgListData["CurrentFolder"] + "');"));
Folders["ComposeMsg"].push(new Array(Lang_AddRecpt, "addrec", "AddRecpientsDOM();"));
Folders["ComposeMsg"].push(new Array(Lang_AddBCC, "newgroup", "ToggleBccRow();"));
if(document.getElementById('spellcheck').value == 1){
Folders["ComposeMsg"].push(new Array(Lang_SpellCheck, "spell", "SpellCheck(true);"));
}
Folders["ComposeMsg"].push(new Array(Lang_Attachments, "attach", "Attachment(" + unique + ");"));
// If Videomail is enabled via the Webadmin
if(document.getElementById('VideoMail').value == 1) {
Folders["ComposeMsg"].push(new Array(Lang_VideoMail, "video", "ToggleVideo();"));
}
Folders["ComposeMsg"].push(new Array(Lang_SaveMsg, "save_settings", "SendMsg('" + unique + "', '1');"));
Folders["SpellChecker"] = new Array();
Folders["SpellChecker"].push(new Array(Lang_Resume, "spell", "SpellCheck();"));
for (var i in Folders[FolderSet]) {
if (i != "Selected") {
ObjFLTableTbodyTr = document.createElement("tr");
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTd";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjFLTableTbodyTrTdImg.width = "38";
ObjFLTableTbodyTrTdImg.height = "10";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.width = "125";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjFLTableTbodyTrTdImg.width = "125";
ObjFLTableTbodyTrTdImg.height = "10";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbody.appendChild(ObjFLTableTbodyTr);
ObjFLTableTbodyTr = document.createElement("tr");
ObjFLTableTbodyTr.id = "FolderRow" + Folders[FolderSet][i][1];
if (Folders[FolderSet][i][1] == Folders[FolderSet]["Selected"]) {
ObjFLTableTbodyTr.className = "ObjFLTableTbodyTr";
} else {
ObjFLTableTbodyTr.className = "ObjFLTableTbodyTr2";
}
if (Folders[FolderSet][i][2]) {
var onClickFunc = Folders[FolderSet][i][2];
ObjFLTableTbodyTr.onclick = new Function(onClickFunc);
}
if (Folders[FolderSet][i][1] != Folders[FolderSet]["Selected"]) {
var onMouseOverFunc = "FolderHighlight('" + Folders[FolderSet][i][1] + "', 'Over');";
ObjFLTableTbodyTr.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "FolderHighlight('" + Folders[FolderSet][i][1] + "', 'Out');";
ObjFLTableTbodyTr.onmouseout = new Function(onMouseOutFunc);
}
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTd";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.id = "FolderIcon" + Folders[FolderSet][i][1];
if (Folders[FolderSet][i][1] == Folders[FolderSet]["Selected"]) {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_" + Folders[FolderSet][i][1] + "_on.gif";
} else if (Folders[FolderSet][i][1] == "back") {
var FoundMatch = false;
for (var x in MsgListData["Folders"]) {
if (MsgListData["Folders"][x][0] == MsgListData["CurrentFolder"]) {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_" + MsgListData["Folders"][x][1] + "_off.gif";
Folders[FolderSet][i][0] = MsgListData["Folders"][x][0];
FoundMatch = true;
break;
}
}
if (FoundMatch == false) {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_inbox_off.gif";
Folders[FolderSet][i][0] = "Inbox";
}
} else {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_" + Folders[FolderSet][i][1] + ".gif";
}
ObjFLTableTbodyTrTdImg.width = "38";
ObjFLTableTbodyTrTdImg.height = "31";
ObjFLTableTbodyTrTdImg.border = "0";
if (Folders[FolderSet][i][1] == Folders[FolderSet]["Selected"]) {
ObjFLTableTbodyTrTdImg.className = "ObjFLTableTbodyTrTdImg";
} else {
ObjFLTableTbodyTrTdImg.className = "ObjFLTableTbodyTrTdImg2";
}
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.id = "Folder" + Folders[FolderSet][i][1];
ObjFLTableTbodyTrTd.width = "125";
if (Folders[FolderSet][i][1] == Folders[FolderSet]["Selected"]) {
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTdBorder";
} else {
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTdBorder2";
}
if (Folders[FolderSet][i][1] == "back") {
ObjFLTableTbodyTrTd.appendChild(document.createTextNode(Lang_BackTo + " " + Folders[FolderSet][i][0]));
} else {
ObjFLTableTbodyTrTd.appendChild(document.createTextNode(Folders[FolderSet][i][0]));
}
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbody.appendChild(ObjFLTableTbodyTr);
}
}
} else {
FieldInFocus = false;
for (var i in MsgListData["Folders"]) {
ObjFLTableTbodyTr = document.createElement("tr");
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTd";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjFLTableTbodyTrTdImg.width = "38";
ObjFLTableTbodyTrTdImg.height = "10";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.width = "125";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjFLTableTbodyTrTdImg.width = "125";
ObjFLTableTbodyTrTdImg.height = "10";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbody.appendChild(ObjFLTableTbodyTr);
if (MsgListData["Folders"][i][0] == "erase") {
ObjFLTableTbodyTr.id = "EraseMsgFolderIconTr";
ObjFLTableTbodyTr.style.display = "none";
}
ObjFLTableTbodyTr = document.createElement("tr");
ObjFLTableTbodyTr.className = "ObjFLTableTbodyTr2";
if (MsgListData["Folders"][i][0] == "erase") {
ObjFLTableTbodyTr.id = "EraseMsgFolderIcon";
ObjFLTableTbodyTr.style.display = "none";
}
var onClickFunc = "LoadMsgs('" + MsgListData["Folders"][i][0] + "');";
ObjFLTableTbodyTr.onclick = new Function(onClickFunc);
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
var onMouseOverFunc = "FolderHighlight(" + i + ", 'Over', true); if (MsgListData['Ctrl']['DnD']['Active'] == true) this.style.cursor = 'not-allowed';";
ObjFLTableTbodyTr.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "FolderHighlight(" + i + ", 'Out', true); this.style.cursor = 'pointer';";
ObjFLTableTbodyTr.onmouseout = new Function(onMouseOutFunc);
} else {
var onMouseOverFunc = "FolderHighlight(" + i + ", 'Over', true); if (MsgListData['Ctrl']['DnD']['Active'] == true) MsgListData['Ctrl']['DnD']['MoveTo'] = '" + MsgListData["Folders"][i][0] + "';";
ObjFLTableTbodyTr.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "FolderHighlight(" + i + ", 'Out', true); if (MsgListData['Ctrl']['DnD']['Active'] == true) MsgListData['Ctrl']['DnD']['MoveTo'] = '';";
ObjFLTableTbodyTr.onmouseout = new Function(onMouseOutFunc);
}
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTd";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.id = "FolderIcon" + MsgListData["Folders"][i][0];
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_" + MsgListData["Folders"][i][1] + "_on.gif";
} else {
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_" + MsgListData["Folders"][i][1] + "_off.gif";
}
ObjFLTableTbodyTrTdImg.width = "38";
ObjFLTableTbodyTrTdImg.height = "31";
ObjFLTableTbodyTrTdImg.border = "0";
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
ObjFLTableTbodyTrTdImg.className = "ObjFLTableTbodyTrTdImg";
} else {
ObjFLTableTbodyTrTdImg.className = "ObjFLTableTbodyTrTdImg2";
}
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.id = "Folder" + MsgListData["Folders"][i][0];
ObjFLTableTbodyTrTd.width = "125";
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTdBorder";
} else {
ObjFLTableTbodyTrTd.className = "ObjFLTableTbodyTrTdBorder2";
}
if (MsgListData["Folders"][i][2] > 0) {
ObjFLTableTbodyTrTd.appendChild(document.createTextNode(MsgListData["Folders"][i][4] + " (" + MsgListData["Folders"][i][2] + ")"));
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"] && MsgListData["Folders"][i][2] > LastUnreadMsgCount && PlaySound == true) {
LastUnreadMsgCount = MsgListData["Folders"][i][2];
try {
if (window.ActiveXObject) document.NewMsgSound.Run();
} catch (e) {
}
PlaySound = false;
} else if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
LastUnreadMsgCount = MsgListData["Folders"][i][2];
}
} else {
ObjFLTableTbodyTrTd.appendChild(document.createTextNode(MsgListData["Folders"][i][4]));
}
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbody.appendChild(ObjFLTableTbodyTr);
}
}
ObjFLTableTbodyTr = document.createElement("tr");
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.width = "38";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/sidebar_bottom_tile_small.gif";
ObjFLTableTbodyTrTdImg.width = "38";
ObjFLTableTbodyTrTdImg.height = "45";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbodyTrTd = document.createElement("td");
ObjFLTableTbodyTrTd.width = "125";
ObjFLTableTbodyTrTdImg = document.createElement("img");
ObjFLTableTbodyTrTdImg.src = "imgs/simple/shim.gif";
ObjFLTableTbodyTrTdImg.width = "125";
ObjFLTableTbodyTrTdImg.height = "1";
ObjFLTableTbodyTrTdImg.border = "0";
ObjFLTableTbodyTrTd.appendChild(ObjFLTableTbodyTrTdImg);
ObjFLTableTbodyTr.appendChild(ObjFLTableTbodyTrTd);
ObjFLTableTbody.appendChild(ObjFLTableTbodyTr);
}
function MsgRowCtrl(RowIndex, Source, Unique) {
if (Source == "Click") {
if (MsgListData["Ctrl"]["CtrlKey"] == true) {
if (IsSelected(RowIndex) == "false") {
MsgListData["Ctrl"]["Selected"].push(RowIndex);
RowHighlight(RowIndex, true);
} else {
MsgListData["Ctrl"]["Selected"].splice(IsSelected(RowIndex), 1);
RowHighlight(RowIndex, false);
}
} else if (MsgListData["Ctrl"]["ShiftKey"] == true) {
if (MsgListData["Ctrl"]["Selected"].length > 1) {
for (var i in MsgListData["Ctrl"]["Selected"]) {
if (i > 0 && MsgListData["Ctrl"]["Selected"][i] < ObjMLTable.rows.length) {
RowHighlight(MsgListData["Ctrl"]["Selected"][i], false);
}
}
MsgListData["Ctrl"]["Selected"].length = 1;
}
if (MsgListData["Ctrl"]["Selected"].length > 0) {
if (MsgListData["Ctrl"]["Selected"][0] < RowIndex) {
for (var i = MsgListData["Ctrl"]["Selected"][0]; i <= RowIndex; i++) {
if (IsSelected(i) == "false") {
MsgListData["Ctrl"]["Selected"].push(i);
RowHighlight(i, true);
}
}
} else {
for (var i = MsgListData["Ctrl"]["Selected"][0]; i >= RowIndex; i--) {
if (IsSelected(i) == "false") {
MsgListData["Ctrl"]["Selected"].push(i);
RowHighlight(i, true);
}
}
}
} else {
MsgListData["Ctrl"]["Selected"][0] = RowIndex;
RowHighlight(RowIndex, true);
}
} else {
if (MsgListData["Ctrl"]["Selected"].length > 1) {
for (var i in MsgListData["Ctrl"]["Selected"]) {
if (MsgListData["Ctrl"]["Selected"][i] < ObjMLTable.rows.length) {
RowHighlight(MsgListData["Ctrl"]["Selected"][i], false);
}
}
MsgListData["Ctrl"]["Selected"].length = 0;
} else {
if (MsgListData["Ctrl"]["Selected"][0] != null && MsgListData["Ctrl"]["Selected"][0] < ObjMLTable.rows.length) {
RowHighlight(MsgListData["Ctrl"]["Selected"][0], false);
}
}
MsgListData["Ctrl"]["Selected"][0] = RowIndex;
RowHighlight(RowIndex, true);
}
} else if (Source == "DblClick") {
GlobalUnique = Unique;
ReadMsg();
} else if (Source == "Over") {
if (MsgListData["Ctrl"]["DnD"]["Active"] != true) {
if (IsSelected(RowIndex) == "false") {
RowHighlight(RowIndex, true, true);
}
}
} else if (Source == "Out") {
if (MsgListData["Ctrl"]["DnD"]["Active"] != true) {
if (IsSelected(RowIndex) == "false") {
RowHighlight(RowIndex, false);
}
}
} else if (Source == "ContextMenu") {
// Can't call like LoadContextMenu() otherwise e will be null
LoadContextMenu;
} else if (Source == "Down") {
if (MsgListData["Ctrl"]["CtrlKey"] == false && MsgListData["Ctrl"]["ShiftKey"] == false) {
if (IsSelected(RowIndex) == "false") {
MsgRowCtrl(RowIndex, "Click");
}
MsgListData["Ctrl"]["DnD"]["OnDrag"] = true;
}
} else if (Source == "Up") {
MsgListData["Ctrl"]["DnD"]["OnDrag"] = false;
} else if (Source == "Move") {
if (MsgListData["Ctrl"]["DnD"]["OnDrag"] == true && MsgListData["Ctrl"]["DnD"]["Active"] != true && IsSelected(RowIndex) != "false") {
document.onmousemove = StartDnD;
}
}
}
function IsSelected(Criteria) {
var CriteriaFound = "false";
for (var i in MsgListData["Ctrl"]["Selected"]) {
if (MsgListData["Ctrl"]["Selected"][i] == Criteria) {
CriteriaFound = i;
}
}
return CriteriaFound;
}
function RowHighlight(RowIndex, On, Hover) {
if (On == true) {
if (Hover == true) {
ObjMLTable.rows[RowIndex].style.color = "";
ObjMLTable.rows[RowIndex].style.backgroundColor = "#deebf6";
} else {
ObjMLTable.rows[RowIndex].style.color = "white";
ObjMLTable.rows[RowIndex].style.backgroundColor = "#8EBEE5";
}
} else {
ObjMLTable.rows[RowIndex].style.color = "";
ObjMLTable.rows[RowIndex].style.backgroundColor = "";
}
}
function LoadContextMenu(e) {
e = fixE(e);
if (document.getElementById("PopUpBox")) document.body.removeChild(ObjPopUpBox);
ObjPopUpBox = document.createElement("div");
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "ReadMsg(); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_Open));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "ReadMsg(null, null, 'Reply'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_Reply));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "ReadMsg(null, null, 'ReplyAll'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_ReplyAll));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "ReadMsg(null, null, 'Forward'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_Forward));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
// Mark as read
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "MarkMessage('o'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_MarkAsRead));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
// Mark as unread
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "MarkMessage('x'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_MarkAsUnread));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
// Move to Trash
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "MoveMsgs('Trash'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem2";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_Delete));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
// Add to address book
ObjPopUpBoxItem = document.createElement("div");
var onClickFunc = "AddAbook(); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "95px";
ObjPopUpBoxItem.className = "ObjPopUpBoxItem3";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_AddSender));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
ObjPopUpBox.id = "PopUpBox";
ObjPopUpBox.className = "ObjPopUpBox";
ObjPopUpBox.style.top = e.clientY;
ObjPopUpBox.style.left = e.clientX;
document.body.appendChild(ObjPopUpBox);
var onClickFunc = "try { document.body.removeChild(ObjPopUpBox);} catch(e) { }";
document.body.onclick = new Function(onClickFunc);
return false;
}
function DeleteMsgs() {
var CurrentFolderIndex = null;
for (var i in MsgListData["Folders"]) {
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
CurrentFolderIndex = i;
break;
}
}
MsgListData["Ctrl"]["Selected"].sort(NumericSort);
for (var i = 0; i < MsgListData["Ctrl"]["Selected"].length; i ++) {
if (MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][9] == "unread") {
MsgListData["Folders"][CurrentFolderIndex][2] --;
}
ObjMLTable.deleteRow(MsgListData["Ctrl"]["Selected"][i]);
MsgListData["Data"].splice(MsgListData["Ctrl"]["Selected"][i], 1);
MsgListData["Ctrl"]["Selected"].splice(i, 1);
i --;
for (var x in MsgListData["Ctrl"]["Selected"]) {
MsgListData["Ctrl"]["Selected"][x] --;
}
}
var unread = MsgListData["Folders"][CurrentFolderIndex][2];
if(unread > 0)
document.getElementById("Folder" + MsgListData["CurrentFolder"]).innerHTML = MsgListData["CurrentFolder"] + " (" + unread + ")";
else
document.getElementById("Folder" + MsgListData["CurrentFolder"]).innerHTML = MsgListData["CurrentFolder"];
// Create the empty folder message
var EmptyFolder = Lang_HasNoMsgs;
EmptyFolder = EmptyFolder.replace(/\$var\['FolderName'\]/,MsgListData["CurrentFolder"]);
if (MsgListData["Data"].length == 0) document.getElementById("MsgListBox").innerHTML = "<div style=\"width: 100%; text-align: center; padding: 5px;\" class=\"ObjMLTableTbodyTrTdDiv2\">" + EmptyFolder + "</div>";
}
function StartDnD(e) {
e = fixE(e);
if (MsgListData["Ctrl"]["DnD"]["OnDrag"] == true && MsgListData["Ctrl"]["DnD"]["Active"] != true) {
document.getElementById("EraseMsgFolderIcon").style.display = "";
document.getElementById("EraseMsgFolderIconTr").style.display = "";
MsgListData["Ctrl"]["DnD"]["Active"] = true;
MsgListData["Ctrl"]["DnD"]["MoveTo"] = "";
ObjDnDDiv = document.createElement("div");
document.body.appendChild(ObjDnDDiv);
ObjDnDDiv.className = "ObjDnDDiv";
ObjDnDDiv.style.left = (e.clientX + 25) + "px";
ObjDnDDiv.style.top = e.clientY + "px";
ObjDnDDiv.style.filter = 'alpha(opacity=90)';
ObjDnDDiv.style.opacity = '0.90';
ObjDnDDivContent = document.createElement("div");
ObjDnDDivContent.className = "ObjDnDDivContent";
ObjDnDDivContent.appendChild(document.createTextNode(MsgListData["Ctrl"]["Selected"].length + " " + Lang_ItemsToMove));
ObjDnDDiv.appendChild(ObjDnDDivContent);
for (var i in MsgListData["Ctrl"]["Selected"]) {
if (i < 6) {
ObjDnDDivContent = document.createElement("div");
ObjDnDDivContent.className = "ObjDnDDivContent";
if (i < 5) {
ObjDnDDivContent.appendChild(document.createTextNode(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][2]));
} else {
ObjDnDDivContent.appendChild(document.createTextNode("..."));
}
ObjDnDDiv.appendChild(ObjDnDDivContent);
}
ObjMLTable.rows[MsgListData["Ctrl"]["Selected"][i]].style.backgroundColor = "#a3c5e3";
}
document.onmousemove = MoveDnD;
document.onmouseup = FinishDnD;
}
}
var lastpos = 0;
function MoveDnD(e) {
e = fixE(e);
if (MsgListData["Ctrl"]["DnD"]["OnDrag"] == true && MsgListData["Ctrl"]["DnD"]["Active"] == true) {
// scroll page if need be so user can drop to folders that may be out of view
if ((document.body.clientHeight + document.body.scrollTop) < document.body.scrollHeight) {
if (MousePosXY[1] > (document.body.clientHeight + document.body.scrollTop - 50) && (lastpos < MousePosXY[1])) {
document.body.scrollTop += 5;
ObjDnDDiv.style.top = MousePosXY[1] + "px";
} else if (MousePosXY[1] < (document.body.scrollTop + 50) && (lastpos > MousePosXY[1])) {
document.body.scrollTop -= 5;
ObjDnDDiv.style.top = MousePosXY[1] + "px";
} else {
ObjDnDDiv.style.top = MousePosXY[1] + "px"
ObjDnDDiv.style.left = (e.clientX + 25) + "px";
}
ObjDnDDiv.style.left = (e.clientX + 25) + "px";
} else {
ObjDnDDiv.style.top = MousePosXY[1] + "px"
ObjDnDDiv.style.left = (e.clientX + 25) + "px";
}
lastpos = MousePosXY[1];
}
}
function FinishDnD() {
document.getElementById("EraseMsgFolderIcon").style.display = "none";
document.getElementById("EraseMsgFolderIconTr").style.display = "none";
document.onmousemove = "";
document.onmouseup = "";
document.body.removeChild(ObjDnDDiv);
MsgListData["Ctrl"]["DnD"]["OnDrag"] = false;
MsgListData["Ctrl"]["DnD"]["Active"] = false;
if (MailType == "pop3" && MsgListData["Ctrl"]["DnD"]["MoveTo"] == "Inbox") {
alert("Sorry, you cannot move emails back to the\nInbox because the POP3 protocol does not support it.");
} else {
for (var i in MsgListData["Ctrl"]["Selected"]) {
ObjMLTable.rows[MsgListData["Ctrl"]["Selected"][i]].style.backgroundColor = "#8EBEE5";
}
if (MsgListData["Ctrl"]["DnD"]["MoveTo"] != MsgListData["CurrentFolder"]) {
MoveMsgs(MsgListData["Ctrl"]["DnD"]["MoveTo"]);
}
}
}
function fixE(e) {
if (typeof e == "undefined") e = window.event;
if (typeof e.layerX == "undefined") e.layerX = e.offsetX;
if (typeof e.layerY == "undefined") e.layerY = e.offsetY;
return e;
}
function getE(e) {
if (typeof e == "undefined") e = window.event;
if (typeof e.layerX == "undefined") e.layerX = e.offsetX;
if (typeof e.layerY == "undefined") e.layerY = e.offsetY;
return e;
}
function MoveMsgs(MoveTo) {
if (MoveTo) {
DataIsLoading(true);
MoveMessagesReq = false;
if (MoveMessagesReq && MoveMessagesReq.readyState < 4) MoveMessagesReq.abort();
MoveMessagesReq = createXMLHttpRequest();
MoveMessagesReq.onreadystatechange = MoveMessagesReqChange;
var POSTString = "ajax=1&NewFolder=" + encodeURIComponent(MoveTo);
var IDstring = '';
var InboxCheck;
for (var i in MsgListData["Ctrl"]["Selected"]) {
var id = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][0];
var folder = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][1];
var uidl = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][12];
if(folder == 'Inbox' && ( MailType == 'pop3' || MailType == 'imap') )
InboxCheck++;
// Make the string [msg-id]::[folder] - Has to be like this when using the search since we
// don't know which folder we are located under, especially for the search menu
IDstring += "&id[]=" + CalcMoveMsgs(id, folder) + "::" + folder + "::" + uidl;
SpliceMoveMsgs(id, folder);
}
if(MsgListData["CurrentFolder"] == 'Search' && ( MailType == 'pop3' || MailType == 'imap') ) {
POSTString += "&Folder=Inbox";
} else {
POSTString += "&Folder=" + Url.encode(MsgListData["CurrentFolder"]);
}
if(MoveTo == 'erase' && !confirm(Lang_AlertPerm)) return false;
POSTString += IDstring;
MoveMessagesReq.open("POST", "showmail.php", true);
MoveMessagesReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
MoveMessagesReq.send(POSTString);
}
}
function MoveMessagesReqChange() {
if (MoveMessagesReq.readyState == 4 && MoveMessagesReq.status == 200) {
if ( MoveMessagesReq.responseXML && CheckXMLError(MoveMessagesReq) ) {
// We are the search results, just push the last array
try {
var status = MoveMessagesReq.responseXML.getElementsByTagName("status")[0].firstChild.data;
// Check the message was moved successfully
if(status == 1) {
DeleteMsgs();
} else if(status == 0) {
alert(MoveMessagesReq.responseXML.getElementsByTagName("message")[0].firstChild.data)
}
} catch(e) { alert('Error deleting message - Please reload mailbox'); }
}
DataIsLoading(false);
}
}
// Read an email message
function ReadMsg(ShowMsg, FoldersLoaded, Reply, DisplayImages) {
// Test if we are inside the Ajax panel, if so silently return
if (TestAjaxFrameNull()) return;
// If we are using firefox, enable selection so users can select text on readmail pane
document.body.setAttribute("style","-moz-user-select: text;");
// If no messages are selected, don't do anything
if (MsgListData["Ctrl"]["Selected"][0] == undefined) return;
DataIsLoading(true);
if (Reply) {
ReadMsgReply = Reply;
} else {
ReadMsgReply = null;
}
if (ShowMsg && Reply != true) {
ObjMsgReader = document.getElementById("MsgReader");
ObjMsgReader.innerHTML = "";
ObjMRTable = document.createElement("table");
ObjMRTable.id = "ReadMsgInfoTable";
ObjMRTable.className = "ObjMRTable";
ObjMsgReader.appendChild(ObjMRTable);
ObjMRTableTbody = document.createElement("tbody");
ObjMRTableTbody.id = "ReadMsgInfoTableTbody";
ObjMRTable.appendChild(ObjMRTableTbody);
ObjMRTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTr.id = "ReadMsgInfoTableTbodyFirstRow";
ObjMRTableTbody.appendChild(ObjMRTableTbodyTr);
ObjMRTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTd.width = "100%";
ObjMRTableTbodyTrTd.vAlign = "middle";
if (NewHeaderStyle == true) ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd";
ObjMRTableTbodyTrTdTable = document.createElement("table");
ObjMRTableTbodyTrTdTable.id = "ReadMsgInfoTableHeading";
ObjMRTableTbodyTrTdTable.width = "100%";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTable.cellSpacing = "5";
ObjMRTableTbodyTrTdTable.cellPadding = "0";
} else {
ObjMRTableTbodyTrTdTable.cellSpacing = "0";
ObjMRTableTbodyTrTdTable.cellPadding = "5";
}
ObjMRTableTbodyTrTdTable.border = "0";
ObjMRTableTbodyTrTdTableTbody = document.createElement("tbody");
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_From + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd2";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgReaderData[ShowMsg][3]));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Sent + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgReaderData[ShowMsg][4]));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row - To / Sent
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_To + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd4";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv = document.createElement("div");
// Cleanup the data, take out whitespace between recipients
var ToData = MsgReaderData[ShowMsg][5];
ToData = ToData.replace(/,\s+/g, ', ');
ToData = ToData.replace(/;\s+/g, '; ');
// Make the title on mouseover all the recipients, easier to read
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.title = ToData;
// If over a 100 characters, chop down to fit on two rows for usability
if(ToData.length > 100) {
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.style.height = "30px";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.style.overflow = "hidden";
}
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.appendChild(document.createTextNode(ToData));
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdDiv);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Priority + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgReaderData[ShowMsg][12]));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Check CC header exists
if(MsgReaderData[ShowMsg][6]) {
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Cc + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd2";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "4";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv = document.createElement("div");
// Cleanup the data, take out whitespace between recipients
var CcData = MsgReaderData[ShowMsg][6];
CcData = CcData.replace(/,\s+/g, ', ');
CcData = CcData.replace(/;\s+/g, '; ');
// Make the title on mouseover all the recipients, easier to read
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.title = CcData;
// If over a 100 characters, chop down to fit on two rows for usability
if(CcData.length > 100) {
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.style.height = "30px";
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.style.overflow = "hidden";
}
ObjMRTableTbodyTrTdTableTbodyTrTdDiv.appendChild(document.createTextNode(MsgReaderData[ShowMsg][6]));
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdDiv);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
}
// Start New Msg Header Row - Subject
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Subject + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd2";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgReaderData[ShowMsg][2]));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Type + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgReaderData[ShowMsg][7]));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
ObjMRTableTbodyTrTdTable.appendChild(ObjMRTableTbodyTrTdTableTbody);
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTable);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
// Check if Attachments exists
if(MsgReaderData[ShowMsg][10]) {
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Attachments + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd2";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "4";
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = MsgReaderData[ShowMsg][10];
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
}
if (MsgReaderData[ShowMsg][17] != "") {
ObjMRTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTd.width = "240";
if (NewHeaderStyle == false) ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd3";
ObjMRTableTbodyTrTdIFrame = document.createElement("iframe");
ObjMRTableTbodyTrTdIFrame.width = "240";
ObjMRTableTbodyTrTdIFrame.height = "210";
ObjMRTableTbodyTrTdIFrame.src = MsgReaderData[ShowMsg][17];
ObjMRTableTbodyTrTdIFrame.scrolling = "no";
ObjMRTableTbodyTrTdIFrame.frameBorder = "0";
ObjMRTableTbodyTrTdIFrame.marginHeight = "0";
ObjMRTableTbodyTrTdIFrame.marginWidth = "0";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdIFrame.className = "ObjMRTableTbodyTrTdIFrame";
} else {
ObjMRTableTbodyTrTdIFrame.className = "ObjMRTableTbodyTrTdIFrame2";
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdIFrame);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
}
ObjMRTableTbodyTr = document.createElement("tr");
ObjMRTableTbody.appendChild(ObjMRTableTbodyTr);
ObjMRTableTbodyTrTd = document.createElement("td");
if (MsgReaderData[ShowMsg][17] != "") ObjMRTableTbodyTrTd.colSpan = "2";
ObjMRTableTbodyTrTd.height = "100%";
if (NewHeaderStyle == false) ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd4";
ObjMRTableTbodyTrTdDiv = document.createElement("div");
ObjMRTableTbodyTrTdDiv.id = "MsgReaderData";
ObjMRTableTbodyTrTdDiv.className = "ObjMRTableTbodyTrTdDiv";
if (!MsgReaderData[ShowMsg][8]) MsgReaderData[ShowMsg][8] = MsgReaderData[ShowMsg][9];
ObjMRTableTbodyTrTdDivIFrame = document.createElement("iframe");
ObjMRTableTbodyTrTdDivIFrame.width = "100%";
ObjMRTableTbodyTrTdDivIFrame.height = "100%";
ObjMRTableTbodyTrTdDivIFrame.src = "html/blankiframe.html";
ObjMRTableTbodyTrTdDivIFrame.scrolling = "auto";
ObjMRTableTbodyTrTdDivIFrame.frameBorder = "0";
ObjMRTableTbodyTrTdDivIFrame.marginHeight = "0";
ObjMRTableTbodyTrTdDivIFrame.marginWidth = "0";
ObjMRTableTbodyTrTdDivIFrame.className = "ObjMRTableTbodyTrTdDivIFrame";
var FrameNo = 0;
if (MsgReaderData[ShowMsg][17] != "") FrameNo = 1;
// Toggle if we want to view images in email-messages
if (!DisplayImages && MsgReaderData[ShowMsg][11] == 1) {
var displayImagesLink = '<a href="javascript:parent.ReadMsg(null, null, null, 1)">' + Lang_Display + '</a><br><br>';
} else {
var displayImagesLink = '';
}
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdDivIFrame.id = "msgwindow";
ObjMRTableTbodyTrTdDivIFrame.name = "msgwindow";
ObjMRTableTbodyTrTdDiv.appendChild(ObjMRTableTbodyTrTdDivIFrame);
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdDiv);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
window.frames[FrameNo].document.open();
window.frames[FrameNo].document.write("<style> BODY, .sw { font-family:Arial, Helvetica, sans-serif;font-size:9pt;color:#000000; } </style><div class='container'><div class='fade_bottom'></div>" + displayImagesLink + MsgReaderData[ShowMsg][8] + MsgReaderData[ShowMsg][19] + MsgReaderData[ShowMsg][10] + "<br><br><br><br></div>");
window.frames[FrameNo].document.close();
} else if (navigator.userAgent.indexOf("Safari/41") != -1) {
ObjMRTableTbodyTrTdDiv.innerHTML = displayImagesLink + MsgReaderData[ShowMsg][8];
ObjMRTableTbodyTrTdDiv.innerHTML += MsgReaderData[ShowMsg][10];
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdDiv);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
} else {
// Workaround for Firefox - Needs a unique Window name each time, why? Need to null the windows.frames to reduce mem, or auto in FF?
ObjMRTableTbodyTrTdDivIFrame.id = "msgwindow" + msgwinnum;
ObjMRTableTbodyTrTdDivIFrame.name = "msgwindow" + msgwinnum;
ObjMRTableTbodyTrTdDiv.appendChild(ObjMRTableTbodyTrTdDivIFrame);
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdDiv);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
window.frames["msgwindow" + msgwinnum].document.open();
window.frames["msgwindow" + msgwinnum].document.write("<style> BODY, .sw { font-family:Arial, Helvetica, sans-serif;font-size:9pt;color:#000000; } </style><div class='container'><div class='fade_bottom'></div>" + displayImagesLink + MsgReaderData[ShowMsg][8] + MsgReaderData[ShowMsg][19] + MsgReaderData[ShowMsg][10] + "<br><br><br><br></div>" + "</div>");
window.frames["msgwindow" + msgwinnum].document.close();
msgwinnum++;
}
document.getElementById("MsgListViewer").style.display = "none";
MsgListData["Views"]["MsgListViewer"] = false;
document.getElementById("MsgReader").style.display = "";
MsgListData["Views"]["MsgReader"] = true;
if (ReadMsgFoldersLoaded != true) LoadFolders("ReadMsg");
FixShowMail();
// The readmail page has finished loading
DataIsLoading(false);
// Only run if there is something selected
} else {
ReadMsgFoldersLoaded = FoldersLoaded;
if (!DisplayImages && IsMsgLoaded(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]) != "false") {
if (Reply) {
ComposeMsg(Reply);
} else {
ReadMsg(IsMsgLoaded(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]));
}
} else {
// If we are reloading the message to get images then we should
// delete the message from cache so that the new message complete with
// images will be used from cache in future requests
if (DisplayImages) {
for (var i in MsgReaderData) {
if (MsgReaderData[i][0] == MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]) {
MsgReaderData[i].shift();
}
}
}
MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][10] = true;
if (window.ActiveXObject) {
try{
document.getElementById("ListBoxMsgLoadedIcon" + GlobalUnique).src = "imgs/simple/shim.gif";
document.getElementById("ListBoxMsgLoadedIcon" + GlobalUnique).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_msg_loaded.png', sizingMethod='image')";
} catch (e) {
}
} else {
try{
document.getElementById("ListBoxMsgLoadedIcon" + GlobalUnique).src = "imgs/simple/icon_msg_loaded.png";
} catch (e) {
}
}
DataIsLoading(true);
ReadMsgReq = false;
if (ReadMsgReq && ReadMsgReq.readyState < 4) ReadMsgReq.abort();
ReadMsgReq = createXMLHttpRequest();
var id = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0];
var folder = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][1];
var uidl = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][12];
ReadMsgReq.onreadystatechange = ReadMsgReqChange;
ReadMsgReq.open("GET", "reademail.php?ajax=1&folder=" + encodeURIComponent(folder) + "&id=" + encodeURIComponent( CalcMoveMsgs(id, folder) ) + "&cache=" + encodeURIComponent(uidl) + "&DisplayImages=" + DisplayImages, true);
ReadMsgReq.send(null);
}
}
}
function IsMsgLoaded(MsgID) {
var ReturnResult = "false";
for (var i in MsgReaderData) {
if (MsgID == MsgReaderData[i][0]) {
ReturnResult = i;
break;
}
}
return ReturnResult;
}
function ReadMsgReqChange() {
if (ReadMsgReq.readyState == 4 && ReadMsgReq.status == 200) {
if (ReadMsgReq.responseXML && CheckXMLError(ReadMsgReq) ) {
var CurrentFolderIndex = null;
for (var i in MsgListData["Folders"]) {
if (MsgListData["Folders"][i][0] == MsgListData["CurrentFolder"]) {
CurrentFolderIndex = i;
break;
}
}
if (MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][9] == "unread") {
MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][9] = "read";
if (window.ActiveXObject) {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).src = "imgs/simple/shim.gif";
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_read.png', sizingMethod='image')";
} else {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).src = "imgs/simple/icon_read.png";
}
document.getElementById("ListBoxMsgFrom" + MsgListData["Ctrl"]["Selected"][0]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgSubject" + MsgListData["Ctrl"]["Selected"][0]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgDate" + MsgListData["Ctrl"]["Selected"][0]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgSize" + MsgListData["Ctrl"]["Selected"][0]).className = "ObjMLTableTbodyTrTdDiv";
MsgListData["Folders"][CurrentFolderIndex][2] --;
if(MsgListData["Folders"][CurrentFolderIndex][2] > 0)
document.getElementById("Folder" + MsgListData["CurrentFolder"]).innerHTML = MsgListData["CurrentFolder"] + " (" + MsgListData["Folders"][CurrentFolderIndex][2] + ")";
}
var DataFields = new Array("id","folder","EmailSubject","EmailFrom","EmailDate","EmailToList","EmailCcList","EmailType","EmailTxt","EmailHtml","Attachments","BlockedImages","EmailPriority","RawAttachments", "Charset", "RawHeaders", "UIDL", "VideoMail", "EmailReplyTo", "ImageAttachments", "HTMLtoTextReply");
if (MsgReaderData.length >= MsgCacheLimit) {
MsgReaderData.shift();
}
MsgReaderData.push(new Array());
for (var i in DataFields) {
var field;
field = getXMLfieldName(ReadMsgReq.responseXML, DataFields[i]);
MsgReaderData[MsgReaderData.length - 1].push(field);
}
DataIsLoading(false);
if (ReadMsgReply) {
ComposeMsg(ReadMsgReply);
} else {
ReadMsg(MsgReaderData.length - 1);
}
} else {
alert('Message could not be loaded from the server - Please try again or view message using another interface');
}
}
}
function NextMsg() {
var MsgIndex = MsgListData["Ctrl"]["Selected"][0];
if (MsgIndex < (MsgListData["Data"].length - 1)) {
MsgIndex ++;
} else {
MsgIndex = 0;
}
MsgRowCtrl(MsgIndex, "Click");
ReadMsg(null, true);
}
function PreviousMsg() {
var MsgIndex = MsgListData["Ctrl"]["Selected"][0];
if (MsgIndex > 0) {
MsgIndex --;
} else {
MsgIndex = MsgListData["Data"].length - 1;
}
MsgRowCtrl(MsgIndex, "Click");
ReadMsg(null, true);
}
function LoadCal(Language) {
if(TestAjaxFrame("LoadCalendar", Language)) return;
LoadCalendar(Language);
}
function ComposeMsg(Reply, To, Cc, Bcc) {
if (!To) To = "";
if (!Cc) Cc = "";
if (!Bcc) Bcc = "";
// Build our To, Cc, Bcc into an argument list
var args;
if (To) args += "&To=" + escape(To);
if (Cc) args += "&Cc=" + escape(Cc);
if (Bcc) args += '&Bcc=' + escape(Bcc);
if (TestAjaxFrame("Compose", args)) return;
DataIsLoading(true);
// Generate a new unique ID for the 'attachments' panel
if (!ReadMsgReply) ReadMsgReply = null;
// Reset the Videostream each time
VideoStreamUID = null;
// If we are using firefox, enable selection so users can type!
document.body.setAttribute("style","-moz-user-select: text;");
MsgListData["Views"]["MsgListViewer"] = false;
LoadFolders("ComposeMsg");
var ShowMsg = null;
if (Reply) ShowMsg = IsMsgLoaded(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0]);
document.getElementById("MsgListViewer").style.display = "none";
document.getElementById("MsgReader").style.display = "none";
ObjMsgComposerDiv = document.getElementById("MsgComposer");
ObjMsgComposerDiv.innerHTML = "";
ObjMsgComposerDiv.style.display = "";
ObjMRTable = document.createElement("table");
ObjMRTable.width = "100%";
ObjMRTable.height = "100%";
ObjMRTable.cellSpacing = "0";
ObjMRTable.cellPadding = "0";
ObjMRTable.border = "0";
ObjMRTable.style.tableLayout = "fixed";
if (NewHeaderStyle == true) ObjMRTable.className = "ObjMRTableBorder";
ObjMsgComposerDiv.appendChild(ObjMRTable);
ObjMRTableTbody = document.createElement("tbody");
ObjMRTable.appendChild(ObjMRTableTbody);
ObjMRTableTbodyTr = document.createElement("tr");
ObjMRTableTbody.appendChild(ObjMRTableTbodyTr);
ObjMRTableTbodyTrTd = document.createElement("td");
if (NewHeaderStyle == true) ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd";
ObjMRTableTbodyTrTdTable = document.createElement("table");
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTable.cellSpacing = "5";
ObjMRTableTbodyTrTdTable.cellPadding = "0";
} else {
ObjMRTableTbodyTrTdTable.cellSpacing = "0";
ObjMRTableTbodyTrTdTable.cellPadding = "5";
}
ObjMRTableTbodyTrTdTable.border = "0";
ObjMRTableTbodyTrTdTable.style.tableLayout = "fixed";
ObjMRTableTbodyTrTdTableTbody = document.createElement("tbody");
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_From + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsWidth1";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd2";
// Generate a select box with the Prioirty types
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("select");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgFrom";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInputBorder";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInputBorder2";
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource1";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Date + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource2";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
// Get our date
var curdate = new Date()
var DayOfWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var MonthName = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var minutes = curdate.getMinutes();
if (minutes < 10) minutes = '0' + minutes;
var MsgDate = DayOfWeek[curdate.getDay()] + " " + MonthName[curdate.getMonth()] + " " + curdate.getDate() + " " + curdate.getHours() + ":" + minutes;
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(MsgDate));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
// Add the To: field that is clickable for the addrecipients panel
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span onclick=\"AddRecpientsDOM()\" style=\"cursor: pointer;\" title=\"" + Lang_AddRecpt + "\">" + Lang_To + ":</span>";
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsWidth2";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd6";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("textarea");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgTo";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "emailto";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput2";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.autocomplete = "off";
if (document.getElementById("AutoComplete").value == "1") {
if (BrowserVer.Type == "MSIE") {
var OnKeyPress = "liveSearchStart(this);";
var OnKeyDown = "liveSearchKeyPress();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeypress = new Function(OnKeyPress);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeydown = new Function(OnKeyDown);
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keypress", function (e) {
liveSearchStart(this, e);
}, true);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keydown", function (e) {
liveSearchKeyPress(e);
}, true);
}
var OnFocus = "liveSearchHide();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onfocus = new Function(OnFocus);
}
var OnKeyUp = "if (this.value.length > 35) { this.style.height = '40px'; } else this.style.height='22px'; ";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeyup = new Function(OnKeyUp);
if (Reply) {
if (ReadMsgReply == "Reply") {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = MsgReaderData[ShowMsg][18];
} else if (ReadMsgReply == "ReplyAll") {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = MsgReaderData[ShowMsg][18] + ", " + MsgReaderData[ShowMsg][5];
} else if (ReadMsgReply == "Open") {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = MsgReaderData[ShowMsg][5];
}
} else if(To) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = To;
// Expand the field automatically if content large
if(ObjMRTableTbodyTrTdTableTbodyTrTdInput.value.length > 35)
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput6";
}
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.width = "100%";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid silver";
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource3";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Editor + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource4";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
// Turn off HTML editor if not allowed
if(!allow_HtmlEditor) {
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span id=\"ComposeModeText\" onclick=\"ToggleComposeMode(false);\">" + Lang_Text + "</span>";
} else if (ComposeMode == "HTML") {
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span id=\"ComposeModeText\" onclick=\"ToggleComposeMode(false);\" style=\"cursor: pointer;\">Text</span> / <span id=\"ComposeModeHTML\" onclick=\"ToggleComposeMode(true);\" style=\"cursor: pointer; font-weight: bold;\">HTML</span>";
} else if (ComposeMode == "Text") {
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span id=\"ComposeModeText\" onclick=\"ToggleComposeMode(false);\" style=\"cursor: pointer; font-weight: bold;\">" + Lang_Text + "</span> / <span id=\"ComposeModeHTML\" onclick=\"ToggleComposeMode(true);\" style=\"cursor: pointer;\">HTML</span>";
}
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
// Add the Cc: field that is clickable for the addrecipients panel
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span onclick=\"AddRecpientsDOM()\" style=\"cursor: pointer;\" title=\"" + Lang_AddRecpt + "\">" + Lang_Cc + ":</span>";
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsWidth3";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd6";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("textarea");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgCc";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "emailcc";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput3";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.autocomplete = "off";
if (document.getElementById("AutoComplete").value == "1") {
if (BrowserVer.Type == "MSIE") {
var OnKeyPress = "liveSearchStart(this);";
var OnKeyDown = "liveSearchKeyPress();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeypress = new Function(OnKeyPress);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeydown = new Function(OnKeyDown);
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keypress", function (e) {
liveSearchStart(this, e);
}, true);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keydown", function (e) {
liveSearchKeyPress(e);
}, true);
}
var OnFocus = "liveSearchHide();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onfocus = new Function(OnFocus);
}
var OnKeyUp = "if (this.value.length > 35) { this.style.height = '40px'; } else this.style.height='22px';";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeyup = new Function(OnKeyUp);
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid silver";
}
// Append CC if called from URL
if(Cc) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = Cc;
// Expand the field automatically if content large
if(ObjMRTableTbodyTrTdTableTbodyTrTdInput.value.length > 35)
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.height = '40px';
}
if (ReadMsgReply == "ReplyAll") {
if (ObjMRTableTbodyTrTdTableTbodyTrTdInput.value) ObjMRTableTbodyTrTdTableTbodyTrTdInput.value += ", ";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value += MsgReaderData[ShowMsg][6];
} else if (ReadMsgReply == "Open") {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value += MsgReaderData[ShowMsg][6];
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource5";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Priority + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsSource6";
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd3";
// Generate a select box with the Prioirty types
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("select");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeEmailPriority";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput4";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTr.id = "ComposeMsgBccRow";
ObjMRTableTbodyTrTdTableTbodyTr.name = "emailbcc";
ObjMRTableTbodyTrTdTableTbodyTr.style.display = "none";
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
// Add the To: field that is clickable for the addrecipients panel
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span onclick=\"AddRecpientsDOM()\" style=\"cursor: pointer;\" title=\"" + Lang_AddRecpt + "\">" + Lang_Bcc + ":</span>";
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsColSpan1";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "3";
ObjMRTableTbodyTrTdTableTbodyTrTd.style.width = "100%";
if (NewHeaderStyle == false) ObjMRTableTbodyTrTdTableTbodyTrTd.style.borderBottom = "1px solid #ebe9e4";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("textarea");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgBcc";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput3";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.autocomplete = "off";
if (document.getElementById("AutoComplete").value == "1") {
if (BrowserVer.Type == "MSIE") {
var OnKeyPress = "liveSearchStart(this);";
var OnKeyDown = "liveSearchKeyPress();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeypress = new Function(OnKeyPress);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeydown = new Function(OnKeyDown);
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keypress", function (e) {
liveSearchStart(this, e);
}, true);
ObjMRTableTbodyTrTdTableTbodyTrTdInput.addEventListener("keydown", function (e) {
liveSearchKeyPress(e);
}, true);
}
var OnFocus = "liveSearchHide();";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onfocus = new Function(OnFocus);
}
var OnKeyUp = "if (this.value.length > 35) { this.style.height = '40px'; } else this.style.height='22px';";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.onkeyup = new Function(OnKeyUp);
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid silver";
}
if (Bcc) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = Bcc;
ObjMRTableTbodyTrTdTableTbodyTr.style.display = '';
// Expand the field automatically if content large
if(ObjMRTableTbodyTrTdTableTbodyTrTdInput.value.length > 35)
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.height = '40px';
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTr.id = "ComposeMsgAttachmentsRow";
ObjMRTableTbodyTrTdTableTbodyTr.style.display = "none";
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span onclick=\"Attachment('" + unique + "');\" style=\"cursor: pointer;\">" + Lang_Attachments + ":</span>";
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsColSpan2";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "3";
ObjMRTableTbodyTrTdTableTbodyTrTd.style.width = "100%";
if (NewHeaderStyle == false) ObjMRTableTbodyTrTdTableTbodyTrTd.style.borderBottom = "1px solid #ebe9e4";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgAttachments";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput5"; // Same style as To/Cc/etc
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "text";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.disabled = "1";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.width = "100%";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid silver";
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Hidden field for email-encoding
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgCharset";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "hidden";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "Charset";
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
// Hidden field for the message UIDL ( so replied/forwarded markers work )
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgUIDL";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "hidden";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "UIDL";
try
{
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = MsgReaderData[ShowMsg][16];
}
catch (e)
{
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = '';
}
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
// Hidden field for the message reply type ( e.g the flag to update the UIDL, forwarded, read, etc )
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgType";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "hidden";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "Type";
// If null, set a blank field so the sent message is unread
if(!ReadMsgReply)
ReadMsgReply = '';
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = ReadMsgReply;
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
// Hidden field for DraftID ( the message-id )
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgDraftID";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "hidden";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.name = "DraftID";
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTr.id = "VideoMovedOptionsDestination";
ObjMRTableTbodyTrTdTableTbodyTr.style.display = "none";
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Priority + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd8";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("select");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeEmailPriority2";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.className = "ObjMRTableTbodyTrTdTableTbodyTrTdInput4";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
// Turn off HTML editor if not allowed
if(!allow_HtmlEditor) {
//ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML = "<span id=\"ComposeModeText\" onclick=\"ToggleComposeMode(false);\">" + Lang_Text + "</span>";
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML += " <b>" + Lang_Editor + "</b>: " + Lang_Text + " ";
} else if (ComposeMode == "HTML") {
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML += "<span id=\"ComposeModeText2\" onclick=\"ToggleComposeMode(false);\" style=\"cursor: pointer;\">Text</span> / <span id=\"ComposeModeHTML2\" onclick=\"ToggleComposeMode(true);\" style=\"cursor: pointer; font-weight: bold;\">HTML</span>";
} else if (ComposeMode == "Text") {
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML += "<span id=\"ComposeModeText2\" onclick=\"ToggleComposeMode(false);\" style=\"cursor: pointer; font-weight: bold;\">" + Lang_Text + "</span> / <span id=\"ComposeModeHTML2\" onclick=\"ToggleComposeMode(true);\" style=\"cursor: pointer;\">HTML</span>";
}
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Start New Msg Header Row
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd5";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_Subject + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.id = "VideoMovedOptionsColSpan3";
ObjMRTableTbodyTrTdTableTbodyTrTd.colSpan = "3";
ObjMRTableTbodyTrTdTableTbodyTrTd.style.width = "100%";
if (NewHeaderStyle == false) ObjMRTableTbodyTrTdTableTbodyTrTd.style.borderBottom = "1px solid #ebe9e4";
ObjMRTableTbodyTrTdTableTbodyTrTdInput = document.createElement("input");
ObjMRTableTbodyTrTdTableTbodyTrTdInput.id = "ComposeMsgSubject";
ObjMRTableTbodyTrTdTableTbodyTrTdInput.type = "text";
if (Reply) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.value = TestSubjectReply(ReadMsgReply, MsgReaderData[ShowMsg][2] );
}
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.width = "100%";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTableTbodyTrTdInput.style.border = "1px solid silver";
}
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTdInput);
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// Video Mail Help Guide
ObjMRTableTbodyTrTdTableTbodyTr = document.createElement("tr");
ObjMRTableTbodyTrTdTableTbodyTr.id = "VideoMovedHelpDestination";
ObjMRTableTbodyTrTdTableTbodyTr.style.display = "none";
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTdvidmail";
ObjMRTableTbodyTrTdTableTbodyTrTd.appendChild(document.createTextNode(Lang_VideoMail + ":"));
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTdTableTbodyTrTd.className = "ObjMRTableTbodyTrTdTableTbodyTrTd8";
ObjMRTableTbodyTrTdTableTbodyTrTd.innerHTML += "<a href='javascript:help(\"videomail.html\", \"english\")'>" + Lang_Help + "</a>";
ObjMRTableTbodyTrTdTableTbodyTr.appendChild(ObjMRTableTbodyTrTdTableTbodyTrTd);
ObjMRTableTbodyTrTdTableTbody.appendChild(ObjMRTableTbodyTrTdTableTbodyTr);
// The rest of the interface
ObjMRTableTbodyTrTdTable.appendChild(ObjMRTableTbodyTrTdTableTbody);
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTable);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
ObjMRTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTd.id = "ComposeMsgVideoContainer";
ObjMRTableTbodyTrTd.className = "ObjMRTableTbodyTrTd2";
ObjMRTableTbodyTrTd.style.display = "none";
if (NewHeaderStyle == false) {
ObjMRTableTbodyTrTd.style.paddingLeft = "1px";
ObjMRTableTbodyTrTd.style.paddingTop = "10px";
}
ObjMRTableTbodyTrTdIFrame = document.createElement("iframe");
ObjMRTableTbodyTrTdIFrame.id = "ComposeMsgVideoIFrame";
ObjMRTableTbodyTrTdIFrame.width = "242";
ObjMRTableTbodyTrTdIFrame.height = "204";
ObjMRTableTbodyTrTdIFrame.src = "html/blankiframe.html";
ObjMRTableTbodyTrTdIFrame.scrolling = "no";
ObjMRTableTbodyTrTdIFrame.frameBorder = "0";
ObjMRTableTbodyTrTdIFrame.marginHeight = "0";
ObjMRTableTbodyTrTdIFrame.marginWidth = "0";
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdIFrame.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdIFrame.style.border = "1px solid silver";
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdIFrame);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
ObjMRTableTbodyTr = document.createElement("tr");
ObjMRTableTbody.appendChild(ObjMRTableTbodyTr);
ObjMRTableTbodyTrTd = document.createElement("td");
ObjMRTableTbodyTrTd.id = "ComposeMsgTextContainer";
ObjMRTableTbodyTrTd.width = "100%";
ObjMRTableTbodyTrTd.height = "100%";
if (NewHeaderStyle == false) {
ObjMRTableTbodyTrTd.style.paddingLeft = "0px";
ObjMRTableTbodyTrTd.style.paddingTop = "0px";
}
ObjMRTableTbodyTrTd.style.border='1px solid #EEE';
ObjMRTableTbodyTrTdDiv = document.createElement("div");
ObjMRTableTbodyTrTdDiv.id = "SpellCheckerBox";
ObjMRTableTbodyTrTdDiv.style.display = "none";
ObjMRTableTbodyTrTdDiv.style.width = "100%";
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdDiv.style.height="100%";
} else {
ObjMRTableTbodyTrTdDiv.style.height="500px";
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdDiv);
ObjMRTableTbodyTrTdTextArea = document.createElement("textarea");
ObjMRTableTbodyTrTdTextArea.id = "ComposeMsgText";
var onFocusFunc = "FieldInFocus = true;";
ObjMRTableTbodyTrTdTextArea.onfocus = new Function(onFocusFunc);
var onBlurFunc = "FieldInFocus = false;";
ObjMRTableTbodyTrTdTextArea.onblur = new Function(onBlurFunc);
ObjMRTableTbodyTrTdTextArea.style.width = "100%";
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdTextArea.style.height="100%";
} else {
ObjMRTableTbodyTrTdTextArea.style.height="500px";
}
if (NewHeaderStyle == true) {
//ObjMRTableTbodyTrTdTextArea.style.border = "2px solid #bad4ea";
} else {
//ObjMRTableTbodyTrTdTextArea.style.border = "2px solid silver";
}
ObjMRTableTbodyTrTdTextArea.className = "ObjMRTableTbodyTrTdTextArea";
var OnFocusFunc = "FieldInFocus = true;";
ObjMRTableTbodyTrTdTextArea.onfocus = new Function(OnFocusFunc);
var OnBlurFunc = "FieldInFocus = false;";
ObjMRTableTbodyTrTdTextArea.onblur = new Function(OnBlurFunc);
// Load our Signature
var Signature = document.getElementById('Signature').innerHTML;
//alert(Signature);
if (ComposeMode == "HTML") {
// Add our signature, make line breaks into HTML
//Signature = Signature.replace(/\n|\r/gi, "<BR>");
} else {
// Add our signature, make line breaks into HTML
if (window.ActiveXObject)
Signature = Signature.replace(/<br>/gi, "\r");
Signature = Signature.replace(/<\/?[^>]+>/gi, "");
}
if (Reply) {
var MsgFrom = MsgReaderData[ShowMsg][3];
// Format the reply as a text
if(ComposeMode == "Text") {
var ReplyText = "";
if (Reply != "Open") {
// Add our signature, dont worry about linebreaks
ReplyText += "\n\r\n\r" + Signature;
ReplyText += "\n\r\n\rOn " + MsgReaderData[ShowMsg][4] + " , " + MsgFrom + " wrote:\n\r";
// Make the reply from the XML of the server, nicely formatted in PHP/html2text
ReplyText += MsgReaderData[ShowMsg][20];
} else {
// We are opening a draft message
ReplyText = MsgReaderData[ShowMsg][8];
}
ObjMRTableTbodyTrTdTextArea.value = ReplyText;
ObjMRTableTbodyTrTdTextArea.focus();
} else {
// We are replying to a message with the HTML editor
// Load the body
ObjMsgContainerDiv = document.createElement("div");
ObjMsgContainerDiv.id = "msgReply";
ObjMsgContainerDiv.className = "ObjMsgContainerDiv";
ObjMsgContainerDiv.style.display = "";
// Convert into HTML friendly format
MsgFrom = MsgFrom.replace(/</, '<');
MsgFrom = MsgFrom.replace(/>/, '>');
// MsgReaderData[ShowMsg][2] == subject
// MsgReaderData[ShowMsg][5] == To
// MsgReaderData[ShowMsg][6] == CC?
if (Reply != "Open") {
// Apply our default stylesheet to the message for fonts
ObjMsgContainerDiv.innerHTML = "<style> BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px; }</style><br><br>On " + MsgReaderData[ShowMsg][4] + " , " + MsgFrom + " wrote:<br><br>";
ObjMsgContainerDiv.innerHTML += "<BLOCKQUOTE style='BORDER-LEFT: #5167C6 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px; PADDING-RIGHT: 0px'>" + MsgReaderData[ShowMsg][8] + "</BLOCKQUOTE>";
ObjMRTableTbodyTrTd.appendChild(ObjMsgContainerDiv);
ObjMRTableTbodyTrTdTextArea.appendChild(document.createTextNode("<BR>" + Signature));
} else {
ObjMsgContainerDiv.innerHTML += MsgReaderData[ShowMsg][8];
ObjMRTableTbodyTrTd.appendChild(ObjMsgContainerDiv);
}
if(window.ActiveXObject) {
ObjMRTableTbodyTrTdTextArea.innerText += ObjMsgContainerDiv.innerHTML;
} else {
ObjMRTableTbodyTrTdTextArea.value += ObjMsgContainerDiv.innerHTML;
}
ObjMRTableTbodyTrTdTextArea.focus();
}
} else {
if (ComposeMode == "HTML") {
ObjMRTableTbodyTrTdTextArea.appendChild(document.createTextNode("<BR>" + Signature));
} else {
// Add our signature, dont worry about linebreaks
ObjMRTableTbodyTrTdTextArea.appendChild(document.createTextNode("\n\r\n\r" + Signature + "\n\r"));
}
// Make the To field the default selected in focus
document.getElementById('ComposeMsgTo').focus();
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTextArea);
ObjMRTableTbodyTr.appendChild(ObjMRTableTbodyTrTd);
if (ComposeMode == "HTML") {
oEdit1 = new FCKeditor("ComposeMsgText");
oEdit1.BasePath = 'javascript/fckeditor/';
oEdit1.Config["CustomConfigurationsPath"] = "javascript/fckeditor/atmailconfig.js";
oEdit1.ToolbarSet = 'Atmail';
oEdit1.ReplaceTextarea();
//FCKeditorAPI.GetInstance('ComposeMsgText').EditorDocument.style.height = '500px';
}
// If forwarding a message, we need to fire off a Ajax response to rename the MIME parts on disk
if (ReadMsgReply == "Forward") {
var RawAttachments = MsgReaderData[ShowMsg][13].split("::");
var AttachmentList = "";
for(i in RawAttachments) {
if(RawAttachments[i]) {
AttachmentList += unescape(RawAttachments[i]) + ", ";
}
}
// Take the last , off the name
AttachmentList = AttachmentList.substr(0, AttachmentList.length-2);
// Ajax call to move attachments on the server
AttachMIME(RawAttachments, unique);
document.getElementById('ComposeMsgAttachmentsRow').style.display = "";
document.getElementById('ComposeMsgAttachments').value = unescape(AttachmentList);
// Fire off our ajax request to make these attachments into our unique id for email
}
// Add select options for the Email Priority box
AddSelectOption('ComposeEmailPriority', Lang_Normal, 'Normal');
AddSelectOption('ComposeEmailPriority', Lang_High, 'High');
AddSelectOption('ComposeEmailPriority', Lang_Low, 'Low');
AddSelectOption('ComposeEmailPriority2', Lang_Normal, 'Normal');
AddSelectOption('ComposeEmailPriority2', Lang_High, 'High');
AddSelectOption('ComposeEmailPriority2', Lang_Low, 'Low');
// Add select options for the email-from field ( with different personalities if available )
var EmailFrom = document.getElementById('EmailFrom').innerHTML;
var EmailFromArray = EmailFrom.split("::");
for(i in EmailFromArray) {
if(EmailFromArray[i]) {
AddSelectOption("ComposeMsgFrom", EmailFromArray[i], EmailFromArray[i]);
}
}
// For Safari, doesn't add the To/CC/Bcc on top.opencompose for some unknown reason, must be at the end
if(navigator.userAgent.indexOf("Safari") != -1) {
if(To)
document.getElementById("ComposeMsgTo").value = To;
if(Cc)
document.getElementById("ComposeMsgCc").value = Cc;
if(Bcc)
document.getElementById("ComposeMsgBcc").value = Bcc;
}
DataIsLoading(false);
document.onselectstart = SelectText;
}
function SpellCheck(GetData) {
if (ComposeMode == "Text") {
ObjComposeMsgText = document.getElementById("ComposeMsgText");
}
if (GetData == true) {
DataIsLoading(true);
SpellChkWords.length = 0;
SpellChkReq = false;
if (SpellChkReq && SpellChkReq.readyState < 4) SpellChkReq.abort();
SpellChkReq = createXMLHttpRequest();
SpellChkReq.onreadystatechange = SpellChkReqChange;
var EmailMsg = "";
if (ComposeMode == "HTML") {
EmailMsg = FCKeditorAPI.GetInstance('ComposeMsgText').GetData();
} else if (ComposeMode == "Text") {
EmailMsg = ObjComposeMsgText.value;
}
var POSTString = "ajax=1&emailmessage=" + encodeURIComponent(EmailMsg);
SpellChkReq.open("POST", "spell.php", true);
SpellChkReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
SpellChkReq.send(POSTString);
} else {
LoadFolders("SpellChecker");
ObjSpellCheckerBox = document.getElementById("SpellCheckerBox");
if (ObjSpellCheckerBox.style.display == "none") {
if (ComposeMode == "HTML") {
ComposeModeStorage = FCKeditorAPI.GetInstance('ComposeMsgText').GetHTML();
oEdit1 = null;
ObjMRTableTbodyTrTd = document.getElementById("ComposeMsgTextContainer");
ObjMRTableTbodyTrTd.innerHTML = "";
ObjSpellCheckerBox = document.createElement("div");
ObjSpellCheckerBox.id = "SpellCheckerBox";
ObjSpellCheckerBox.style.display = "none";
if (window.ActiveXObject) {
ObjSpellCheckerBox.style.width = "100%";
ObjSpellCheckerBox.style.height = "100%";
} else {
ObjSpellCheckerBox.style.width = "97%";
ObjSpellCheckerBox.style.height = "500px";
}
ObjMRTableTbodyTrTd.appendChild(ObjSpellCheckerBox);
} else if (ComposeMode == "Text") {
ObjComposeMsgText.style.display = "none";
}
ObjSpellCheckerBox.className = "ObjSpellCheckerBox";
ObjSpellCheckerBox.style.display = "";
if (ComposeMode == "HTML") {
ObjSpellCheckerBox.style.padding = "42px 11px 11px 11px";
var AdjustedTxt = ComposeModeStorage;
} else if (ComposeMode == "Text") {
ObjSpellCheckerBox.style.padding = "2px 1px 1px 1px";
ObjSpellCheckerBox.style.cursor = "default";
var AdjustedTxt = ObjComposeMsgText.value.replace(/\r|\n/g, "<br>");
}
AjustedTxtArray.length = 0;
ObjAdjustedTxt = document.createElement("div");
ObjAdjustedTxt.innerHTML = AdjustedTxt;
CycleDOMNodes(ObjAdjustedTxt);
ObjSpellCheckerBox.innerHTML = ObjAdjustedTxt.innerHTML;
DataIsLoading(false);
} else {
ObjPopUpBox = document.getElementById("PopUpBox");
if (!window.ActiveXObject && ObjPopUpBox) document.body.removeChild(ObjPopUpBox);
LoadFolders("ComposeMsg");
ObjSpellCheckerBox = document.getElementById("SpellCheckerBox");
ObjSpellCheckerBox.style.display = "none";
for (var i in AjustedTxtArray) {
ObjSpellCheckerWord = document.getElementById("SpellChkWord" + i);
if (ObjSpellCheckerWord.childNodes[0].tagName == "INPUT") {
ObjSpellCheckerWord.parentNode.replaceChild(document.createTextNode(ObjSpellCheckerWord.childNodes[0].value), ObjSpellCheckerWord);
} else {
ObjSpellCheckerWord.parentNode.replaceChild(document.createTextNode(ObjSpellCheckerWord.innerHTML), ObjSpellCheckerWord);
}
}
var UpdatedMsgData = ObjSpellCheckerBox.innerHTML;
if (ComposeMode == "HTML") {
ObjMRTableTbodyTrTd = document.getElementById("ComposeMsgTextContainer");
ObjMRTableTbodyTrTd.innerHTML = "";
ObjSpellCheckerBox = document.createElement("div");
ObjSpellCheckerBox.id = "SpellCheckerBox";
ObjSpellCheckerBox.style.display = "none";
if (window.ActiveXObject) {
ObjSpellCheckerBox.style.width = "100%";
ObjSpellCheckerBox.style.height = "100%";
} else {
ObjSpellCheckerBox.style.width = "97%";
ObjSpellCheckerBox.style.height = "500px";
}
ObjMRTableTbodyTrTd.appendChild(ObjSpellCheckerBox);
ObjMRTableTbodyTrTdTextArea = document.createElement("textarea");
ObjMRTableTbodyTrTdTextArea.id = "ComposeMsgText";
ObjMRTableTbodyTrTdTextArea.value = UpdatedMsgData;
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTextArea);
oEdit1 = new FCKeditor("ComposeMsgText");
oEdit1.BasePath = 'javascript/fckeditor/';
oEdit1.Config["CustomConfigurationsPath"] = "javascript/fckeditor/atmailconfig.js";
oEdit1.ToolbarSet = 'Atmail';
oEdit1.ReplaceTextarea();
//FCKeditorAPI.GetInstance('ComposeMsgText').EditorDocument.style.height = '500px';
} else if (ComposeMode == "Text") {
ObjComposeMsgText.style.display = "";
UpdatedMsgData = UpdatedMsgData.replace(/<span>|<\/span>/gi, "");
UpdatedMsgData = UpdatedMsgData.replace(/<br>|<br \/>/gi, "\n");
UpdatedMsgData = UpdatedMsgData.replace(/</gi, "<");
UpdatedMsgData = UpdatedMsgData.replace(/>/gi, ">");
ObjComposeMsgText.value = UpdatedMsgData;
}
}
}
}
function SpellChkReqChange() {
if (SpellChkReq.readyState == 4 && SpellChkReq.status == 200) {
if (SpellChkReq.responseXML) {
try {
var error = SpellChkReq.responseXML.getElementsByTagName("Error").firstChild.nodeValue;
} catch (e){}
if (error) {
alert(error);
return;
}
for (var x = 0; x < SpellChkReq.responseXML.getElementsByTagName("Suggestion").length; x ++) {
SpellChkWords.push(SpellChkReq.responseXML.getElementsByTagName("Suggestion")[x].firstChild.data.split(","));
}
SpellCheck();
}
}
}
// Cycle through each DOM element for the spell check
function CycleDOMNodes(ObjMasterNode) {
for (var x = 0; x < ObjMasterNode.childNodes.length; x ++) {
if (ObjMasterNode.childNodes[x].hasChildNodes()) {
CycleDOMNodes(ObjMasterNode.childNodes[x]);
} else {
if (ObjMasterNode.childNodes[x].data != undefined) {
ObjNewTxtSpan = document.createElement("span");
ObjNewTxtSpan.innerHTML = CheckDOMSpelling(ObjMasterNode.childNodes[x].data);
ObjMasterNode.childNodes[x].parentNode.replaceChild(ObjNewTxtSpan, ObjMasterNode.childNodes[x]);
}
}
}
}
// Display the spell-check works on the DOM element
function CheckDOMSpelling(TextToCk) {
var AddSpace = false;
if (SpellChkWords.length > 0) {
TextToCk = TextToCk.split(/\b/);
for (var x in TextToCk) {
if (TextToCk[x].match(/\w/)) {
TextToCk[x] = new Array(TextToCk[x], false);
for (var y in SpellChkWords) {
if (TextToCk[x][0] == SpellChkWords[y][0] && TextToCk[x][1] == false) {
TextToCk[x][0] = "<span id=\"SpellChkWord" + AjustedTxtArray.length + "\" style=\"color: red; cursor: pointer; text-decoration: underline;\" onclick=\"SpellCheckSuggestion(" + AjustedTxtArray.length + ", " + y + ");\" oncontextmenu=\"SpellCheckSuggestion(" + AjustedTxtArray.length + ", " + y + "); return false;\">" + SpellChkWords[y][0] + "</span>";
TextToCk[x][1] = true;
AjustedTxtArray.push(1);
}
}
TextToCk[x] = TextToCk[x][0];
} else if (TextToCk[x] == " ") {
if(ComposeMode == 'HTML')
TextToCk[x] = " ";
}
}
return TextToCk.join("");
} else {
return TextToCk;
}
}
function SpellCheckSuggestion(TxtAryIndex, SpellWord, NoEdit) {
if (!NoEdit) NoEdit = false;
if (window.ActiveXObject) {
oPopup = window.createPopup();
var oPopBody = oPopup.document.body;
oPopBody.className = "oPopBody";
oPopBody.style.border = "1px solid #8EBEE5";
oPopBody.style.padding = "1px";
} else {
if (document.getElementById("PopUpBox")) {
document.body.removeChild(ObjPopUpBox);
}
}
ObjPopUpBox = document.createElement("div");
var PopUpBoxHeight = 4;
ObjCurrentWord = document.getElementById("SpellChkWord" + TxtAryIndex);
var CurrentWordTxt = "";
if (ObjCurrentWord.childNodes[0].tagName == "INPUT") {
CurrentWordTxt = ObjCurrentWord.childNodes[0].value;
} else {
CurrentWordTxt = ObjCurrentWord.childNodes[0].data;
}
var FoundMatch = false;
for (var i in SpellChkWords[SpellWord]) {
if (i > 0 && CurrentWordTxt != SpellChkWords[SpellWord][i]) {
PopUpBoxHeight += 25;
ObjPopUpBoxItem = document.createElement("div");
if (window.ActiveXObject) {
ObjPopUpBoxItem.onclick = "parent.SpellChkFixWord(" + TxtAryIndex + ", " + SpellWord + ", " + i + ", " + NoEdit + "); parent.oPopup.hide();";
ObjPopUpBoxItem.onmouseover = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseout = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.style.width = "100%";
} else {
var onClickFunc = "SpellChkFixWord(" + TxtAryIndex + ", " + SpellWord + ", " + i + ", " + NoEdit + "); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "165px";
}
ObjPopUpBoxItem.className = "ObjPopUpBoxItem4";
ObjPopUpBoxItem.style.cursor = "default";
ObjPopUpBoxItem.style.fontFamily = "Arial, Helvetica, sans-serif";
ObjPopUpBoxItem.style.fontSize = "9pt";
ObjPopUpBoxItem.style.padding = "5px";
ObjPopUpBoxItem.appendChild(document.createTextNode(SpellChkWords[SpellWord][i]));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
} else if (CurrentWordTxt == SpellChkWords[SpellWord][i]) {
FoundMatch = true;
}
}
if (CurrentWordTxt == SpellChkWords[SpellWord][0] || FoundMatch == false) {
if (SpellChkWords[SpellWord].length > 1) {
PopUpBoxHeight += 9;
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBoxItem.style.width = "100%";
ObjPopUpBoxItem.style.overflow = "hidden";
ObjPopUpBoxItem.style.height = "5px";
ObjPopUpBoxItem.style.cursor = "default";
ObjPopUpBoxItem.style.borderTop = "1px solid silver";
ObjPopUpBoxItem.style.marginTop = "4px";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
}
PopUpBoxHeight += 25;
ObjPopUpBoxItem = document.createElement("div");
if (window.ActiveXObject) {
ObjPopUpBoxItem.onclick = "parent.AddToDictionary(" + TxtAryIndex + "); parent.oPopup.hide();";
ObjPopUpBoxItem.onmouseover = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseout = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.style.width = "100%";
} else {
var onClickFunc = "AddToDictionary(" + TxtAryIndex + "); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "165px";
}
ObjPopUpBoxItem.className = "ObjPopUpBoxItem5";
ObjPopUpBoxItem.style.cursor = "default";
ObjPopUpBoxItem.style.fontFamily = "Arial, Helvetica, sans-serif";
ObjPopUpBoxItem.style.fontSize = "9pt";
ObjPopUpBoxItem.style.padding = "5px";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_AddWord));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
}
if (NoEdit != true) {
PopUpBoxHeight += 9;
ObjPopUpBoxItem = document.createElement("div");
ObjPopUpBoxItem.className = "ObjPopUpBoxItem";
ObjPopUpBoxItem.style.width = "100%";
ObjPopUpBoxItem.style.overflow = "hidden";
ObjPopUpBoxItem.style.height = "5px";
ObjPopUpBoxItem.style.cursor = "default";
ObjPopUpBoxItem.style.borderTop = "1px solid silver";
ObjPopUpBoxItem.style.marginTop = "4px";
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
PopUpBoxHeight += 25;
ObjPopUpBoxItem = document.createElement("div");
if (window.ActiveXObject) {
ObjPopUpBoxItem.onclick = "parent.SpellChkFixWord(" + TxtAryIndex + ", " + SpellWord + ", 'Edit'); parent.oPopup.hide();";
ObjPopUpBoxItem.onmouseover = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseout = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.style.width = "100%";
} else {
var onClickFunc = "SpellChkFixWord(" + TxtAryIndex + ", " + SpellWord + ", 'Edit'); document.body.removeChild(ObjPopUpBox);";
ObjPopUpBoxItem.onclick = new Function(onClickFunc);
var onMouseOverFunc = "this.style.backgroundColor = '#85b3dc'; this.style.color = 'white';";
ObjPopUpBoxItem.onmouseover = new Function(onMouseOverFunc);
var onMouseOutFunc = "this.style.backgroundColor = ''; this.style.color = 'black';";
ObjPopUpBoxItem.onmouseout = new Function(onMouseOutFunc);
ObjPopUpBoxItem.style.width = "165px";
}
ObjPopUpBoxItem.className = "ObjPopUpBoxItem5";
ObjPopUpBoxItem.style.cursor = "default";
ObjPopUpBoxItem.style.fontFamily = "Arial, Helvetica, sans-serif";
ObjPopUpBoxItem.style.fontSize = "9pt";
ObjPopUpBoxItem.style.padding = "5px";
ObjPopUpBoxItem.appendChild(document.createTextNode(Lang_Edit + " ..."));
ObjPopUpBox.appendChild(ObjPopUpBoxItem);
}
if (window.ActiveXObject) {
oPopBody.innerHTML = ObjPopUpBox.innerHTML;
oPopup.show(MousePosXY[0], MousePosXY[1], 175, PopUpBoxHeight, document.body);
} else {
ObjPopUpBox.id = "PopUpBox";
ObjPopUpBox.className = "ObjPopUpBox2";
ObjPopUpBox.style.border = "1px solid #8EBEE5";
ObjPopUpBox.style.padding = "1px";
ObjPopUpBox.style.position = "absolute";
ObjPopUpBox.style.width = "175px";
ObjPopUpBox.style.height = PopUpBoxHeight + "px";
ObjPopUpBox.style.top = MousePosXY[1];
ObjPopUpBox.style.left = MousePosXY[0];
ObjPopUpBox.style.backgroundColor = "white";
document.body.appendChild(ObjPopUpBox);
}
}
function SpellChkFixWord(TxtAryIndex, SpellWord, SpellWordCount, ConvertFromEdit) {
ObjSpellChkWord = document.getElementById("SpellChkWord" + TxtAryIndex);
if (SpellWordCount == "Edit") {
ObjSpellChkWord.onclick = "";
ObjSpellChkWord.innerHTML = "<input id=\"SpellChkEdit" + TxtAryIndex + "\" type=\"text\" value=\"" + ObjSpellChkWord.innerHTML + "\">";
ObjSpellChkEdit = document.getElementById("SpellChkEdit" + TxtAryIndex);
ObjSpellChkEdit.className = "ObjSpellChkEdit";
var OnDblClickFunc = "SpellCheckSuggestion(" + TxtAryIndex + ", " + SpellWord + ", true);";
ObjSpellChkEdit.ondblclick = new Function(OnDblClickFunc);
var OnFocusFunc = "FieldInFocus = true;";
ObjSpellChkEdit.onfocus = new Function(OnFocusFunc);
var OnBlurFunc = "FieldInFocus = false;";
ObjSpellChkEdit.onblur = new Function(OnBlurFunc);
var OnChangeFunc = "this.style.border = '1px solid green';";
ObjSpellChkEdit.onchange = new Function(OnChangeFunc);
ObjSpellChkEdit.focus();
} else {
ObjSpellChkWord.innerHTML = SpellChkWords[SpellWord][SpellWordCount];
ObjSpellChkWord.className = "ObjSpellChkWord";
if (ConvertFromEdit == true) {
var OnClickFunc = "SpellCheckSuggestion(" + TxtAryIndex + ", " + SpellWord + ");";
ObjSpellChkWord.onclick = new Function(OnClickFunc);
}
}
}
function AddToDictionary(TxtAryIndex) {
DataIsLoading(true);
ObjAddWord = document.getElementById("SpellChkWord" + TxtAryIndex);
ObjAddWord.style.color = "";
ObjAddWord.style.cursor = "";
ObjAddWord.style.textDecoration = "";
var AddWord = "";
if (ObjAddWord.childNodes[0].tagName == "INPUT") {
AddWord = ObjAddWord.childNodes[0].value;
ObjAddWord.replaceChild(document.createTextNode(AddWord), ObjAddWord.childNodes[0]);
} else {
AddWord = ObjAddWord.childNodes[0].data;
ObjAddWord.onclick = "";
}
AddToDicReq = false;
if (AddToDicReq && AddToDicReq.readyState < 4) AddToDicReq.abort();
AddToDicReq = createXMLHttpRequest();
AddToDicReq.onreadystatechange = AddToDicReqChange;
AddToDicReq.open("GET", "spell.php?add=1&replace=" + encodeURIComponent(AddWord), true);
AddToDicReq.send(null);
}
function AddToDicReqChange() {
if (AddToDicReq.readyState == 4 && AddToDicReq.status == 200) DataIsLoading(false);
}
function ReplaceTags(xStr) {
var regExp = /<p>/gi;
xStr = xStr.replace(regExp,"\n");
var regExp = /<br>/gi;
xStr = xStr.replace(regExp,"\n");
var regExp = /<\/?[^>]+>/gi;
xStr = xStr.replace(regExp,"");
var regExp = /</gi;
xStr = xStr.replace(regExp,"<");
var regExp = />/gi;
xStr = xStr.replace(regExp,">");
return xStr;
}
function ToggleBccRow(Override) {
ObjComposeMsgBccRow = document.getElementById("ComposeMsgBccRow");
if (Override == true) {
ObjComposeMsgBccRow.style.display = "";
} else {
if (ObjComposeMsgBccRow.style.display == "") {
ObjComposeMsgBccRow.style.display = "none";
} else {
ObjComposeMsgBccRow.style.display = "";
}
}
}
function UpdateAttachDiv(AttachmentList) {
ObjAttachmentsField = document.getElementById("ComposeMsgAttachments");
ObjAttachmentsRow = document.getElementById("ComposeMsgAttachmentsRow");
if (AttachmentList) {
ObjAttachmentsField.value = AttachmentList;
} else {
ObjAttachmentsField.value = "";
}
if (ObjAttachmentsField.value == "") {
ObjAttachmentsRow.style.display = "none";
} else {
ObjAttachmentsRow.style.display = "";
}
}
function ToggleComposeMode(HTML) {
if(navigator.userAgent.indexOf("Safari") != -1) {
alert("Currently Safari does not support HTML editing. This will be included once supported for Safari. In the meantime please use Firefox or IE for this feature");
return;
}
if (document.getElementById("SpellCheckerBox").style.display == "") {
alert("You can not change edit modes whilst using the spell checker.");
} else {
if (HTML == true && ComposeMode != "HTML") {
ComposeMode = "HTML";
document.getElementById("ComposeModeHTML").style.fontWeight = "bold";
document.getElementById("ComposeModeText").style.fontWeight = "";
document.getElementById("ComposeModeHTML2").style.fontWeight = "bold";
document.getElementById("ComposeModeText2").style.fontWeight = "";
ObjComposeMsgText = document.getElementById("ComposeMsgText");
oEdit1 = new FCKeditor("ComposeMsgText");
oEdit1.BasePath = 'javascript/fckeditor/';
oEdit1.Config["CustomConfigurationsPath"] = "javascript/fckeditor/atmailconfig.js";
oEdit1.ToolbarSet = 'Atmail';
ObjComposeMsgText.value = ObjComposeMsgText.value.replace(/\r|\n/g, "<br>\n");
oEdit1.ReplaceTextarea();
//FCKeditorAPI.GetInstance('ComposeMsgText').EditorDocument.style.height = '500px';
} else if (HTML == false && ComposeMode != "Text") {
ComposeMode = "Text";
document.getElementById("ComposeModeHTML").style.fontWeight = "";
document.getElementById("ComposeModeText").style.fontWeight = "bold";
document.getElementById("ComposeModeHTML2").style.fontWeight = "";
document.getElementById("ComposeModeText2").style.fontWeight = "bold";
ComposeModeStorage = FCKeditorAPI.GetInstance('ComposeMsgText').GetHTML();
oEdit1 = null;
ObjMRTableTbodyTrTd = document.getElementById("ComposeMsgTextContainer");
ObjMRTableTbodyTrTd.innerHTML = "";
ObjMRTableTbodyTrTdDiv = document.createElement("div");
ObjMRTableTbodyTrTdDiv.id = "SpellCheckerBox";
ObjMRTableTbodyTrTdDiv.style.display = "none";
ObjMRTableTbodyTrTdDiv.style.width = "100%";
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdDiv.style.height = "100%";
} else {
ObjMRTableTbodyTrTdDiv.style.height = "500px";
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdDiv);
ObjMRTableTbodyTrTdTextArea = document.createElement("textarea");
ObjMRTableTbodyTrTdTextArea.id = "ComposeMsgText";
ObjMRTableTbodyTrTdTextArea.style.width = "100%";
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdTextArea.style.height = "100%";
} else {
ObjMRTableTbodyTrTdTextArea.style.height = "500px";
}
if (NewHeaderStyle == true) {
ObjMRTableTbodyTrTdTextArea.style.border = "1px solid #bad4ea";
} else {
ObjMRTableTbodyTrTdTextArea.style.border = "1px solid silver";
}
ObjMRTableTbodyTrTdTextArea.className = "ObjMRTableTbodyTrTdTextArea2";
var OnFocusFunc = "FieldInFocus = true;";
ObjMRTableTbodyTrTdTextArea.onfocus = new Function(OnFocusFunc);
var OnBlurFunc = "FieldInFocus = false;";
ObjMRTableTbodyTrTdTextArea.onblur = new Function(OnBlurFunc);
ObjTmpDiv = document.createElement("div");
ObjTmpDiv.innerHTML = ComposeModeStorage;
if (window.ActiveXObject) {
ObjMRTableTbodyTrTdTextArea.innerText = ObjTmpDiv.innerText;
} else {
// For firefox use textContent rather then innerText
ObjMRTableTbodyTrTdTextArea.value = ObjTmpDiv.textContent;
}
ObjMRTableTbodyTrTd.appendChild(ObjMRTableTbodyTrTdTextArea);
ObjMRTableTbodyTrTdTextArea.focus();
}
}
}
function SendMsg(unique, draft) {
if (document.getElementById("ComposeMsgTo").value) {
DataIsLoading(true);
SendMessagesReq = false;
if (SendMessagesReq && SendMessagesReq.readyState < 4) SendMessagesReq.abort();
SendMessagesReq = createXMLHttpRequest();
SendMessagesReq.onreadystatechange = SendMessagesReqChange;
// Build our HTTP post for the message
var POSTString = "ajax=1&unique=" + encodeURIComponent(unique);
//+ "&UIDL=" + MsgSendUIDL + "&unique=" + MsgSendUnique + "&type=" + MsgSendType + "&DraftID=" + MsgSendDraftID + "&Draft=&Charset=" + MsgSendCharset;
// Character set
POSTString += "&Charset=" + encodeURIComponent(document.getElementById("ComposeMsgCharset").value);
// DraftID for replying/sending a draft ( used to delete the msg in the Draft folder after sending )
POSTString += "&DraftID=" + encodeURIComponent(document.getElementById("ComposeMsgDraftID").value);
// UIDL field ( used to pass on the message status, e.g forwarded, replied, etc
POSTString += "&UIDL=" + encodeURIComponent(document.getElementById("ComposeMsgUIDL").value);
try {
var id = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0];
var folder = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][1];
POSTString += "&id=" + encodeURIComponent(CalcMoveMsgs(id, folder));
}
catch(e) {
}
// Type field ( e.g forwarded, replied, for UIDL update )
POSTString += "&type=" + encodeURIComponent(document.getElementById("ComposeMsgType").value);
// Email To/Cc/Bcc/Header fields
POSTString += "&emailto=" + encodeURIComponent(document.getElementById("ComposeMsgTo").value);
POSTString += "&emailpriority=0";
POSTString += "&emailcc=" + encodeURIComponent(document.getElementById("ComposeMsgCc").value);
POSTString += "&emailfrom=" + encodeURIComponent(document.getElementById("ComposeMsgFrom").value);
var VideoStream = GetVideoID(false, encodeURIComponent(document.getElementById("ComposeMsgFrom").value), encodeURIComponent(document.getElementById("ComposeMsgSubject").value));
if (document.getElementById("VideoMail").value == 1) {
if (document.getElementById("ComposeMsgVideoContainer").style.display == "none") {
POSTString += "&emailpriority=" + encodeURIComponent(document.getElementById("ComposeEmailPriority").value);
if (VideoStream != null) {
if (confirm("You have a video recorded, do you want to send it?")) POSTString += "&VideoStream=" + VideoStream;
}
} else {
POSTString += "&emailpriority=" + encodeURIComponent(document.getElementById("ComposeEmailPriority2").value);
if (VideoStream != null) {
POSTString += "&VideoStream=" + VideoStream;
// Set the Videostream to null, message sent, so not to alert on the next compose attempt
VideoStreamUID = null;
}
}
} else {
POSTString += "&emailpriority=" + encodeURIComponent(document.getElementById("ComposeEmailPriority").value);
}
if(draft == '1') {
POSTString += "&Draft=1";
}
if (document.getElementById("ComposeMsgBcc").style.display == "") {
POSTString += "&emailbcc=" + encodeURIComponent(document.getElementById("ComposeMsgBcc").value);
}
POSTString += "&emailsubject=" + encodeURIComponent(document.getElementById("ComposeMsgSubject").value);
if (ComposeMode == "HTML") {
POSTString += "&contype=text/html";
// MUST CALL encodeURIComponent for big data on posts - Otherwise data will be stripped!
var msg = encodeURIComponent(FCKeditorAPI.GetInstance('ComposeMsgText').GetHTML());
POSTString += "&emailmessage=" + msg;
} else if (ComposeMode == "Text") {
POSTString += "&contype=text/plain";
// MUST CALL encodeURIComponent for big data on posts - Otherwise data will be stripped!
POSTString += "&emailmessage=" + encodeURIComponent(document.getElementById("ComposeMsgText").value);
}
SendMessagesReq.open("POST", "sendmail.php", true);
SendMessagesReq.setRequestHeader("Method", "POST sendmail.php HTTP/1.1");
SendMessagesReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
SendMessagesReq.setRequestHeader("Connection", "close");
try {
var type = document.getElementById("ComposeMsgType").value.toLowerCase();
// Update the message status buttons in realtime
if(type == 'reply' || type == 'forward') {
if (window.ActiveXObject) {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).src = "imgs/simple/shim.gif";
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_" + type + ".png', sizingMethod='image')";
} else {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][0]).src = "imgs/simple/icon_" + type + ".png";
}
}
} catch(e) {
}
SendMessagesReq.send(POSTString);
} else {
alert("Please enter an email address in the to field.");
}
}
function SendMessagesReqChange() {
if (SendMessagesReq.readyState == 4 && SendMessagesReq.status == 200) {
DataIsLoading(false);
// Check the response
if (SendMessagesReq.responseXML) {
try
{
var status = SendMessagesReq.responseXML.getElementsByTagName("Status")[0].firstChild.data;
if(status == 0) {
LoadFolders();
LoadMsgs(MsgListData['CurrentFolder']);
ShowEmailSentNotice();
} else {
alert(SendMessagesReq.responseXML.getElementsByTagName("StatusMessage")[0].firstChild.data);
LoadFolders();
LoadMsgs(MsgListData['CurrentFolder']);
}
return 0;
} catch(e) {
alert('Could not send message - Please check the recipients are correctly formatted and contact the System Admin');
}
}
}
}
// Calculate moved messages only if it's from the POP3 server in the Inbox, or IMAP ( any folder )
function CalcMoveMsgs(v, folder) {
// If expunge on logout, do not change the message array index
if(document.getElementById('Expunge').value == '1')
return v;
var c = 0;
if(MailType == 'pop3' && folder =='Inbox') {
for(i in MsgArrayMove) {
c++;
if(v == MsgArrayMove[i])
return c;
}
} else {
return v;
}
}
// Splice the array down for POP3/IMAP mailboxes, so the unique ID is in sync
function SpliceMoveMsgs(v, folder) {
var c = 0;
// We need to correct our ID if we have moved messages in the past too!
v = CalcMoveMsgs(v, folder);
if(!parseInt(v)) return v;
for(i in MsgArrayMove) {
if(MsgArrayMove[i] == v) MsgArrayMove.splice(c,1);
c++;
}
}
function StyleSheetChanger() {
var mysheet=document.styleSheets[0]
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules
mysheet.crossdelete=mysheet.deleteRule? mysheet.deleteRule : mysheet.removeRule
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase().indexOf("a")!=-1){
mysheet.crossdelete(i)
i-- //decrement i by 1, since deleting a rule collapses the array by 1
}
}
}
// Check our response - If it's an error reload the entire Window with the Error message ( e.g timeout, password, access probs )
function CheckXMLError(XMLReq) {
try
{
var err = XMLReq.responseXML.getElementsByTagName("ErrorMessage")[0].firstChild.data;
if (XMLReq.responseXML.getElementsByTagName("ErrorMessage")[0].getAttribute('action') == 'logout')
{
alert(err);
document.location = 'index.php?func=logout';
return;
}
document.write(err);
return 0;
}
catch (e)
{
return 1;
}
}
function TestAjaxFrame(func, args) {
if(!args)
args = '';
// Test if we are inside the Ajax panel
try
{
var ErrorText = document.getElementById("FolderBox").innerHTML;
}
catch (e)
{
window.location.href='parse.php?file=html/LANG/simple/showmail_interface.html&ajax=1&func=' + func + '&' + args;
return 1;
}
}
function TestAjaxFrameNull() {
// Test if we are inside the Ajax panel
try
{
var ErrorText = document.getElementById("FolderBox").innerHTML;
}
catch (e)
{
return 1;
}
}
// About Window for @Mail
function aboutwin() {
var wdh = 270; hgt = 290;
helpWin = open('util.php?func=about', '', 'width=' + wdh + ',height=' + hgt + ',left=100,top=100,scrollbars=no');
}
function LoadingFade() {
fadeIn("Connecting", 100);
fadeIn("LoadingImage", 100);
}
function FadeStatus(objId, opacity) {
if (opacity >= 0) {
opacity -= 5;
this.ObjFadeWindow.style.filter = "Alpha(Opacity=" + opacity + ");";
window.setTimeout("FadeStatus('"+objId+"',"+opacity+")", 10);
}
if(opacity == '0')
this.ObjFadeWindow.parentNode.removeChild(this.ObjFadeWindow);
}
function FadeStatusReverse(objId, opacity) {
if (opacity <= 65) {
opacity += 5;
this.ObjFadeWindow.style.filter = "Alpha(Opacity=" + opacity + ");";
window.setTimeout("FadeStatusReverse('"+objId+"',"+opacity+")", 10);
}
}
function LogoutAjax(EmptyTrash) {
LoadLoginPage('5');
FadeStatusReverse(this.ObjFadeWindow, '5');
}
function WebmailLogin(username, domain, password, mailserver, protocol, language) {
//atmailRoot = (BrowserVer.Type == 'Firefox') ? '../' : '';
atmailroot = document.location.href;
atmailroot = atmailroot.replace(/index\.php.*/, '');
DataIsLoading(true);
WebMailLoginReq = createXMLHttpRequest();
WebMailLoginReq.onreadystatechange = WebMailLoginReqChange;
var POSTString = "ajax=1&username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password) + "&MailServer=" + encodeURIComponent(mailserver) + "&pop3host=" + encodeURIComponent(domain) + "&MailType=" + encodeURIComponent(protocol) + "&Language=" + "&LoginType=ajax";
WebMailLoginReq.open("POST", atmailroot + "/atmail.php", true);
WebMailLoginReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
WebMailLoginReq.send(POSTString);
}
function WebMailLoginReqChange() {
if (WebMailLoginReq.readyState == 4 && WebMailLoginReq.status == 200) {
DataIsLoading(false);
var err;
try
{
err = WebMailLoginReq.responseXML.getElementsByTagName("ErrorMessage")[0].firstChild.data;
} catch(e) {
}
if ( WebMailLoginReq.responseXML && err ) {
//alert('Cannot login in, there is an error. Check login details and mail-server responding');
//var ErrorBody = WebMailLoginReq.responseXML.getElementsByTagName("ErrorBody")[0].firstChild.data;
//alert(ErrorBody);
GroupingFrame.document.getElementById('AuthStatus').innerHTML = "<font color='red'>Server responded: " + err + "</font>";
return 0;
} else {
document.getElementById('EmailFrom').innerHTML=WebMailLoginReq.responseText;
FadeStatus(ObjFadeWindow, '65');
location.href='parse.php?file=html/LANG/simple/showmail_interface.html&ajax=1&func=Inbox&To=';
LoadMsgs();
}
}
}
function LoadLoginPage(Amount) {
this.ObjAdvancedWindow = createObjAdvancedWindow(ColorScheme, "440px", "310px");
document.body.appendChild(this.ObjAdvancedWindow);
document.getElementById("ObjAdvancedWindow").style.display = "none";
this.ObjAdvancedWindowBody = document.createElement("div");
this.ObjAdvancedWindowBody.style.width = (BrowserVer.Type == "MSIE") ? "100%" : "99%";
this.ObjAdvancedWindowBody.style.height = (BrowserVer.Type == "MSIE") ? "100%" : "99%";
this.ObjAdvancedWindowBody.style.backgroundColor = "#ffffff";
this.ObjAdvancedWindowBody.style.padding = "2px";
this.ObjAdvancedWindow.appendChild(this.ObjAdvancedWindowBody);
var ObjIFrame = document.createElement("iframe");
ObjIFrame.name = "GroupingFrame";
ObjIFrame.scrolling = "auto";
ObjIFrame.width = "100%";
ObjIFrame.height = "100%";
ObjIFrame.src = "parse.php?file=html/login-light.html";
ObjIFrame.frameBorder = "0";
ObjIFrame.marginHeight = "0";
ObjIFrame.marginWidth = "0";
ObjIFrame.application = "yes";
this.ObjAdvancedWindowBody.appendChild(ObjIFrame);
centerObjAdvancedWindow();
document.getElementById("ObjAdvancedWindow").style.display = "";
centerObjAdvancedWindow();
DataIsLoading(false);
}
function BrowserVerChk() {
this.Type = false;
this.TypeLong = false;
this.Version = false;
this.LateGen = false;
if (navigator.appVersion.indexOf("MSIE") != -1) {
this.Type = "MSIE";
this.TypeLong = "Internet Explorer";
var TempArray = navigator.appVersion.split("MSIE");
this.Version = parseFloat(TempArray[1]);
if (this.Version >= 6) this.LateGen = true;
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
this.Type = "Firefox";
this.TypeLong = "Firefox";
var VersionIndex = navigator.userAgent.indexOf("Firefox") + 8;
this.Version = parseFloat(navigator.userAgent.charAt(VersionIndex) + "." + navigator.userAgent.charAt(VersionIndex + 2)) * 1;
if (this.Version >= 1.5) this.LateGen = true;
}
}
function fadeIn(objId,opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity >= 0) {
setOpacity(obj, opacity);
opacity -= 10;
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 20);
}
}
}
function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
obj.style.opacity = opacity/100;
if(opacity == 0) {
document.getElementById("LoadingText").style.display = "none";
document.getElementById("LoadingIcon").style.display = "none";
document.getElementById("BrandingLogo").style.display = "";
document.body.style.cursor = '';
}
}
// Change an attachment MIME for forwarding
function AttachMIME(AttachmentList, unique) {
AttachMIMEsReq = false;
if (AttachMIMEsReq && AttachMIMEsReq.readyState < 4) AttachMIMEsReq.abort();
AttachMIMEsReq = createXMLHttpRequest();
AttachMIMEsReq.onreadystatechange = AttachMIMEsReqChange;
// Build our HTTP post for the message
var POSTString = "func=renameattach&ajax=1&unique=" + encodeURIComponent(unique);
for(i in AttachmentList) {
// Unescape the attachment name when sending, since encodeURICompontent will do it twice
if(AttachmentList[i])
POSTString += "&Attachment[]=" + encodeURIComponent(unescape(AttachmentList[i]));
}
AttachMIMEsReq.open("GET", "compose.php?" + POSTString, true);
AttachMIMEsReq.send(null);
}
function AttachMIMEsReqChange() {
if (AttachMIMEsReq.readyState == 4 && AttachMIMEsReq.status == 200) {
DataIsLoading(false);
}
}
// Create select box options ( for compose panel )
function AddSelectOption(selectbox, text, value) {
var option = document.createElement('option');
option.text = text;
option.value = value;
var select = document.getElementById(selectbox);
try {
select.add(option, null); // standards compliant; doesn't work in IE
}
catch(e) {
select.add(option); // IE only
}
}
// Delete the message cache, then reload the email from the server w/ the images set
function DisplayImages() {
id = MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0];
MsgListData["Data"][MsgListData["Ctrl"]["Selected"][0]][0] = false;
ReadMsg(null, null, null, 1);
}
// Load an XML doc, on success eval object
function loadXMLDoc(url, object) {
// branch for native XMLHttpRequest object
req = createXMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
function processReqChange(object) {
// only if req shows "loaded"
if (req.readyState == 4 && req.status == 200) {
DisplayImages();
return true
} else {
return false
}
}
// Legacy function to open compose panel - From ReadMsg.pm and abook functions
function opencompose(to, cc, bcc, target) {
ComposeMsg(null, to, cc, bcc);
}
function help(currFile, lang) {
var wdh = 700; hgt = 500;
if(!currFile)
currFile = 'file.html'
helpWin = open('parse.php?file=html/' + lang + '/help/filexp.html&FirstLoad=1&HelpFile=' + currFile + '', '', 'width=' + wdh + ',height=' + hgt + ',left=100,top=100,status=no,resizable=yes,scrollbars=yes');
}
function MarkMessage(Flag) {
DataIsLoading(true);
MarkMessageReq = false;
if (MarkMessageReq && MarkMessageReq.readyState < 4) MarkMessageReq.abort();
MarkMessageReq = createXMLHttpRequest();
var ids = '';
var folders = '';
for (i in MsgListData["Ctrl"]["Selected"]) {
ids += "&id[]=" + MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][0];
folders += "&folders[]=" + Url.encode(MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][1]);
//uidl += MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][12];
}
MarkMessageReq.open("GET", "showmail.php?ajax=1" + folders + ids + "&Flag=" + encodeURIComponent(Flag), true);
MarkMessageReq.send(null);
for (i in MsgListData["Ctrl"]["Selected"]) {
if (Flag == 'o') {
MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][9] = "read";
if (window.ActiveXObject) {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).src = "imgs/simple/shim.gif";
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_read.png', sizingMethod='image')";
} else {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).src = "imgs/simple/icon_read.png";
}
document.getElementById("ListBoxMsgFrom" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgSubject" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgDate" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDiv2";
document.getElementById("ListBoxMsgSize" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDiv2";
} else if(Flag == 'x') {
MsgListData["Data"][MsgListData["Ctrl"]["Selected"][i]][9] = "unread";
if (window.ActiveXObject) {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).src = "imgs/simple/shim.gif";
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imgs/simple/icon_unread.png', sizingMethod='image')";
} else {
document.getElementById("ListBoxMsgIcon" + MsgListData["Ctrl"]["Selected"][i]).src = "imgs/simple/icon_unread.png";
}
document.getElementById("ListBoxMsgFrom" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDivBold";
document.getElementById("ListBoxMsgSubject" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDivBold";
document.getElementById("ListBoxMsgDate" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDivBold";
document.getElementById("ListBoxMsgSize" + MsgListData["Ctrl"]["Selected"][i]).className = "ObjMLTableTbodyTrTdDivBoldSize";
}
}
DataIsLoading(false);
}
function TestSubjectReply(Type, Subject) {
if(Type == 'Reply' || Type == 'ReplyAll') {
var group = new RegExp(/^Re.*?:|^Ynt|^TR:|^Oggetto:|^VS:|^Awt:|^Aw:|^TR:|^R:|^RES:/i);
// If one of the Subject replys match, return as normal
if(group.exec(Subject)) {
return Subject;
} else {
// Otherwise append Re: subject
return "Re: " + Subject;
}
} else if(Type == 'Forward') {
var group = new RegExp(/^Fwd:/i);
// If the subject has Fwd, return as normal
if(group.exec(Subject)) {
return Subject;
} else {
// Otherwise append Fwd: subject
return "Fwd: " + Subject;
}
} else {
return Subject;
}
}
function getXMLfieldName(XMLobj, Field) {
var field;
try {
field = XMLobj.getElementsByTagName(Field)[0].firstChild.data;
} catch(e) {
field = '';
}
return field;
}
function formatHTMLtoText(txt, ReadMsgReply) {
var regExp = /<\/?[^>]+>/gi;
// remove newlines from html so we
// only have newlines made from <br> tags
txt = txt.replace(/\n/g, '');
txt = txt.replace(/<BR>/gi,"\n");
txt = txt.replace(/<P>/gi,"\n");
txt = txt.replace(/ /gi, ' ');
txt = txt.replace(/"/gi, '"');
txt = txt.replace(/>/gi, '>');
txt = txt.replace(/</gi, '<');
txt = txt.replace(/&/gi, '&');
txt = txt.replace(/©/gi, '(c)');
txt = txt.replace(/™/gi, '(tm)');
txt = txt.replace(/“/g, '"');
txt = txt.replace(/”/g, '"');
txt = txt.replace(/–/g, '-');
txt = txt.replace(/’/g, "'");
txt = txt.replace(/&/g, '&');
txt = txt.replace(/©/g, '(c)');
txt = txt.replace(/™/g, '(tm)');
txt = txt.replace(/—/g, '--');
txt = txt.replace(/“/g, '"');
txt = txt.replace(/”/g, '"');
txt = txt.replace(/•/g, '*');
txt = txt.replace(/®/ig, '(R)');
txt = txt.replace(/•/ig, '*');
txt = txt.replace(/&[&;]+;/g, '');
txt = txt.replace(regExp,"");
// If we are replying, quote email
if(ReadMsgReply == 'Reply') {
txt = txt.replace(/^\s?/gm, "\n>");
txt = txt.replace(/^$/gm, "");
}
return txt;
}
function drawDate(elem) {
var curdate = new Date()
var DayOfWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var MonthName = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var minutes = curdate.getMinutes();
if (minutes < 10) minutes = '0' + minutes;
var MsgDate = DayOfWeek[curdate.getDay()] + " " + MonthName[curdate.getMonth()] + " " + curdate.getDate() + " " + curdate.getHours() + ":" + minutes;
}
// Make in one template
function createObjFadeWindow() {
WindowOpen = true;
try {
changeScroll('hidden');
} catch(e) {
}
var ObjNewFadeWindow = document.createElement("div");
ObjNewFadeWindow.id = "ObjFadeWindow";
ObjNewFadeWindow.style.position = "absolute";
ObjNewFadeWindow.style.top = "0px";
ObjNewFadeWindow.style.left = "0px";
ObjNewFadeWindow.style.width = "100%";
ObjNewFadeWindow.style.height = "100%";
ObjNewFadeWindow.style.backgroundColor = "#b3b3b3";
ObjNewFadeWindow.style.cursor = "not-allowed";
ObjNewFadeWindow.style.filter = "Alpha(Opacity=50)";
ObjNewFadeWindow.style.opacity = "0.50";
ObjNewFadeWindow.style.zIndex = "995";
return ObjNewFadeWindow;
}
// Get the window height for resizing the floating div
function getWindowHeight() {
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
// Get the window width for resizing the floating div
function getWindowWidth() {
var windowWidth = 0;
if (typeof(window.innerWidth) == 'number') {
windowWidth = window.innerWidth;
}
else {
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth = document.documentElement.clientWidth;
}
else {
if (document.body && document.body.clientWidth) {
windowWidth = document.body.clientWidth;
}
}
}
return windowWidth;
}
function createObjAdvancedWindow(ColorScheme, Width, Height, Top, Left) {
if (!Top) Top = "20%";
if (!Left) Left = "15%";
if (!Width) Width = "70%";
if (!Height) Height = "60%";
var ObjAdvancedWindow = document.createElement("div");
ObjAdvancedWindow.id = "ObjAdvancedWindow";
ObjAdvancedWindow.style.position = "absolute";
// Center of the screen please!
ObjAdvancedWindow.style.margin = 'auto';
ObjAdvancedWindow.style.textAlign = 'left';
//ObjAdvancedWindow.style.top = Top;
//ObjAdvancedWindow.style.left = Left;
ObjAdvancedWindow.style.width = Width;
ObjAdvancedWindow.style.height = Height;
ObjAdvancedWindow.style.borderTop = "2px solid " + AppColors[ColorScheme][0];
ObjAdvancedWindow.style.borderRight = "1px solid " + AppColors[ColorScheme][0];
ObjAdvancedWindow.style.borderBottom = "2px solid " + AppColors[ColorScheme][0];
ObjAdvancedWindow.style.borderLeft = "1px solid " + AppColors[ColorScheme][0];
ObjAdvancedWindow.style.backgroundColor = AppColors[ColorScheme][1];
ObjAdvancedWindow.style.padding = "2px";
ObjAdvancedWindow.style.zIndex = "999";
WindowOpen = true;
return ObjAdvancedWindow;
}
function centerObjAdvancedWindow() {
if (BrowserVer.Type == "Safari") {
var contentElement = document.getElementById('ObjAdvancedWindow');
contentElement.style.top = '20%';
contentElement.style.left = '20%';
return
}
if (document.getElementById) {
var windowHeight = getWindowHeight();
var windowWidth = getWindowWidth();
//alert('in center = ' + windowHeight);
if (windowHeight > 0) {
var contentElement = document.getElementById('ObjAdvancedWindow');
if (contentElement) {
var contentHeight = contentElement.offsetHeight;
var contentWidth = contentElement.offsetWidth;
// Background "Halo" effect needs a little offset under IE
//if(BrowserVer.Type == "MSIE")
// contentHeight = contentHeight - 4;
if (windowHeight - contentHeight > 0) {
//contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
// Required for IE. style.margin = 'auto'; in FF works already
//if(BrowserVer.Type == "MSIE")
contentElement.style.left = ((windowWidth / 2) - (contentWidth / 2)) + 'px';
}
else {
//alert('in here ie?');
contentElement.style.position = 'static';
}
}
}
if (document.getElementById('ObjFadeWindow') && document.getElementById("ObjAdvancedWindow")) {
if (document.getElementById('ObjAdvancedWindow').style.width == '599px') {
document.getElementById('ObjFadeWindow').style.backgroundImage = "url(imgs/caloverlay-big.png)";
} else {
document.getElementById('ObjFadeWindow').style.backgroundImage = "url(imgs/caloverlay-small.png)";
}
document.getElementById('ObjFadeWindow').style.backgroundRepeat = "no-repeat";
document.getElementById('ObjFadeWindow').style.backgroundPosition = "center";
}
}
}
function centerObjWindow() {
try {
centerObjAdvancedWindow();
} catch(e) {
}
}
| BigBlueHat/atmailopen | javascript/ajax/ajax-int.js | JavaScript | apache-2.0 | 190,333 |
# Epipremnum giganteum (Roxb.) Schott SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Epipremnum/Epipremnum giganteum/README.md | Markdown | apache-2.0 | 193 |
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014-2019 Couchbase, 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.
*/
#ifndef LCB_DURABILITY_INTERNAL_H
#define LCB_DURABILITY_INTERNAL_H
#ifdef __cplusplus
#include "mctx-helper.h"
extern "C" {
#endif
/**
* @name internal durability functions
* These functions are used internally beyond the durability module.
* @{
*/
/** Indicate that this durability command context is for an original storage op */
void lcbdurctx_set_durstore(lcb_MULTICMD_CTX *ctx, int enabled);
void lcbdur_destroy(void *dset);
/**@}
*
* The rest of this file is internal to the various durability operations and
* is not accessed by the rest of the codebase
*/
#ifdef __cplusplus
}
#endif
#ifdef LCBDUR_PRIV_SYMS
namespace lcb
{
namespace durability
{
/**
* Here is the internal API for the durability functions.
*
* Durability works on polling multiple observe responses and waiting until a
* key (or set of keys) have either been persisted, or the wait period has
* expired.
*
* The operation maintains an internal counter which counts how many keys
* do not have a conclusive observe response yet (i.e. how many do not have
* their criteria satisfied yet). The operation is considered complete when
* the counter reaches 0.
*/
/**
* Information about a particular server's state -- whether it has been
* persisted to or replicated to. This is tied to a given mc_SERVER
* instance.
*/
struct ServerInfo {
const lcb::Server *server; /**< Server pointer (for comparison only) */
lcb_U16 persisted; /**< Exists on server */
lcb_U16 exists; /**< Persisted to server */
ServerInfo() : server(NULL), persisted(0), exists(0) {}
void clear()
{
server = NULL;
persisted = 0;
exists = 0;
}
};
struct Durset;
// For use in conjunction with MCREQ_F_PRIVCALLBACK
struct CallbackCookie {
lcb_RESPCALLBACK callback;
CallbackCookie() : callback(NULL) {}
};
/**Information a single entry in a durability set. Each entry contains a single
* key */
struct Item : public CallbackCookie {
Item() : reqcas(0), reqseqno(0), uuid(0), result(), parent(NULL), vbid(0), done(0) {}
/**
* Returns true if the entry is complete, false otherwise. This only assumes
* successful entries.
*/
bool is_all_done() const;
/**
* Determine if this item has been satisfied on a specific server. This
* function is used to determine if a probe should be sent to the server.
*
* If there are no items "tied" to the server (because they have all been
* completed) then we employ a bandwidth saving optimization by not sending
* additional probes to it.
*
* @param info Server to check against
* @param is_master If this server is the master for the item's vbucket
*
* @return true if the item is both persisted and replicated on the server,
* OR if the item has been replicated, but replication is not
* required for the item.
*/
bool is_server_done(const ServerInfo &info, bool is_master) const;
/**
* Updates the state of the given entry and synchronizes it with the
* current server list.
*
* Specifically this function will return a list of
* servers which still need to be contacted, and will increment internal
* counters on behalf of those (still active) servers which the item has
* already been replicated to (and persisted to, if requested).
*
* This will invalidate any cached information of the cluster configuration
* in respect to this item has changed -- this includes things like servers
* moving indices or being recreated entirely.
*
* This function should be called during poll().
* @param[out] ixarray An array of server indices which should be queried
* @return the number of effective entries in the array.
*/
size_t prepare(uint16_t ixarray[4]);
enum UpdateFlags { NO_CHANGES = 0x00, UPDATE_PERSISTED = 0x01, UPDATE_REPLICATED = 0x02 };
/**
* Update an item's status.
* @param flags OR'd set of UPDATE_PERSISTED and UPDATE_REPLICATED
* @param ix The server index
*/
void update(int flags, int srvix);
/**
* Set the logical state of the entry to done, and invoke the callback.
* It is safe to call this multiple times
*/
void finish();
void finish(lcb_STATUS err)
{
result.rc = err;
finish();
}
lcb_RESPENDURE &res()
{
return result;
}
const lcb_RESPENDURE &res() const
{
return result;
}
ServerInfo *get_server_info(int index);
lcb_U64 reqcas; /**< Last known CAS for the user */
lcb_U64 reqseqno; /**< Last known seqno for the user */
lcb_U64 uuid;
lcb_RESPENDURE result; /**< Result to be passed to user */
Durset *parent;
lcb_U16 vbid; /**< vBucket ID (computed via hashkey) */
lcb_U8 done; /**< Whether we have a conclusive result for this entry */
/** Array of servers which have satisfied constraints */
ServerInfo sinfo[4];
};
/**
* A collection encompassing one or more entries which are to be checked for
* persistence
*/
struct Durset : public MultiCmdContext {
/**
* Call this when the polling method (poll_impl()) has completed. This will
* trigger a new poll after the interval.
*/
void on_poll_done();
void incref()
{
refcnt++;
}
/**
* Decrement the refcount for the 'dset'. When it hits zero then the dset is
* freed
*/
void decref()
{
if (!--refcnt) {
delete this;
}
}
enum State { STATE_OBSPOLL, STATE_INIT, STATE_TIMEOUT, STATE_IGNORE };
/**
* Schedules us to be notified with the given state within a particular amount
* of time. This is used both for the timeout and for the interval
*/
void switch_state(State state);
/**
* Called from mctx_schedule(). This allows implementations to do any
* additional bookeeping, having guaranteed that all items are now
* added.
*/
virtual lcb_STATUS prepare_schedule()
{
return LCB_SUCCESS;
}
/**
* Called from mctx_add. Called to register any item-specific data (i.e.
* to associate item data with internal structures)
* @param itm the newly added item
* @param the original command, for more context
*/
virtual lcb_STATUS after_add(Item &, const lcb_CMDENDURE *)
{
return LCB_SUCCESS;
}
/**
* Called to actually check for persistence/replication. This must be
* implemented.
*/
virtual lcb_STATUS poll_impl() = 0;
virtual ~Durset();
Durset(lcb_INSTANCE *instance, const lcb_durability_opts_t *options);
// Implementation for MULTICMD_CTX
lcb_STATUS MCTX_done(const void *cookie);
lcb_STATUS MCTX_addcmd(const lcb_CMDBASE *cmd);
void MCTX_fail();
void MCTX_setspan(lcbtrace_SPAN *span);
/**
* This function calls poll_impl(). The implementation should then call
* on_poll_done() once the polling is finished
*/
inline void poll();
/** Called after timeouts and intervals. */
inline void tick();
static Durset *createSeqnoDurset(lcb_INSTANCE *, const lcb_durability_opts_t *);
lcb_DURABILITYOPTSv0 opts; /**< Sanitized user options */
std::vector< Item > entries;
unsigned nremaining; /**< Number of entries remaining to poll for */
int waiting; /**< Set if currently awaiting an observe callback */
unsigned refcnt; /**< Reference count */
State next_state; /**< Internal state */
lcb_STATUS lasterr;
bool is_durstore; /** Whether the callback should be DURSTORE */
std::string kvbufs; /**< Backing storage for key buffers */
const void *cookie; /**< User cookie */
hrtime_t ns_timeout; /**< Timestamp of next timeout */
void *timer;
lcb_INSTANCE *instance;
lcbtrace_SPAN *span;
};
} // namespace durability
} // namespace lcb
#endif // __cplusplus
#endif // LCB_DURABILITY_INTERNAL_H
| avsej/libcouchbase | src/operations/durability_internal.h | C | apache-2.0 | 8,742 |
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.httpd;
import com.google.common.base.Strings;
import com.google.gerrit.audit.AuditEvent;
import com.google.gerrit.audit.AuditService;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.AccountManager;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.util.TimeUtil;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Singleton
public class HttpLogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final DynamicItem<WebSession> webSession;
private final Provider<String> urlProvider;
private final String logoutUrl;
private final AuditService audit;
@Inject
protected HttpLogoutServlet(final AuthConfig authConfig,
final DynamicItem<WebSession> webSession,
@CanonicalWebUrl @Nullable final Provider<String> urlProvider,
final AccountManager accountManager,
final AuditService audit) {
this.webSession = webSession;
this.urlProvider = urlProvider;
this.logoutUrl = authConfig.getLogoutURL();
this.audit = audit;
}
protected void doLogout(final HttpServletRequest req,
final HttpServletResponse rsp) throws IOException {
webSession.get().logout();
if (logoutUrl != null) {
rsp.sendRedirect(logoutUrl);
} else {
String url = urlProvider.get();
if (Strings.isNullOrEmpty(url)) {
url = req.getContextPath();
}
if (Strings.isNullOrEmpty(url)) {
url = "/";
}
if (!url.endsWith("/")) {
url += "/";
}
rsp.sendRedirect(url);
}
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse rsp) throws IOException {
final String sid = webSession.get().getSessionId();
final CurrentUser currentUser = webSession.get().getCurrentUser();
final String what = "sign out";
final long when = TimeUtil.nowMs();
try {
doLogout(req, rsp);
} finally {
audit.dispatch(new AuditEvent(sid, currentUser,
what, when, null, null));
}
}
}
| Team-OctOS/host_gerrit | gerrit-httpd/src/main/java/com/google/gerrit/httpd/HttpLogoutServlet.java | Java | apache-2.0 | 3,085 |
=begin
#ARTIK Cloud API
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require 'uri'
module ArtikCloud
class Configuration
# Defines url scheme
attr_accessor :scheme
# Defines url host
attr_accessor :host
# Defines url base path
attr_accessor :base_path
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines the access token (Bearer) used with OAuth2.
attr_accessor :access_token
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# The time limit for HTTP request in seconds.
# Default to 0 (never times out).
attr_accessor :timeout
### TLS/SSL setting
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
### TLS/SSL setting
# Set this to false to skip verifying SSL host name
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl_host
### TLS/SSL setting
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
### TLS/SSL setting
# Client certificate file (for client certificate)
attr_accessor :cert_file
### TLS/SSL setting
# Client private key file (for client certificate)
attr_accessor :key_file
# Set this to customize parameters encoding of array parameter with multi collectionFormat.
# Default to nil.
#
# @see The params_encoding option of Ethon. Related source code:
# https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
attr_accessor :params_encoding
attr_accessor :inject_format
attr_accessor :force_ending_format
def initialize
@scheme = 'https'
@host = 'api.artik.cloud'
@base_path = '/v1.1'
@api_key = {}
@api_key_prefix = {}
@timeout = 0
@verify_ssl = true
@verify_ssl_host = true
@params_encoding = nil
@cert_file = nil
@key_file = nil
@debugging = false
@inject_format = false
@force_ending_format = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
yield(self) if block_given?
end
# The default Configuration object.
def self.default
@@default ||= Configuration.new
end
def configure
yield(self) if block_given?
end
def scheme=(scheme)
# remove :// from scheme
@scheme = scheme.sub(/:\/\//, '')
end
def host=(host)
# remove http(s):// and anything after a slash
@host = host.sub(/https?:\/\//, '').split('/').first
end
def base_path=(base_path)
# Add leading and trailing slashes to base_path
@base_path = "/#{base_path}".gsub(/\/+/, '/')
@base_path = "" if @base_path == "/"
end
def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
URI.encode(url)
end
# Gets API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def api_key_with_prefix(param_name)
if @api_key_prefix[param_name]
"#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
else
@api_key[param_name]
end
end
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
'artikcloud_oauth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
}
end
end
end
| artikcloud/artikcloud-ruby | lib/artikcloud/configuration.rb | Ruby | apache-2.0 | 5,791 |
# Clavaria phycophila Leathers SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycologia 48: 286 (1956)
#### Original name
Clavaria phycophila Leathers
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Clavariaceae/Clavaria/Clavaria phycophila/README.md | Markdown | apache-2.0 | 205 |
# Rosa ×novakii Klášt. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rosa/Rosa novakii/README.md | Markdown | apache-2.0 | 173 |
# Pilea sylvatica Elmer SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Urticaceae/Pilea/Pilea sylvatica/README.md | Markdown | apache-2.0 | 171 |
# Erica angulosa E.G.H.Oliv. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Erica/Erica angulosa/README.md | Markdown | apache-2.0 | 176 |
# Gymnopus subterginus (Halling) Halling SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
in Antonín, Halling & Noordeloos, Mycotaxon 63: 365 (1997)
#### Original name
Collybia subterginum Halling
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Marasmiaceae/Gymnopus/Gymnopus subterginus/README.md | Markdown | apache-2.0 | 250 |
# Echinocereus subinermis subsp. ochoterenae (J.G.Ortega) N.P.Taylor SUBSPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Echinocereus ochoterenae J.G.Ortega
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Echinocereus/Echinocereus subinermis/Echinocereus subinermis ochoterenae/README.md | Markdown | apache-2.0 | 250 |
# Hieracium picroides subsp. trichopicris (Zahn) Zahn SUBSPECIES
#### Status
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium picroides/Hieracium picroides trichopicris/README.md | Markdown | apache-2.0 | 191 |
# Clostridium acidisoli Kuhner et al., 2000 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Bacteria/Firmicutes/Clostridia/Clostridiales/Clostridiaceae/Clostridium/Clostridium acidisoli/README.md | Markdown | apache-2.0 | 199 |
# Phlomis spectabilis Falc. ex Benth. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
A. L. P. P. de Candolle, Prodr. 12:542. 1848
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Phlomis/Phlomis spectabilis/README.md | Markdown | apache-2.0 | 225 |
/*
(C) Copyright 2013-2016 The RISCOSS Project Consortium
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 Alberto Siena
**/
package eu.riscoss.client.entities;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.fusesource.restygwt.client.JsonCallback;
import org.fusesource.restygwt.client.Method;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.CellTable.Resources;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;
import eu.riscoss.client.JsonCallbackWrapper;
import eu.riscoss.client.JsonEntitySummary;
import eu.riscoss.client.JsonRiskDataList;
import eu.riscoss.client.Log;
import eu.riscoss.client.RiscossJsonClient;
import eu.riscoss.client.codec.CodecRASInfo;
import eu.riscoss.client.layers.LayersModule;
import eu.riscoss.client.rdr.EntityDataBox;
import eu.riscoss.client.report.RiskAnalysisReport;
import eu.riscoss.client.riskanalysis.RASPanel;
import eu.riscoss.client.ui.ContextualInfoTable;
import eu.riscoss.client.ui.CustomizableForm;
import eu.riscoss.client.ui.CustomizableForm.CustomField;
import eu.riscoss.client.ui.TreeWidget;
import eu.riscoss.shared.JRASInfo;
import eu.riscoss.shared.RiscossUtil;
public class EntityPropertyPage implements IsWidget {
public class RDCConfDialog {
DialogBox dialog = new DialogBox( false, true );
DockPanel dock = new DockPanel();
RDCConfigurationPage ppg = new RDCConfigurationPage();
String RDCEntity;
EntitiesModule module;
LayersModule lModule;
RDCConfDialog(EntitiesModule module) {
this.module = module;
dock.add( ppg.asWidget(), DockPanel.CENTER );
dialog.setWidget( dock );
}
public void setLModule(LayersModule m) {
this.lModule = m;
}
public Boolean changedData() {
return ppg.changedData();
}
public void setChangedData() {
ppg.setChangedData();
}
public void saveAndRun() {
Boolean b = Window.confirm("Data collectors will be saved before running. Do you want to continue? (If you click 'Cancel', it will not be executed)");
if (b) {
JSONObject json = ppg.getJson();
String str = "";
String sep = "";
for( String key : json.keySet() ) {
if( json.get( key ).isObject().get( "enabled" ).isBoolean().booleanValue() == true ) {
str += sep + key;
sep = ", ";
}
}
saveAndRunRDC(json);
}
}
public void save(String entity) {
RDCEntity = entity;
JSONObject json = ppg.getJson();
String str = "";
String sep = "";
for( String key : json.keySet() ) {
if( json.get( key ).isObject().get( "enabled" ).isBoolean().booleanValue() == true ) {
str += sep + key;
sep = ", ";
}
}
RiscossJsonClient.saveRDCs( json, RDCEntity, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
if (module != null) {
module.reloadData();
}
if (lModule != null) {
lModule.reloadData(RDCEntity);
}
}
});
}
private void saveAndRunRDC(JSONObject json) {
RiscossJsonClient.saveRDCs( json, RDCEntity, new JsonCallback() {
@Override
public void onSuccess(Method method, JSONValue response) {
RiscossJsonClient.runRDCs( EntityPropertyPage.this.entity, new JsonCallback() {
@Override
public void onSuccess(Method method, JSONValue response) {
try {
Log.println( "RDC Collector returned " + response );
JSONObject json = response.isObject();
String msg = json.get( "msg" ).isString().stringValue();
Log.println( "Iterating..." );
for( String rdc : json.keySet() ) {
Log.println( rdc );
JSONObject o = json.get( rdc ).isObject();
if( o == null ) continue;
if( "error".equals( o.get( "result" ).isString().stringValue() ) ) {
msg += " " + rdc + ": " + o.get( "error-message" ).isString().stringValue();
}
Log.println( "Ok" );
}
Log.println( "MSG: " + msg );
Window.alert( msg );
module.ppg.refreshDC();
}
catch( Exception ex ) {
Window.alert( ex.getMessage() );
}
}
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert( exception.getMessage() );
}
});
}
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert( exception.getMessage() );
}} );
}
public void show(String entity) {
ppg.setSelectedEntity( entity );
dialog.show();
}
public DockPanel getDock() {
return dock;
}
public void setSelectedEntity(String entity) {
RDCEntity = entity;
ppg.setSelectedEntity(entity);
}
}
public void setLModule(LayersModule l) {
confDialog.setLModule(l);
}
TabPanel tab = new TabPanel();
SimplePanel summaryPanel = new SimplePanel();
SimplePanel ciPanel = new SimplePanel();
SimplePanel rasPanel = new SimplePanel();
SimplePanel newRasPanel = new SimplePanel();
SimplePanel dataCollectors = new SimplePanel();
SimplePanel rdr = new SimplePanel();
ContextualInfoTable userForm = new ContextualInfoTable();
FlexTable tb = new FlexTable();
String layer;
Anchor rdcAnchor;
private String entity;
RDCConfDialog confDialog;
EntityDataBox entityDataBox;
ArrayList<String> entitiesList;
ArrayList<String> parentList;
ArrayList<String> childrenList;
String[] contextualInfo;
ArrayList<String> extraInfoList;
boolean rasLoaded = false;
EntitiesModule module;
Button backRAS;
Boolean changedData = false;
public EntityPropertyPage(EntitiesModule m) {
this.module = m;
tab.add( summaryPanel, "Properties" );
tab.add( ciPanel, "Custom information" );
tab.add( dataCollectors, "Data Collectors");
tab.add( rdr, "Data Repository");
tab.add( newRasPanel, "Analysis Sessions" );
tab.selectTab( 0 );
tab.setSize( "100%", "100%" );
RiscossJsonClient.listEntities(new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
}
@Override
public void onSuccess(Method method, JSONValue response) {
entitiesList = new ArrayList<>();
for (int i = 0; i < response.isArray().size(); ++i) {
entitiesList.add(response.isArray().get(i).isObject().get("name").isString().stringValue());
}
}
});
}
public void setSelectedTab(int i) {
tab.selectTab(i);
}
@Override
public Widget asWidget() {
return this.tab;
}
public void setSelectedEntity( String entity ) {
if( summaryPanel.getWidget() != null ) {
summaryPanel.getWidget().removeFromParent();
}
if( ciPanel.getWidget() != null ) {
ciPanel.getWidget().removeFromParent();
}
this.entity = entity;
extraInfoList = new ArrayList<>();
if( this.entity == null ) return;
RiscossJsonClient.getEntityData( entity, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert( exception.getMessage() );
}
@Override
public void onSuccess(Method method, JSONValue response) {
loadProperties( response );
}} );
}
public String getLayer() {
return layer;
}
VerticalPanel parents;
VerticalPanel children;
VerticalPanel v;
ListBox parentsListbox = new ListBox();
ListBox childrenListbox = new ListBox();
TextColumn<String> t;
TextColumn<String> t2;
Button deleteParent;
Button deleteChildren;
CellTable<String> parentsTable;
CellTable<String> childrenTable;
FlexTable custom;
JsonEntitySummary info;
ListDataProvider<String> parentDataProvider;
SimplePager pager;
ListDataProvider<String> childrenDataProvider;
SimplePager childrenPager;
VerticalPanel propertiesPanel = new VerticalPanel();
protected void loadProperties( JSONValue response ) {
rasLoaded = false;
info = new JsonEntitySummary( response );
confDialog = new RDCConfDialog(module);
confDialog.setSelectedEntity(entity);
layer = info.getLayer();
parentList = new ArrayList<>();
childrenList = new ArrayList<>();
parentsListbox = new ListBox();
childrenListbox = new ListBox();
for (int i = 0; i < info.getParentList().size(); ++i) {
parentList.add(info.getParentList().get(i).isString().stringValue());
}
for (int i = 0; i < info.getChildrenList().size(); ++i) {
childrenList.add(info.getChildrenList().get(i).isString().stringValue());
}
//Properties Panel
v = new VerticalPanel();
propertiesPanel = new VerticalPanel();
Label layerInfoLabel = new Label("Layer information");
layerInfoLabel.setStyleName("smallTitle");
Label parentInfoLabel = new Label("Hierarchy information");
parentInfoLabel.setStyleName("smallTitle");
loadContextualInfoData();
propertiesPanel.add(layerInfoLabel);
propertiesPanel.add(tb);
propertiesPanel.add(parentInfoLabel);
propertiesPanel.add(v);
v.setWidth("100%");
{
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setWidth("100%");
parents = new VerticalPanel();
children = new VerticalPanel();
HorizontalPanel data = new HorizontalPanel();
Label l = new Label("Parent");
l.setStyleName("bold");
data.add(l);
RiscossJsonClient.getCandidateChildren(entity, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
for (int i = 0; i < response.isArray().size(); ++i) {
childrenListbox.addItem(response.isArray().get(i).isString().stringValue());
}
RiscossJsonClient.getCandidateParents(entity, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
for (int i = 0; i < response.isArray().size(); ++i) {
parentsListbox.addItem(response.isArray().get(i).isString().stringValue());
}
}
});
}
});
/*for (int i = 0; i < entitiesList.size(); ++i) {
if (!entitiesList.get(i).equals(entity)) {
parentsListbox.addItem(entitiesList.get(i));
childrenListbox.addItem(entitiesList.get(i));
}
}*/
data.add(parentsListbox);
Button b = new Button("Add parent", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String newParent = parentsListbox.getItemText(parentsListbox.getSelectedIndex());
if (parentList.contains(newParent)) {
Window.alert("The selected entity is already a parent");
return;
}
if (childrenList.contains(newParent)) {
Window.alert("The selected entity is already a children. An entity can not be parent and child of the same entity.");
return;
}
parentList.add(newParent);
parentsTable.setRowData(0, parentList);
changedData = true;
}
});
b.setStyleName("Button");
data.add(b);
data.setStyleName("marginTopBottom");
parents.add(data);
parentsTable = new CellTable<String>(15, (Resources) GWT.create(TableResources.class));
parentsTable.setWidth("100%");
t = new TextColumn<String>() {
@Override
public String getValue(String arg0) {
return arg0;
}
};
deleteParent = new Button("Delete parent");
deleteParent.setStyleName("deleteButton");
final SingleSelectionModel<String> selectionModel = new SingleSelectionModel<String>();
parentsTable.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent arg0) {
parents.remove(deleteParent);
deleteParent.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
parentList.remove(selectionModel.getSelectedObject());
parents.remove(parentsTable);
parents.remove(pager);
parentsTable = new CellTable<String>(15, (Resources) GWT.create(TableResources.class));
parentsTable.setWidth("100%");
parentsTable.setSelectionModel(selectionModel);
t = new TextColumn<String>() {
@Override
public String getValue(String arg0) {
return arg0;
}
};
parentsTable.addColumn(t, "Parents");
if (parentList.size() > 0) parentsTable.setRowData(0, parentList);
else {
parentList.add("");
parentsTable.setRowData(0, parentList);
parentList.remove(0);
}
parentsTable.setStyleName("table");
parentDataProvider = new ListDataProvider<String>();
parentDataProvider.addDataDisplay( parentsTable );
for( int i = 0; i < parentList.size(); i++ ) {
parentDataProvider.getList().add( parentList.get(i) );
}
pager = new SimplePager();
pager.setDisplay( parentsTable );
parents.add(parentsTable);
parents.add(pager);
parents.remove(deleteParent);
changedData = true;
}
});
parents.add(deleteParent);
}
});
parentsTable.addColumn(t, "Parents");
if (parentList.size() > 0) parentsTable.setRowData(0, parentList);
else {
parentList.add("");
parentsTable.setRowData(0, parentList);
parentList.remove(0);
}
parentsTable.setStyleName("table");
parentDataProvider = new ListDataProvider<String>();
parentDataProvider.addDataDisplay( parentsTable );
for( int i = 0; i < parentList.size(); i++ ) {
parentDataProvider.getList().add( parentList.get(i) );
}
pager = new SimplePager();
pager.setDisplay( parentsTable );
parents.add(parentsTable);
parents.add(pager);
HorizontalPanel data2 = new HorizontalPanel();
Label l2 = new Label("Children");
l2.setStyleName("bold");
data2.add(l2);
data2.add(childrenListbox);
Button b2 = new Button("Add children", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String newChildren = childrenListbox.getItemText(childrenListbox.getSelectedIndex());
if (childrenList.contains(newChildren)) {
Window.alert("The selected entity is already a children");
return;
}
if (parentList.contains(newChildren)) {
Window.alert("The selected entity is already a children. An entity can not be parent and child of the same entity.");
return;
}
childrenList.add(newChildren);
childrenTable.setRowData(0, childrenList);
changedData = true;
}
});
b2.setStyleName("Button");
data2.add(b2);
data2.setStyleName("marginTopBottom");
children.add(data2);
childrenTable = new CellTable<String>(15, (Resources) GWT.create(TableResources.class));
childrenTable.setWidth("100%");
t2 = new TextColumn<String>() {
@Override
public String getValue(String arg0) {
return arg0;
}
};
deleteChildren = new Button("Delete children");
deleteChildren.setStyleName("deleteButton");
final SingleSelectionModel<String> selectionModel2 = new SingleSelectionModel<String>();
childrenTable.setSelectionModel(selectionModel2);
selectionModel2.addSelectionChangeHandler(new Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent arg0) {
children.remove(deleteChildren);
deleteChildren.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
childrenList.remove(selectionModel2.getSelectedObject());
children.remove(childrenTable);
children.remove(childrenPager);
childrenTable = new CellTable<String>(15, (Resources) GWT.create(TableResources.class));
childrenTable.setWidth("100%");
childrenTable.setSelectionModel(selectionModel2);
t2 = new TextColumn<String>() {
@Override
public String getValue(String arg0) {
return arg0;
}
};
childrenTable.addColumn(t, "Children");
if (childrenList.size() > 0) childrenTable.setRowData(0, childrenList);
else {
childrenList.add("");
childrenTable.setRowData(0, childrenList);
childrenList.remove(0);
}
childrenTable.setStyleName("table");
childrenDataProvider = new ListDataProvider<String>();
childrenDataProvider.addDataDisplay( childrenTable );
for( int i = 0; i < childrenList.size(); i++ ) {
childrenDataProvider.getList().add( childrenList.get(i) );
}
childrenPager = new SimplePager();
childrenPager.setDisplay( childrenTable );
children.add(childrenTable);
children.add(childrenPager);
children.remove(deleteChildren);
changedData = true;
}
});
children.add(deleteChildren);
}
});
childrenTable.addColumn(t, "Children");
if (childrenList.size() > 0) childrenTable.setRowData(0, childrenList);
else {
childrenList.add("");
childrenTable.setRowData(0, childrenList);
childrenList.remove(0);
}
childrenTable.setStyleName("table");
childrenDataProvider = new ListDataProvider<String>();
childrenDataProvider.addDataDisplay( childrenTable );
for( int i = 0; i < childrenList.size(); i++ ) {
childrenDataProvider.getList().add( childrenList.get(i) );
}
childrenPager = new SimplePager();
childrenPager.setDisplay( childrenTable );
children.add(childrenTable);
children.add(childrenPager);
hPanel.setWidth("100%");
hPanel.add(parents);
HorizontalPanel h = new HorizontalPanel();
h.setWidth("100px");
hPanel.add(h);
hPanel.add(children);
v.add(hPanel);
}
entityDataBox = new EntityDataBox();
entityDataBox.setSelectedEntity(entity);
rdr.setWidget(entityDataBox);
loadRASWidget();
}
public void runDC() {
confDialog.saveAndRun();
}
public void refreshDC() {
entityDataBox = new EntityDataBox();
entityDataBox.setSelectedEntity(entity);
rdr.setWidget(entityDataBox);
}
List<String> types;
TextBox newID;
TextBox newValue;
private void loadContextualInfoData() {
tb = new FlexTable();
userForm = new ContextualInfoTable();
custom = new FlexTable();
types = new ArrayList<>();
int row = 0;
int rowC = 0;
for( int i = 0; i < info.getUserData().size(); i++ ) {
JsonRiskDataList.RiskDataItem item = info.getUserData().get( i );
if (item.getDataType().equals("CUSTOM")) {
userForm.addField(item.getId(), item.getValue());
}
else {
String val = item.getValue();
contextualInfo = val.split(";");
String extrainfo = "";
for (int k = 1; k < contextualInfo.length; ++k) {
extrainfo += ";" + contextualInfo[k];
}
extraInfoList.add(extrainfo);
tb.insertRow(row);
tb.insertCell(row, 0);
tb.insertCell(row, 1);
Label id = new Label(item.getId());
id.setStyleName("bold");
tb.setWidget(row, 0, id);
if (item.getDataType().equals("Integer")) {
TextBox t = new TextBox();
t.setText(contextualInfo[0]);
t.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
changedData = true;
}
});
tb.setWidget(row, 1, t);
types.add("Integer");
}
else if (item.getDataType().equals("Boolean")) {
CheckBox c = new CheckBox();
if (Integer.parseInt(contextualInfo[0]) == 1) c.setChecked(true);
c.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(
ValueChangeEvent<Boolean> event) {
changedData = true;
}
});
tb.setWidget(row, 1, c);
types.add("Boolean");
}
else if (item.getDataType().equals("Date")) {
DateTimeFormat dateFormat = DateTimeFormat.getLongDateFormat();
DateBox dateBox = new DateBox();
dateBox.setFormat(new DateBox.DefaultFormat(dateFormat));
dateBox.getDatePicker().setYearArrowsVisible(true);
dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
@Override
public void onValueChange(ValueChangeEvent<Date> event) {
changedData = true;
}
});
Grid g = new Grid(1,7);
g.setWidget(0, 0, dateBox);
String inf[] = contextualInfo[0].split(":");
TextBox t = new TextBox();
TextBox t2 = new TextBox();
TextBox t3 = new TextBox();
if (inf.length > 1) {
String date[] = inf[0].split("-");
String time[] = inf[1].split("-");
int year = Integer.parseInt(date[0]) - 1900;
int month = Integer.parseInt(date[1]) - 1;
if (month == 0) {month = 12;--year;}
int day = Integer.parseInt(date[2]);
Date d = new Date(year, month, day);
dateBox.setValue(d);
t.setText(String.valueOf(time[0]));
t2.setText(String.valueOf(time[1]));
t3.setText(String.valueOf(time[2]));
}
t.setWidth("30px");
t.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
changedData = true;
}
});
g.setWidget(0, 1, t);
g.setWidget(0, 2, new Label("hh"));
t2.setWidth("30px");
t2.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
changedData = true;
}
});
g.setWidget(0, 3, t2);
g.setWidget(0, 4, new Label("mm"));
t3.setWidth("30px");
t3.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
changedData = true;
}
});
g.setWidget(0, 5, t3);
g.setWidget(0, 6, new Label("ss"));
tb.setWidget(row, 1, g);
types.add("Date");
}
else if (item.getDataType().equals("List")) {
ListBox lb = new ListBox();
for (int k = 1; k < contextualInfo.length; ++k) {
lb.addItem(contextualInfo[k]);
}
lb.setSelectedIndex(Integer.parseInt(contextualInfo[0]));
lb.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
changedData = true;
}
});
tb.setWidget(row, 1, lb);
types.add("List");
}
else if (item.getDataType().equals("Text")) {
TextBox t = new TextBox();
t.setText(contextualInfo[0]);
t.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
changedData = true;
}
});
tb.setWidget(row, 1, t);
types.add("Text");
}
++row;
}
}
HorizontalPanel newCIElement = new HorizontalPanel();
newCIElement.setStyleName("layerData");
Label newIDL = new Label("ID");
newIDL.setStyleName("bold");
newID = new TextBox();
Label newValueL = new Label("Value");
newValueL.setStyleName("bold");
newValue = new TextBox();
newCIElement.add(newIDL);
newCIElement.add(newID);
newCIElement.add(newValueL);
newCIElement.add(newValue);
Button newCustomInfo = new Button("New custom information");
newCustomInfo.setStyleName("button");
newCustomInfo.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean b = userForm.newField(newID.getText(), newValue.getText());
if (b) {
newID.setText("");
newValue.setText("");
}
}
});
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(newCIElement);
vPanel.add(newCustomInfo);
vPanel.add(userForm.getWidget());
summaryPanel.setWidget( propertiesPanel );
dataCollectors.setWidget(confDialog.getDock());
ciPanel.setWidget( vPanel );
}
String newN;
String newL;
public void saveEntityData(String newName, String newLayer) {
newN = newName;
newL = newLayer;
RiscossJsonClient.listRiskAnalysisSessions(entity, "", new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
if (!newL.equals(layer) && (parentList.size() > 0 || childrenList.size() > 0)) {
Window.alert("Entities with parents or children cannot modify the layer");
return;
}
if( response == null ) return;
if( response.isObject() == null ) return;
response = response.isObject().get( "list" );
if (!newL.equals(layer) && response.isArray().size() > 0) {
Window.alert("Entities with associated risk analysis sessions cannot modify the layer");
return;
}
if (!newL.equals(layer) && response.isArray().size() == 0) {
RiscossJsonClient.editLayer(entity, newL, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
if (!newN.equals(entity)) {
renameAndSave(newN);
} else {
saveEntity();
}
}
});
}
else if (newL.equals(layer)) {
if (!newN.equals(entity)) {
renameAndSave(newN);
} else {
saveEntity();
}
}
}
});
}
private void renameAndSave(String newName) {
newN = newName;
RiscossJsonClient.listEntities(new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
if (newN == null || newN.equals("") ) {
return;
}
//String s = RiscossUtil.sanitize(txt.getText().trim());//attention:name sanitation is not directly notified to the user
if (!RiscossUtil.sanitize(newN).equals(newN)){
//info: firefox has some problem with this window, and fires assertion errors in dev mode
Window.alert("Entity name contains prohibited characters (##,@,\") \nPlease re-enter name");
return;
}
for(int i=0; i<response.isArray().size(); i++){
JSONObject o = (JSONObject)response.isArray().get(i);
if (newN.equals(o.get( "name" ).isString().stringValue())) {
Window.alert("Entity name already in use.\nPlease re-enter name.");
return;
}
}
RiscossJsonClient.renameEntity(entity, newN, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
entity = newN;
saveEntity();
}
});
}
});
}
private void saveEntity() {
saveContextualInfo();
changedData = false;
confDialog.setChangedData();
}
private void saveDataCollectors() {
confDialog.setLModule(l);
confDialog.save(entity);
}
private void saveParentyInfo() {
RiscossJsonClient.setChildren(entity, childrenList, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
RiscossJsonClient.setParents(entity, parentList, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
saveDataCollectors();
}
});
}
});
}
private void saveContextualInfo() {
userForm.save(entity);
for (int i = 0; i < tb.getRowCount(); ++i) {
JSONObject o = new JSONObject();
o.put( "id", new JSONString( ((Label)tb.getWidget(i, 0)).getText() ) );
o.put( "target", new JSONString( EntityPropertyPage.this.entity ) );
String datatype = types.get(i);
String value = "";
if (datatype.equals("Integer")) {
if (!((TextBox) tb.getWidget(i, 1)).getText().equals("")) {
int cValue = Integer.parseInt(((TextBox) tb.getWidget(i, 1)).getText());
String[] extra = extraInfoList.get(i).split(";");
int min = Integer.parseInt(extra[1]);
int max = Integer.parseInt(extra[2]);
if (cValue < min || cValue > max) {
Window.alert(((Label)tb.getWidget(i, 0)).getText() + " value must be within limits (min = " + min + ", max = " + max + ")");
return;
}
}
value += ((TextBox) tb.getWidget(i, 1)).getText();
value += extraInfoList.get(i);
}
else if (datatype.equals("Boolean")) {
if (((CheckBox) tb.getWidget(i, 1)).isChecked()) value += "1";
else value += "0";
}
else if (datatype.equals("Date")) {
if (!((TextBox) ((Grid) tb.getWidget(i, 1)).getWidget(0, 1)).getText().equals("")) {
int hour = Integer.parseInt(((TextBox) ((Grid) tb.getWidget(i, 1)).getWidget(0, 1)).getText());
int minute = Integer.parseInt(((TextBox) ((Grid) tb.getWidget(i, 1)).getWidget(0, 3)).getText());
int second = Integer.parseInt(((TextBox) ((Grid) tb.getWidget(i, 1)).getWidget(0, 5)).getText());
Date date = ((DateBox) ((Grid) tb.getWidget(i,1)).getWidget(0, 0)).getValue();
date.setHours(hour);
date.setMinutes(minute);
date.setSeconds(second);
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd:HH-mm-ss");
value += fmt.format(date);
}
}
else if (datatype.equals("List")){
value += ((ListBox) tb.getWidget(i, 1)).getSelectedIndex();
value += extraInfoList.get(i);
}
else if (datatype.equals("Text")) {
value += ((TextBox) tb.getWidget(i, 1)).getText();
}
o.put( "value", new JSONString( value ) );
o.put( "datatype", new JSONString ( datatype ) );
o.put( "type", new JSONString( "custom" ) );
o.put( "origin", new JSONString( "user" ) );
JSONArray array = new JSONArray();
array.set( 0, o );
RiscossJsonClient.postRiskData( array, new JsonCallback() {
@Override
public void onFailure( Method method, Throwable exception ) {
Window.alert( exception.getMessage() );
}
@Override
public void onSuccess( Method method, JSONValue response ) {
}
} );
if (i == tb.getRowCount()-1) saveParentyInfo();
}
if (tb.getRowCount() == 0) saveParentyInfo();
}
TreeWidget riskTree;
List<String> models;
String nextRisk;
String risksses;
List<JRASInfo> list = new ArrayList<>();
int count = 0;
VerticalPanel panel;
private void loadRASWidget() {
RiscossJsonClient.listRCs(entity, new JsonCallback() {
@Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
@Override
public void onSuccess(Method method, JSONValue response) {
models = new ArrayList<String>();
for( int i = 0; i < response.isArray().size(); i++ ) {
JSONObject o = (JSONObject)response.isArray().get( i );
models.add( o.get( "name" ).isString().stringValue() );
}
riskTree = new TreeWidget();
for (int i = 0; i < models.size(); ++i) {
nextRisk = models.get(i);
RiscossJsonClient.listRiskAnalysisSessions( entity, models.get(i), new JsonCallback() {
String risk = nextRisk;
public void onSuccess(Method method, JSONValue response) {
if( response == null ) return;
if( response.isObject() == null ) return;
response = response.isObject().get( "list" );
List<JRASInfo> riskSessions = new ArrayList<>();
CodecRASInfo codec = GWT.create( CodecRASInfo.class );
if( response.isArray() != null ) {
for( int i = 0; i < response.isArray().size(); i++ ) {
JRASInfo info = codec.decode( response.isArray().get( i ) );
riskSessions.add( info );
}
}
Label a = new Label("> " + risk);
a.setWidth("100%");
a.setStyleName("bold");
HorizontalPanel cPanel = new HorizontalPanel();
cPanel.setStyleName("tree");
cPanel.setWidth("100%");
cPanel.add(a);
TreeWidget c = new TreeWidget(cPanel);
riskTree.addChild(c);
for (int i = 0; i < riskSessions.size(); ++i) {
risksses = riskSessions.get(i).getName();
Anchor b = new Anchor(risksses);
b.setWidth("100%");
b.setStyleName("font");
b.addClickHandler(new ClickHandler() {
String name = risksses;
int k = count;
@Override
public void onClick(ClickEvent event) {
setSelectedRiskSes(name, k);
}
});
list.add(riskSessions.get(i));
++count;
HorizontalPanel dPanel = new HorizontalPanel();
dPanel.setStyleName("tree");
dPanel.setWidth("100%");
dPanel.add(b);
TreeWidget d = new TreeWidget(dPanel);
c.addChild(d);
}
}
public void onFailure(Method method, Throwable exception) {
Window.alert( exception.getMessage() );
}
});
}
panel = new VerticalPanel();
panel.add(riskTree);
newRasPanel.setWidget(panel);
}
});
}
LayersModule l;
public void setLayerModule(LayersModule l) {
this.l = l;
}
private void setSelectedRiskSes(String name, int k) {
if (l != null) l.setSelectedRiskSes(list.get(k).getId(), this);
else module.setSelectedRiskSes(list.get(k).getId(), this);
}
public void back(Boolean entityB) {
if (entityB) module.back();
else l.back();
}
public void delete(String ras, Boolean entityB) {
if (entityB) module.deleteRiskSes(ras);
else l.deleteRiskSes(ras);
}
/*protected void loadRAS( JSONValue response ) {
if( rasPanel.getWidget() != null ) {
rasPanel.getWidget().removeFromParent();
}
if( response == null ) {
rasLoaded = true;
return;
}
try {
RiskAnalysisReport report = new RiskAnalysisReport();
report.showResults(
response.isObject().get( "results" ).isArray(),
response.isObject().get( "argumentation" ) );
rasPanel.setWidget( report.asWidget() );
rasLoaded = true;
}
catch( Exception ex ) {
Window.alert( ex.getMessage() );
}
}*/
protected void onChildEntitySelected( List<String> entities ) {
RiscossJsonClient.setChildren( entity, entities, new JsonCallback() {
@Override
public void onFailure( Method method, Throwable exception ) {
Window.alert( exception.getMessage() );
}
@Override
public void onSuccess( Method method, JSONValue response ) {
}} );
}
protected void onParentEntitySelected( List<String> parents ) {
RiscossJsonClient.setParents( entity, parents, new JsonCallback() {
@Override
public void onFailure( Method method, Throwable exception ) {
Window.alert( exception.getMessage() );
}
@Override
public void onSuccess( Method method, JSONValue response ) {
}} );
}
public boolean hasParents() {
if (parentList.size() > 0) return true;
else return false;
}
} | RISCOSS/riscoss-corporate | riscoss-webapp/src/main/java/eu/riscoss/client/entities/EntityPropertyPage.java | Java | apache-2.0 | 37,647 |
/**
* package for Professions test tasks.
* @author avlodin
* @since 17.04.17
* @version 1.0
*/
package ru.job4j.professions; | DartSicon/avolodin | chapter_002/src/test/java/ru/job4j/professions/package-info.java | Java | apache-2.0 | 131 |
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2014 wcm.io
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.wcm.caravan.commons.metrics.rx;
import java.util.concurrent.atomic.AtomicBoolean;
import org.osgi.annotation.versioning.ProviderType;
import rx.Observable.Operator;
import rx.Subscriber;
import com.codahale.metrics.Counter;
/**
* Operator counting hits and misses. If no element passes the operator, the {@code missesCounter} gets increased. For
* every passed element the {@code hitsCounter} gets increased.
* @param <R> Items type
*/
@ProviderType
public final class HitsAndMissesCountingMetricsOperator<R> implements Operator<R, R> {
private final Counter hitsCounter;
private final Counter missesCounter;
/**
* @param hitsCounter Counter for hits
* @param missesCounter Counter for misses
*/
public HitsAndMissesCountingMetricsOperator(Counter hitsCounter, Counter missesCounter) {
this.hitsCounter = hitsCounter;
this.missesCounter = missesCounter;
}
@Override
public Subscriber<? super R> call(Subscriber<? super R> subscriber) {
final AtomicBoolean hit = new AtomicBoolean();
return new Subscriber<R>() {
@Override
public void onCompleted() {
(hit.get() ? hitsCounter : missesCounter).inc();
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(R next) {
hit.set(true);
subscriber.onNext(next);
}
};
}
}
| wcm-io-caravan/caravan-commons | metrics/src/main/java/io/wcm/caravan/commons/metrics/rx/HitsAndMissesCountingMetricsOperator.java | Java | apache-2.0 | 2,081 |
//C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either Version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
//C- Lizardtech Software. Lizardtech Software has authorized us to
//C- replace the original DjVu(r) Reference Library notice by the following
//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, either Version 2 of the license,
//C- | or (at your option) any later version. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation "ddjvuapi.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <locale.h>
#ifdef HAVE_NAMESPACES
namespace DJVU {
struct ddjvu_context_s;
struct ddjvu_job_s;
struct ddjvu_document_s;
struct ddjvu_page_s;
struct ddjvu_format_s;
struct ddjvu_message_p;
struct ddjvu_thumbnail_p;
struct ddjvu_runnablejob_s;
struct ddjvu_printjob_s;
struct ddjvu_savejob_s;
}
using namespace DJVU;
# define DJVUNS DJVU::
#else
# define DJVUNS /**/
#endif
#include "GException.h"
#include "GSmartPointer.h"
#include "GThreads.h"
#include "GContainer.h"
#include "ByteStream.h"
#include "IFFByteStream.h"
#include "BSByteStream.h"
#include "GString.h"
#include "GBitmap.h"
#include "GPixmap.h"
#include "GScaler.h"
#include "DjVuPort.h"
#include "DataPool.h"
#include "DjVuInfo.h"
#include "IW44Image.h"
#include "DjVuImage.h"
#include "DjVuFileCache.h"
#include "DjVuDocument.h"
#include "DjVuDumpHelper.h"
#include "DjVuMessageLite.h"
#include "DjVuMessage.h"
#include "DjVmNav.h"
#include "DjVuText.h"
#include "DjVuAnno.h"
#include "DjVuToPS.h"
#include "DjVmDir.h"
#include "DjVmDir0.h"
#include "DjVuNavDir.h"
#include "DjVmDoc.h"
#include "miniexp.h"
#include "ddjvuapi.h"
// ----------------------------------------
// Private structures
struct DJVUNS ddjvu_message_p : public GPEnabled
{
GNativeString tmp1;
GNativeString tmp2;
ddjvu_message_t p;
ddjvu_message_p() { memset(&p, 0, sizeof(p)); }
};
struct DJVUNS ddjvu_thumbnail_p : public GPEnabled
{
ddjvu_document_t *document;
int pagenum;
GTArray<char> data;
GP<DataPool> pool;
static void callback(void *);
};
// ----------------------------------------
// Context, Jobs, Document, Pages
struct DJVUNS ddjvu_context_s : public GPEnabled
{
GMonitor monitor;
GP<DjVuFileCache> cache;
GPList<ddjvu_message_p> mlist;
GP<ddjvu_message_p> mpeeked;
int uniqueid;
ddjvu_message_callback_t callbackfun;
void *callbackarg;
};
struct DJVUNS ddjvu_job_s : public DjVuPort
{
GMonitor monitor;
void *userdata;
GP<ddjvu_context_s> myctx;
GP<ddjvu_document_s> mydoc;
bool released;
ddjvu_job_s();
// virtual port functions:
virtual bool inherits(const GUTF8String&);
virtual bool notify_error(const DjVuPort*, const GUTF8String&);
virtual bool notify_status(const DjVuPort*, const GUTF8String&);
// default implementation of virtual job functions:
virtual ddjvu_status_t status() {return DDJVU_JOB_NOTSTARTED;}
virtual void release() {}
virtual void stop() {}
};
struct DJVUNS ddjvu_document_s : public ddjvu_job_s
{
GP<DjVuDocument> doc;
GPMap<int,DataPool> streams;
GMap<GUTF8String, int> names;
GPMap<int,ddjvu_thumbnail_p> thumbnails;
int streamid;
bool fileflag;
bool urlflag;
bool docinfoflag;
bool pageinfoflag;
minivar_t protect;
// virtual job functions:
virtual ddjvu_status_t status();
virtual void release();
// virtual port functions:
virtual bool inherits(const GUTF8String&);
virtual bool notify_error(const DjVuPort*, const GUTF8String&);
virtual bool notify_status(const DjVuPort*, const GUTF8String&);
virtual void notify_doc_flags_changed(const DjVuDocument*, long, long);
virtual GP<DataPool> request_data(const DjVuPort*, const GURL&);
static void callback(void *);
bool want_pageinfo(void);
};
struct DJVUNS ddjvu_page_s : public ddjvu_job_s
{
GP<DjVuImage> img;
ddjvu_job_t *job;
bool pageinfoflag; // was the first m_pageinfo sent?
bool pagedoneflag; // was the final m_pageinfo sent?
// virtual job functions:
virtual ddjvu_status_t status();
virtual void release();
// virtual port functions:
virtual bool inherits(const GUTF8String&);
virtual bool notify_error(const DjVuPort*, const GUTF8String&);
virtual bool notify_status(const DjVuPort*, const GUTF8String&);
virtual void notify_file_flags_changed(const DjVuFile*, long, long);
virtual void notify_relayout(const class DjVuImage*);
virtual void notify_redisplay(const class DjVuImage*);
virtual void notify_chunk_done(const DjVuPort*, const GUTF8String &);
void sendmessages();
};
// ----------------------------------------
// Helpers
// Hack to increment counter
static void
ref(GPEnabled *p)
{
GPBase n(p);
char *gn = (char*)&n;
*(GPEnabled**)gn = 0;
n.assign(0);
}
// Hack to decrement counter
static void
unref(GPEnabled *p)
{
GPBase n;
char *gn = (char*)&n;
*(GPEnabled**)gn = p;
n.assign(0);
}
// Allocate strings
static char *
xstr(const char *s)
{
int l = strlen(s);
char *p = (char*)malloc(l + 1);
if (p)
{
strcpy(p, s);
p[l] = 0;
}
return p;
}
// Allocate strings
static char *
xstr(const GNativeString &n)
{
return xstr( (const char*) n );
}
// Allocate strings
static char *
xstr(const GUTF8String &u)
{
GNativeString n(u);
return xstr( n );
}
// Fill a message head
static ddjvu_message_any_t
xhead(ddjvu_message_tag_t tag,
ddjvu_context_t *context)
{
ddjvu_message_any_t any;
any.tag = tag;
any.context = context;
any.document = 0;
any.page = 0;
any.job = 0;
return any;
}
static ddjvu_message_any_t
xhead(ddjvu_message_tag_t tag,
ddjvu_job_t *job)
{
ddjvu_message_any_t any;
any.tag = tag;
any.context = job->myctx;
any.document = job->mydoc;
any.page = 0;
any.job = job;
return any;
}
static ddjvu_message_any_t
xhead(ddjvu_message_tag_t tag,
ddjvu_document_t *document)
{
ddjvu_message_any_t any;
any.tag = tag;
any.context = document->myctx;
any.document = document;
any.page = 0;
any.job = document;
return any;
}
static ddjvu_message_any_t
xhead(ddjvu_message_tag_t tag,
ddjvu_page_t *page)
{
ddjvu_message_any_t any;
any.tag = tag;
any.context = page->myctx;
any.document = page->mydoc;
any.page = page;
any.job = page->job;
return any;
}
// ----------------------------------------
// Version
const char*
ddjvu_get_version_string(void)
{
#ifdef DJVULIBRE_VERSION
return "DjVuLibre-" DJVULIBRE_VERSION;
#else
return "DjVuLibre";
#endif
}
int
ddjvu_code_get_version(void)
{
return DJVUVERSION;
}
// ----------------------------------------
// Context
ddjvu_context_t *
ddjvu_context_create(const char *programname)
{
ddjvu_context_t *ctx = 0;
G_TRY
{
#ifdef LC_ALL
setlocale(LC_ALL,"");
# ifdef LC_NUMERIC
setlocale(LC_NUMERIC, "C");
# endif
#endif
if (programname)
djvu_programname(programname);
DjVuMessage::use_language();
DjVuMessageLite::create();
ctx = new ddjvu_context_s;
ref(ctx);
ctx->uniqueid = 0;
ctx->callbackfun = 0;
ctx->callbackarg = 0;
ctx->cache = DjVuFileCache::create();
}
G_CATCH_ALL
{
if (ctx)
unref(ctx);
ctx = 0;
}
G_ENDCATCH;
return ctx;
}
void
ddjvu_context_release(ddjvu_context_t *ctx)
{
G_TRY
{
if (ctx)
unref(ctx);
}
G_CATCH_ALL
{
}
G_ENDCATCH;
}
// ----------------------------------------
// Message helpers
// post a new message
static void
msg_push(const ddjvu_message_any_t &head,
GP<ddjvu_message_p> msg = 0)
{
ddjvu_context_t *ctx = head.context;
if (! msg)
msg = new ddjvu_message_p;
msg->p.m_any = head;
GMonitorLock lock(&ctx->monitor);
if ((head.document && head.document->released) ||
(head.page && head.page->released) ||
(head.job && head.job->released) )
return;
if (ctx->callbackfun)
(*ctx->callbackfun)(ctx, ctx->callbackarg);
ctx->mlist.append(msg);
ctx->monitor.broadcast();
}
static void
msg_push_nothrow(const ddjvu_message_any_t &head,
GP<ddjvu_message_p> msg = 0)
{
G_TRY
{
msg_push(head, msg);
}
G_CATCH_ALL
{
}
G_ENDCATCH;
}
// prepare error message from string
static GP<ddjvu_message_p>
msg_prep_error(GUTF8String message,
const char *function=0,
const char *filename=0,
int lineno=0)
{
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->p.m_error.message = 0;
p->p.m_error.function = function;
p->p.m_error.filename = filename;
p->p.m_error.lineno = lineno;
G_TRY
{
p->tmp1 = DjVuMessageLite::LookUpUTF8(message);
p->p.m_error.message = (const char*)(p->tmp1);
}
G_CATCH_ALL
{
}
G_ENDCATCH;
return p;
}
// prepare error message from exception
static GP<ddjvu_message_p>
msg_prep_error(const GException &ex,
const char *function=0,
const char *filename=0,
int lineno=0)
{
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->p.m_error.message = 0;
p->p.m_error.function = function;
p->p.m_error.filename = filename;
p->p.m_error.lineno = lineno;
G_TRY
{
p->tmp1 = DjVuMessageLite::LookUpUTF8(ex.get_cause());
p->p.m_error.message = (const char*)(p->tmp1);
p->p.m_error.function = ex.get_function();
p->p.m_error.filename = ex.get_file();
p->p.m_error.lineno = ex.get_line();
}
G_CATCH_ALL
{
}
G_ENDCATCH;
return p;
}
// prepare status message
static GP<ddjvu_message_p>
msg_prep_info(GUTF8String message)
{
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->tmp1 = DjVuMessageLite::LookUpUTF8(message); // i18n nonsense!
p->p.m_info.message = (const char*)(p->tmp1);
return p;
}
// ----------------------------------------
#ifdef __GNUG__
# define ERROR1(x, m) \
msg_push_nothrow(xhead(DDJVU_ERROR,x),\
msg_prep_error(m,__func__,__FILE__,__LINE__))
#else
# define ERROR1(x, m) \
msg_push_nothrow(xhead(DDJVU_ERROR,x),\
msg_prep_error(m,0,__FILE__,__LINE__))
#endif
// ----------------------------------------
// Cache
void
ddjvu_cache_set_size(ddjvu_context_t *ctx,
unsigned long cachesize)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
if (ctx->cache && cachesize>0)
ctx->cache->set_max_size(cachesize);
}
G_CATCH(ex)
{
ERROR1(ctx, ex);
}
G_ENDCATCH;
}
DDJVUAPI unsigned long
ddjvu_cache_get_size(ddjvu_context_t *ctx)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
if (ctx->cache)
return ctx->cache->get_max_size();
}
G_CATCH(ex)
{
ERROR1(ctx, ex);
}
G_ENDCATCH;
return 0;
}
void
ddjvu_cache_clear(ddjvu_context_t *ctx)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
if (ctx->cache)
{
ctx->cache->clear();
return;
}
}
G_CATCH(ex)
{
ERROR1(ctx, ex);
}
G_ENDCATCH;
}
// ----------------------------------------
// Jobs
ddjvu_job_s::ddjvu_job_s()
: userdata(0), released(false)
{
}
bool
ddjvu_job_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_job_s")
|| DjVuPort::inherits(classname);
}
bool
ddjvu_job_s::notify_error(const DjVuPort *, const GUTF8String &m)
{
msg_push(xhead(DDJVU_ERROR, this), msg_prep_error(m));
return true;
}
bool
ddjvu_job_s::notify_status(const DjVuPort *p, const GUTF8String &m)
{
msg_push(xhead(DDJVU_INFO, this), msg_prep_info(m));
return true;
}
void
ddjvu_job_release(ddjvu_job_t *job)
{
G_TRY
{
if (!job)
return;
job->release();
job->userdata = 0;
job->released = true;
// clean all messages
ddjvu_context_t *ctx = job->myctx;
if (ctx)
{
GMonitorLock lock(&ctx->monitor);
GPosition p = ctx->mlist;
while (p)
{
GPosition s = p; ++p;
if (ctx->mlist[s]->p.m_any.job == job ||
ctx->mlist[s]->p.m_any.document == job ||
ctx->mlist[s]->p.m_any.page == job )
ctx->mlist.del(s);
}
// cleanup pointers in current message as well.
if (ctx->mpeeked)
{
ddjvu_message_t *m = &ctx->mpeeked->p;
if (m->m_any.job == job)
m->m_any.job = 0;
if (m->m_any.document == job)
m->m_any.document = 0;
if (m->m_any.page == job)
m->m_any.page = 0;
}
}
// decrement reference counter
unref(job);
}
G_CATCH_ALL
{
}
G_ENDCATCH;
}
ddjvu_status_t
ddjvu_job_status(ddjvu_job_t *job)
{
G_TRY
{
if (! job)
return DDJVU_JOB_NOTSTARTED;
return job->status();
}
G_CATCH(ex)
{
ERROR1(job, ex);
}
G_ENDCATCH;
return DDJVU_JOB_FAILED;
}
void
ddjvu_job_stop(ddjvu_job_t *job)
{
G_TRY
{
if (job)
job->stop();
}
G_CATCH(ex)
{
ERROR1(job, ex);
}
G_ENDCATCH;
}
void
ddjvu_job_set_user_data(ddjvu_job_t *job, void *userdata)
{
if (job)
job->userdata = userdata;
}
void *
ddjvu_job_get_user_data(ddjvu_job_t *job)
{
if (job)
return job->userdata;
return 0;
}
// ----------------------------------------
// Message queue
ddjvu_message_t *
ddjvu_message_peek(ddjvu_context_t *ctx)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
if (ctx->mpeeked)
return &ctx->mpeeked->p;
if (! ctx->mlist.size())
ctx->monitor.wait(0);
GPosition p = ctx->mlist;
if (! p)
return 0;
ctx->mpeeked = ctx->mlist[p];
ctx->mlist.del(p);
return &ctx->mpeeked->p;
}
G_CATCH_ALL
{
}
G_ENDCATCH;
return 0;
}
ddjvu_message_t *
ddjvu_message_wait(ddjvu_context_t *ctx)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
if (ctx->mpeeked)
return &ctx->mpeeked->p;
while (! ctx->mlist.size())
ctx->monitor.wait();
GPosition p = ctx->mlist;
if (! p)
return 0;
ctx->mpeeked = ctx->mlist[p];
ctx->mlist.del(p);
return &ctx->mpeeked->p;
}
G_CATCH_ALL
{
}
G_ENDCATCH;
return 0;
}
void
ddjvu_message_pop(ddjvu_context_t *ctx)
{
G_TRY
{
GMonitorLock lock(&ctx->monitor);
ctx->mpeeked = 0;
}
G_CATCH_ALL
{
}
G_ENDCATCH;
}
void
ddjvu_message_set_callback(ddjvu_context_t *ctx,
ddjvu_message_callback_t callback,
void *closure)
{
GMonitorLock lock(&ctx->monitor);
ctx->callbackfun = callback;
ctx->callbackarg = closure;
}
// ----------------------------------------
// Document callbacks
void
ddjvu_document_s::release()
{
GPosition p;
GMonitorLock lock(&monitor);
doc = 0;
for (p=thumbnails; p; ++p)
{
ddjvu_thumbnail_p *thumb = thumbnails[p];
if (thumb->pool)
thumb->pool->del_trigger(ddjvu_thumbnail_p::callback, (void*)thumb);
}
for (p = streams; p; ++p)
{
GP<DataPool> pool = streams[p];
if (pool)
pool->del_trigger(callback, (void*)this);
if (pool && !pool->is_eof())
pool->stop();
}
}
ddjvu_status_t
ddjvu_document_s::status()
{
if (!doc)
return DDJVU_JOB_NOTSTARTED;
long flags = doc->get_doc_flags();
if (flags & DjVuDocument::DOC_INIT_OK)
return DDJVU_JOB_OK;
else if (flags & DjVuDocument::DOC_INIT_FAILED)
return DDJVU_JOB_FAILED;
return DDJVU_JOB_STARTED;
}
bool
ddjvu_document_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_document_s")
|| ddjvu_job_s::inherits(classname);
}
bool
ddjvu_document_s::notify_error(const DjVuPort *, const GUTF8String &m)
{
if (!doc) return false;
msg_push(xhead(DDJVU_ERROR, this), msg_prep_error(m));
return true;
}
bool
ddjvu_document_s::notify_status(const DjVuPort *p, const GUTF8String &m)
{
if (!doc) return false;
msg_push(xhead(DDJVU_INFO, this), msg_prep_info(m));
return true;
}
void
ddjvu_document_s::notify_doc_flags_changed(const DjVuDocument *, long, long)
{
GMonitorLock lock(&monitor);
if (docinfoflag || !doc) return;
long flags = doc->get_doc_flags();
if ((flags & DjVuDocument::DOC_INIT_OK) ||
(flags & DjVuDocument::DOC_INIT_FAILED) )
{
msg_push(xhead(DDJVU_DOCINFO, this));
docinfoflag = true;
}
}
void
ddjvu_document_s::callback(void *arg)
{
ddjvu_document_t *doc = (ddjvu_document_t *)arg;
if (doc && doc->pageinfoflag && !doc->fileflag)
msg_push(xhead(DDJVU_PAGEINFO, doc));
}
GP<DataPool>
ddjvu_document_s::request_data(const DjVuPort *p, const GURL &url)
{
// Note: the following line try to restore
// the bytes stored in the djvu file
// despite LT's i18n and gurl classes.
GUTF8String name = (const char*)url.fname();
GMonitorLock lock(&monitor);
GP<DataPool> pool;
if (names.contains(name))
{
int streamid = names[name];
return streams[streamid];
}
else if (fileflag)
{
if (doc && url.is_local_file_url())
return DataPool::create(url);
}
else if (doc)
{
// prepare pool
if (++streamid > 0)
streams[streamid] = pool = DataPool::create();
else
pool = streams[(streamid = 0)];
names[name] = streamid;
pool->add_trigger(-1, callback, (void*)this);
// build message
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->p.m_newstream.streamid = streamid;
p->tmp1 = name;
p->p.m_newstream.name = (const char*)(p->tmp1);
p->p.m_newstream.url = 0;
if (urlflag)
{
// Should be urlencoded.
p->tmp2 = (const char*)url.get_string();
p->p.m_newstream.url = (const char*)(p->tmp2);
}
msg_push(xhead(DDJVU_NEWSTREAM, this), p);
}
return pool;
}
bool
ddjvu_document_s::want_pageinfo()
{
if (doc && docinfoflag && !pageinfoflag)
{
pageinfoflag = true;
int doctype = doc->get_doc_type();
if (doctype == DjVuDocument::BUNDLED ||
doctype == DjVuDocument::OLD_BUNDLED )
{
GP<DataPool> pool;
{
GMonitorLock lock(&monitor);
if (streams.contains(0))
pool = streams[0];
}
if (pool && doctype == DjVuDocument::BUNDLED)
{
GP<DjVmDir> dir = doc->get_djvm_dir();
if (dir)
for (int i=0; i<dir->get_files_num(); i++)
{
GP<DjVmDir::File> f = dir->pos_to_file(i);
if (! pool->has_data(f->offset, f->size))
pool->add_trigger(f->offset, f->size, callback, (void*)this );
}
}
else if (pool && doctype == DjVuDocument::OLD_BUNDLED)
{
GP<DjVmDir0> dir = doc->get_djvm_dir0();
if (dir)
for (int i=0; i<dir->get_files_num(); i++)
{
GP<DjVmDir0::FileRec> f = dir->get_file(i);
if (! pool->has_data(f->offset, f->size))
pool->add_trigger(f->offset, f->size, callback, (void*)this );
}
}
}
}
return pageinfoflag;
}
// ----------------------------------------
// Documents
ddjvu_document_t *
ddjvu_document_create(ddjvu_context_t *ctx,
const char *url,
int cache)
{
ddjvu_document_t *d = 0;
G_TRY
{
DjVuFileCache *xcache = ctx->cache;
if (! cache) xcache = 0;
d = new ddjvu_document_s;
ref(d);
GMonitorLock lock(&d->monitor);
d->streams[0] = DataPool::create();
d->streamid = -1;
d->fileflag = false;
d->docinfoflag = false;
d->pageinfoflag = false;
d->myctx = ctx;
d->mydoc = 0;
d->doc = DjVuDocument::create_noinit();
if (url)
{
GURL gurl = GUTF8String(url);
gurl.clear_djvu_cgi_arguments();
d->urlflag = true;
d->doc->start_init(gurl, d, xcache);
}
else
{
GUTF8String s;
s.format("ddjvu:///doc%d/index.djvu", ++(ctx->uniqueid));;
GURL gurl = s;
d->urlflag = false;
d->doc->start_init(gurl, d, xcache);
}
}
G_CATCH(ex)
{
if (d)
unref(d);
d = 0;
ERROR1(ctx, ex);
}
G_ENDCATCH;
return d;
}
static ddjvu_document_t *
ddjvu_document_create_by_filename_imp(ddjvu_context_t *ctx,
const char *filename,
int cache, int utf8)
{
ddjvu_document_t *d = 0;
G_TRY
{
DjVuFileCache *xcache = ctx->cache;
if (! cache) xcache = 0;
GURL gurl;
if (utf8)
gurl = GURL::Filename::UTF8(filename);
else
gurl = GURL::Filename::Native(filename);
gurl.original = filename;
d = new ddjvu_document_s;
ref(d);
GMonitorLock lock(&d->monitor);
d->streamid = -1;
d->fileflag = true;
d->pageinfoflag = false;
d->urlflag = false;
d->docinfoflag = false;
d->myctx = ctx;
d->mydoc = 0;
d->doc = DjVuDocument::create_noinit();
d->doc->start_init(gurl, d, xcache);
}
G_CATCH(ex)
{
if (d)
unref(d);
d = 0;
ERROR1(ctx, ex);
}
G_ENDCATCH;
return d;
}
ddjvu_document_t *
ddjvu_document_create_by_filename(ddjvu_context_t *ctx,
const char *filename,
int cache)
{
return ddjvu_document_create_by_filename_imp(ctx,filename,cache,0);
}
ddjvu_document_t *
ddjvu_document_create_by_filename_utf8(ddjvu_context_t *ctx,
const char *filename,
int cache)
{
return ddjvu_document_create_by_filename_imp(ctx,filename,cache,1);
}
ddjvu_job_t *
ddjvu_document_job(ddjvu_document_t *document)
{
return document;
}
// ----------------------------------------
// Streams
void
ddjvu_stream_write(ddjvu_document_t *doc,
int streamid,
const char *data,
unsigned long datalen )
{
G_TRY
{
GP<DataPool> pool;
{
GMonitorLock lock(&doc->monitor);
GPosition p = doc->streams.contains(streamid);
if (p) pool = doc->streams[p];
}
if (! pool)
G_THROW("Unknown stream ID");
if (datalen > 0)
pool->add_data(data, datalen);
}
G_CATCH(ex)
{
ERROR1(doc,ex);
}
G_ENDCATCH;
}
void
ddjvu_stream_close(ddjvu_document_t *doc,
int streamid,
int stop )
{
G_TRY
{
GP<DataPool> pool;
{
GMonitorLock lock(&doc->monitor);
GPosition p = doc->streams.contains(streamid);
if (p) pool = doc->streams[p];
}
if (! pool)
G_THROW("Unknown stream ID");
if (stop)
pool->stop(true);
pool->set_eof();
}
G_CATCH(ex)
{
ERROR1(doc, ex);
}
G_ENDCATCH;
}
// ----------------------------------------
// Document queries
ddjvu_document_type_t
ddjvu_document_get_type(ddjvu_document_t *document)
{
G_TRY
{
DjVuDocument *doc = document->doc;
if (doc)
{
switch (doc->get_doc_type())
{
case DjVuDocument::OLD_BUNDLED:
return DDJVU_DOCTYPE_OLD_BUNDLED;
case DjVuDocument::OLD_INDEXED:
return DDJVU_DOCTYPE_OLD_INDEXED;
case DjVuDocument::BUNDLED:
return DDJVU_DOCTYPE_BUNDLED;
case DjVuDocument::INDIRECT:
return DDJVU_DOCTYPE_INDIRECT;
case DjVuDocument::SINGLE_PAGE:
return DDJVU_DOCTYPE_SINGLEPAGE;
default:
break;
}
}
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return DDJVU_DOCTYPE_UNKNOWN;
}
int
ddjvu_document_get_pagenum(ddjvu_document_t *document)
{
G_TRY
{
DjVuDocument *doc = document->doc;
if (doc)
return doc->get_pages_num();
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return 1;
}
int
ddjvu_document_get_filenum(ddjvu_document_t *document)
{
G_TRY
{
DjVuDocument *doc = document->doc;
if (! (doc && doc->is_init_ok()))
return 0;
int doc_type = doc->get_doc_type();
if (doc_type == DjVuDocument::BUNDLED ||
doc_type == DjVuDocument::INDIRECT )
{
GP<DjVmDir> dir = doc->get_djvm_dir();
return dir->get_files_num();
}
else if (doc_type == DjVuDocument::OLD_BUNDLED)
{
GP<DjVmDir0> dir0 = doc->get_djvm_dir0();
return dir0->get_files_num();
}
else
return doc->get_pages_num();
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return 0;
}
#undef ddjvu_document_get_fileinfo
extern "C" DDJVUAPI ddjvu_status_t
ddjvu_document_get_fileinfo(ddjvu_document_t *d, int f, ddjvu_fileinfo_t *i);
ddjvu_status_t
ddjvu_document_get_fileinfo(ddjvu_document_t *d, int f, ddjvu_fileinfo_t *i)
{
// for binary backward compatibility with ddjvuapi=17
struct info17_s { char t; int p,s; const char *d, *n, *l; };
return ddjvu_document_get_fileinfo_imp(d,f,i,sizeof(info17_s));
}
ddjvu_status_t
ddjvu_document_get_fileinfo_imp(ddjvu_document_t *document, int fileno,
ddjvu_fileinfo_t *info,
unsigned int infosz )
{
G_TRY
{
ddjvu_fileinfo_t myinfo;
memset(info, 0, infosz);
if (infosz > sizeof(myinfo))
return DDJVU_JOB_FAILED;
DjVuDocument *doc = document->doc;
if (! doc)
return DDJVU_JOB_NOTSTARTED;
if (! doc->is_init_ok())
return document->status();
int type = doc->get_doc_type();
if ( type == DjVuDocument::BUNDLED ||
type == DjVuDocument::INDIRECT )
{
GP<DjVmDir> dir = doc->get_djvm_dir();
GP<DjVmDir::File> file = dir->pos_to_file(fileno, &myinfo.pageno);
if (! file)
G_THROW("Illegal file number");
myinfo.type = 'I';
if (file->is_page())
myinfo.type = 'P';
else
myinfo.pageno = -1;
if (file->is_thumbnails())
myinfo.type = 'T';
if (file->is_shared_anno())
myinfo.type = 'S';
myinfo.size = file->size;
myinfo.id = file->get_load_name();
myinfo.name = file->get_save_name();
myinfo.title = file->get_title();
memcpy(info, &myinfo, infosz);
return DDJVU_JOB_OK;
}
else if (type == DjVuDocument::OLD_BUNDLED)
{
GP<DjVmDir0> dir0 = doc->get_djvm_dir0();
GP<DjVuNavDir> nav = doc->get_nav_dir();
GP<DjVmDir0::FileRec> frec = dir0->get_file(fileno);
if (! frec)
G_THROW("Illegal file number");
myinfo.size = frec->size;
myinfo.id = (const char*) frec->name;
myinfo.name = myinfo.title = myinfo.id;
if (! nav)
return DDJVU_JOB_STARTED;
else if (nav->name_to_page(frec->name) >= 0)
myinfo.type = 'P';
else
myinfo.type = 'I';
memcpy(info, &myinfo, infosz);
return DDJVU_JOB_OK;
}
else
{
if (fileno<0 || fileno>=doc->get_pages_num())
G_THROW("Illegal file number");
myinfo.type = 'P';
myinfo.pageno = fileno;
myinfo.size = -1;
GP<DjVuNavDir> nav = doc->get_nav_dir();
myinfo.id = (nav) ? (const char *) nav->page_to_name(fileno) : 0;
myinfo.name = myinfo.title = myinfo.id;
GP<DjVuFile> file = doc->get_djvu_file(fileno, true);
GP<DataPool> pool;
if (file)
pool = file->get_init_data_pool();
if (pool)
myinfo.size = pool->get_length();
memcpy(info, &myinfo, infosz);
return DDJVU_JOB_OK;
}
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return DDJVU_JOB_FAILED;
}
int
ddjvu_document_search_pageno(ddjvu_document_t *document, const char *name)
{
G_TRY
{
DjVuDocument *doc = document->doc;
if (! (doc && doc->is_init_ok()))
return -1;
GP<DjVmDir> dir = doc->get_djvm_dir();
if (! dir)
return 0;
GP<DjVmDir::File> file;
if (! (file = dir->id_to_file(GUTF8String(name))))
if (! (file = dir->name_to_file(GUTF8String(name))))
if (! (file = dir->title_to_file(GUTF8String(name))))
{
char *edata=0;
long int p = strtol(name, &edata, 10);
if (edata!=name && !*edata && p>=1)
file = dir->page_to_file(p-1);
}
if (file)
{
int pageno = -1;
int fileno = dir->get_file_pos(file);
if (dir->pos_to_file(fileno, &pageno))
return pageno;
}
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return -1;
}
int
ddjvu_document_check_pagedata(ddjvu_document_t *document, int pageno)
{
G_TRY
{
document->want_pageinfo();
DjVuDocument *doc = document->doc;
if (doc && doc->is_init_ok())
{
bool dontcreate = false;
if (doc->get_doc_type() == DjVuDocument::INDIRECT ||
doc->get_doc_type() == DjVuDocument::OLD_INDEXED )
{
dontcreate = true;
GURL url = doc->page_to_url(pageno);
if (! url.is_empty())
{
GUTF8String name = (const char*)url.fname();
GMonitorLock lock(&document->monitor);
if (document->names.contains(name))
dontcreate = false;
}
}
GP<DjVuFile> file = doc->get_djvu_file(pageno, dontcreate);
if (file && file->is_data_present())
return 1;
}
}
G_CATCH(ex)
{
ERROR1(document,ex);
}
G_ENDCATCH;
return 0;
}
#undef ddjvu_document_get_pageinfo
extern "C" DDJVUAPI ddjvu_status_t
ddjvu_document_get_pageinfo(ddjvu_document_t *d, int p, ddjvu_pageinfo_t *i);
ddjvu_status_t
ddjvu_document_get_pageinfo(ddjvu_document_t *d, int p, ddjvu_pageinfo_t *i)
{
// for binary backward compatibility with ddjvuapi<=17
struct info17_s { int w; int h; int d; };
return ddjvu_document_get_pageinfo_imp(d,p,i,sizeof(struct info17_s));
}
ddjvu_status_t
ddjvu_document_get_pageinfo_imp(ddjvu_document_t *document, int pageno,
ddjvu_pageinfo_t *pageinfo,
unsigned int infosz)
{
G_TRY
{
ddjvu_pageinfo_t myinfo;
memset(pageinfo, 0, infosz);
if (infosz > sizeof(myinfo))
return DDJVU_JOB_FAILED;
DjVuDocument *doc = document->doc;
if (doc)
{
document->want_pageinfo();
GP<DjVuFile> file = doc->get_djvu_file(pageno);
if (! file || ! file->is_data_present() )
return DDJVU_JOB_STARTED;
const GP<ByteStream> pbs(file->get_djvu_bytestream(false, false));
const GP<IFFByteStream> iff(IFFByteStream::create(pbs));
GUTF8String chkid;
if (iff->get_chunk(chkid))
{
if (chkid == "FORM:DJVU")
{
while (iff->get_chunk(chkid) && chkid!="INFO")
iff->close_chunk();
if (chkid == "INFO")
{
GP<ByteStream> gbs = iff->get_bytestream();
GP<DjVuInfo> info=DjVuInfo::create();
info->decode(*gbs);
int rot = info->orientation;
myinfo.rotation = rot;
myinfo.width = (rot&1) ? info->height : info->width;
myinfo.height = (rot&1) ? info->width : info->height;
myinfo.dpi = info->dpi;
myinfo.version = info->version;
memcpy(pageinfo, &myinfo, infosz);
return DDJVU_JOB_OK;
}
}
else if (chkid == "FORM:BM44" || chkid == "FORM:PM44")
{
while (iff->get_chunk(chkid) &&
chkid!="BM44" && chkid!="PM44")
iff->close_chunk();
if (chkid=="BM44" || chkid=="PM44")
{
GP<ByteStream> gbs = iff->get_bytestream();
if (gbs->read8() == 0)
{
gbs->read8();
unsigned char vhi = gbs->read8();
unsigned char vlo = gbs->read8();
unsigned char xhi = gbs->read8();
unsigned char xlo = gbs->read8();
unsigned char yhi = gbs->read8();
unsigned char ylo = gbs->read8();
myinfo.width = (xhi<<8)+xlo;
myinfo.height = (yhi<<8)+ylo;
myinfo.dpi = 100;
myinfo.rotation = 0;
myinfo.version = (vhi<<8)+vlo;
memcpy(pageinfo, &myinfo, infosz);
}
}
}
}
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return DDJVU_JOB_FAILED;
}
static char *
get_file_dump(DjVuFile *file)
{
DjVuDumpHelper dumper;
GP<DataPool> pool = file->get_init_data_pool();
GP<ByteStream> str = dumper.dump(pool);
int size = str->size();
char *buffer;
if ((size = str->size()) > 0 && (buffer = (char*)malloc(size+1)))
{
str->seek(0);
int len = str->readall(buffer, size);
buffer[len] = 0;
return buffer;
}
return 0;
}
char *
ddjvu_document_get_pagedump(ddjvu_document_t *document, int pageno)
{
G_TRY
{
DjVuDocument *doc = document->doc;
if (doc)
{
document->want_pageinfo();
GP<DjVuFile> file = doc->get_djvu_file(pageno);
if (file && file->is_data_present())
return get_file_dump(file);
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return 0;
}
char *
ddjvu_document_get_filedump(ddjvu_document_t *document, int fileno)
{
G_TRY
{
DjVuDocument *doc = document->doc;
document->want_pageinfo();
if (doc)
{
GP<DjVuFile> file;
int type = doc->get_doc_type();
if ( type != DjVuDocument::BUNDLED &&
type != DjVuDocument::INDIRECT )
file = doc->get_djvu_file(fileno);
else
{
GP<DjVmDir> dir = doc->get_djvm_dir();
GP<DjVmDir::File> fdesc = dir->pos_to_file(fileno);
if (fdesc)
file = doc->get_djvu_file(fdesc->get_load_name());
}
if (file && file->is_data_present())
return get_file_dump(file);
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return 0;
}
// ----------------------------------------
// Page
static ddjvu_page_t *
ddjvu_page_create(ddjvu_document_t *document, ddjvu_job_t *job,
const char *pageid, int pageno)
{
ddjvu_page_t *p = 0;
G_TRY
{
DjVuDocument *doc = document->doc;
if (! doc) return 0;
p = new ddjvu_page_s;
ref(p);
GMonitorLock lock(&p->monitor);
p->myctx = document->myctx;
p->mydoc = document;
p->pageinfoflag = false;
p->pagedoneflag = false;
if (! job)
job = p;
p->job = job;
if (pageid)
p->img = doc->get_page(GNativeString(pageid), false, job);
else
p->img = doc->get_page(pageno, false, job);
}
G_CATCH(ex)
{
if (p)
unref(p);
p = 0;
ERROR1(document, ex);
}
G_ENDCATCH;
return p;
}
ddjvu_page_t *
ddjvu_page_create_by_pageno(ddjvu_document_t *document, int pageno)
{
return ddjvu_page_create(document, 0, 0, pageno);
}
ddjvu_page_t *
ddjvu_page_create_by_pageid(ddjvu_document_t *document, const char *pageid)
{
return ddjvu_page_create(document, 0, pageid, 0);
}
ddjvu_job_t *
ddjvu_page_job(ddjvu_page_t *page)
{
return page;
}
// ----------------------------------------
// Page callbacks
void
ddjvu_page_s::release()
{
img = 0;
}
ddjvu_status_t
ddjvu_page_s::status()
{
if (! img)
return DDJVU_JOB_NOTSTARTED;
DjVuFile *file = img->get_djvu_file();
DjVuInfo *info = img->get_info();
if (! file)
return DDJVU_JOB_NOTSTARTED;
else if (file->is_decode_stopped())
return DDJVU_JOB_STOPPED;
else if (file->is_decode_failed())
return DDJVU_JOB_FAILED;
else if (file->is_decode_ok())
return (info) ? DDJVU_JOB_OK : DDJVU_JOB_FAILED;
else if (file->is_decoding())
return DDJVU_JOB_STARTED;
return DDJVU_JOB_NOTSTARTED;
}
bool
ddjvu_page_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_page_s")
|| ddjvu_job_s::inherits(classname);
}
bool
ddjvu_page_s::notify_error(const DjVuPort *, const GUTF8String &m)
{
if (!img) return false;
msg_push(xhead(DDJVU_ERROR, this), msg_prep_error(m));
return true;
}
bool
ddjvu_page_s::notify_status(const DjVuPort *p, const GUTF8String &m)
{
if (!img) return false;
msg_push(xhead(DDJVU_INFO, this), msg_prep_info(m));
return true;
}
void
ddjvu_page_s::notify_file_flags_changed(const DjVuFile *sender, long, long)
{
GMonitorLock lock(&monitor);
if (!img) return;
DjVuFile *file = img->get_djvu_file();
if (file==0 || file!=sender) return;
long flags = file->get_flags();
if ((flags & DjVuFile::DECODE_OK) ||
(flags & DjVuFile::DECODE_FAILED) ||
(flags & DjVuFile::DECODE_STOPPED) )
{
if (pagedoneflag) return;
msg_push(xhead(DDJVU_PAGEINFO, this));
pageinfoflag = pagedoneflag = true;
}
}
void
ddjvu_page_s::notify_relayout(const DjVuImage *dimg)
{
GMonitorLock lock(&monitor);
if (img && !pageinfoflag)
{
msg_push(xhead(DDJVU_PAGEINFO, this));
msg_push(xhead(DDJVU_RELAYOUT, this));
pageinfoflag = true;
}
}
void
ddjvu_page_s::notify_redisplay(const DjVuImage *dimg)
{
GMonitorLock lock(&monitor);
if (img && !pageinfoflag)
{
msg_push(xhead(DDJVU_PAGEINFO, this));
msg_push(xhead(DDJVU_RELAYOUT, this));
pageinfoflag = true;
}
if (img && pageinfoflag)
msg_push(xhead(DDJVU_REDISPLAY, this));
}
void
ddjvu_page_s::notify_chunk_done(const DjVuPort*, const GUTF8String &name)
{
GMonitorLock lock(&monitor);
if (! img) return;
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->tmp1 = name;
p->p.m_chunk.chunkid = (const char*)(p->tmp1);
msg_push(xhead(DDJVU_CHUNK,this), p);
}
// ----------------------------------------
// Page queries
int
ddjvu_page_get_width(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
return page->img->get_width();
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
int
ddjvu_page_get_height(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
return page->img->get_height();
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
int
ddjvu_page_get_resolution(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
return page->img->get_dpi();
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
double
ddjvu_page_get_gamma(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
return page->img->get_gamma();
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 2.2;
}
int
ddjvu_page_get_version(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
return page->img->get_version();
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return DJVUVERSION;
}
ddjvu_page_type_t
ddjvu_page_get_type(ddjvu_page_t *page)
{
G_TRY
{
if (! (page && page->img))
return DDJVU_PAGETYPE_UNKNOWN;
else if (page->img->is_legal_bilevel())
return DDJVU_PAGETYPE_BITONAL;
else if (page->img->is_legal_photo())
return DDJVU_PAGETYPE_PHOTO;
else if (page->img->is_legal_compound())
return DDJVU_PAGETYPE_COMPOUND;
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return DDJVU_PAGETYPE_UNKNOWN;
}
char *
ddjvu_page_get_short_description(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
{
const char *desc = page->img->get_short_description();
return xstr(DjVuMessageLite::LookUpUTF8(desc));
}
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
char *
ddjvu_page_get_long_description(ddjvu_page_t *page)
{
G_TRY
{
if (page && page->img)
{
const char *desc = page->img->get_long_description();
return xstr(DjVuMessageLite::LookUpUTF8(desc));
}
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
// ----------------------------------------
// Rotations
void
ddjvu_page_set_rotation(ddjvu_page_t *page,
ddjvu_page_rotation_t rot)
{
G_TRY
{
switch(rot)
{
case DDJVU_ROTATE_0:
case DDJVU_ROTATE_90:
case DDJVU_ROTATE_180:
case DDJVU_ROTATE_270:
if (page && page->img && page->img->get_info())
page->img->set_rotate((int)rot);
break;
default:
G_THROW("Illegal ddjvu rotation code");
break;
}
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
}
ddjvu_page_rotation_t
ddjvu_page_get_rotation(ddjvu_page_t *page)
{
ddjvu_page_rotation_t rot = DDJVU_ROTATE_0;
G_TRY
{
if (page && page->img)
rot = (ddjvu_page_rotation_t)(page->img->get_rotate() & 3);
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return rot;
}
ddjvu_page_rotation_t
ddjvu_page_get_initial_rotation(ddjvu_page_t *page)
{
ddjvu_page_rotation_t rot = DDJVU_ROTATE_0;
G_TRY
{
GP<DjVuInfo> info;
if (page && page->img)
info = page->img->get_info();
if (info)
rot = (ddjvu_page_rotation_t)(info->orientation & 3);
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return rot;
}
// ----------------------------------------
// Rectangles
static void
rect2grect(const ddjvu_rect_t *r, GRect &g)
{
g.xmin = r->x;
g.ymin = r->y;
g.xmax = r->x + r->w;
g.ymax = r->y + r->h;
}
static void
grect2rect(const GRect &g, ddjvu_rect_t *r)
{
if (g.isempty())
{
r->x = r->y = 0;
r->w = r->h = 0;
}
else
{
r->x = g.xmin;
r->y = g.ymin;
r->w = g.width();
r->h = g.height();
}
}
ddjvu_rectmapper_t *
ddjvu_rectmapper_create(ddjvu_rect_t *input, ddjvu_rect_t *output)
{
GRect ginput, goutput;
rect2grect(input, ginput);
rect2grect(output, goutput);
GRectMapper *mapper = new GRectMapper;
if (!ginput.isempty())
mapper->set_input(ginput);
if (!goutput.isempty())
mapper->set_output(goutput);
return (ddjvu_rectmapper_t*)mapper;
}
void
ddjvu_rectmapper_modify(ddjvu_rectmapper_t *mapper,
int rotation, int mirrorx, int mirrory)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
gmapper->rotate(rotation);
if (mirrorx & 1)
gmapper->mirrorx();
if (mirrory & 1)
gmapper->mirrory();
}
void
ddjvu_rectmapper_release(ddjvu_rectmapper_t *mapper)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
delete gmapper;
}
void
ddjvu_map_point(ddjvu_rectmapper_t *mapper, int *x, int *y)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
gmapper->map(*x,*y);
}
void
ddjvu_map_rect(ddjvu_rectmapper_t *mapper, ddjvu_rect_t *rect)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
GRect grect;
rect2grect(rect,grect);
gmapper->map(grect);
grect2rect(grect,rect);
}
void
ddjvu_unmap_point(ddjvu_rectmapper_t *mapper, int *x, int *y)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
gmapper->unmap(*x,*y);
}
void
ddjvu_unmap_rect(ddjvu_rectmapper_t *mapper, ddjvu_rect_t *rect)
{
GRectMapper *gmapper = (GRectMapper*)mapper;
if (! gmapper) return;
GRect grect;
rect2grect(rect,grect);
gmapper->unmap(grect);
grect2rect(grect,rect);
}
// ----------------------------------------
// Render
struct DJVUNS ddjvu_format_s
{
ddjvu_format_style_t style;
uint32_t rgb[3][256];
uint32_t palette[6*6*6];
uint32_t xorval;
double gamma;
GPixel white;
char ditherbits;
bool rtoptobottom;
bool ytoptobottom;
};
static ddjvu_format_t *
fmt_error(ddjvu_format_t *fmt)
{
delete fmt;
return 0;
}
ddjvu_format_t *
ddjvu_format_create(ddjvu_format_style_t style,
int nargs, unsigned int *args)
{
ddjvu_format_t *fmt = new ddjvu_format_s;
memset(fmt, 0, sizeof(ddjvu_format_t));
fmt->style = style;
fmt->rtoptobottom = false;
fmt->ytoptobottom = false;
fmt->gamma = 2.2;
fmt->white = GPixel::WHITE;
// Ditherbits
fmt->ditherbits = 32;
if (style==DDJVU_FORMAT_RGBMASK16)
fmt->ditherbits = 16;
else if (style==DDJVU_FORMAT_PALETTE8)
fmt->ditherbits = 8;
else if (style==DDJVU_FORMAT_MSBTOLSB || style==DDJVU_FORMAT_LSBTOMSB)
fmt->ditherbits = 1;
// Args
switch(style)
{
case DDJVU_FORMAT_RGBMASK16:
case DDJVU_FORMAT_RGBMASK32:
{
if (sizeof(uint16_t)!=2 || sizeof(uint32_t)!=4)
return fmt_error(fmt);
if (!args || nargs<3 || nargs>4)
return fmt_error(fmt);
{ // extra nesting for windows
for (int j=0; j<3; j++)
{
int shift = 0;
uint32_t mask = args[j];
for (shift=0; shift<32 && !(mask & 1); shift++)
mask >>= 1;
if ((shift>=32) || (mask&(mask+1)))
return fmt_error(fmt);
for (int i=0; i<256; i++)
fmt->rgb[j][i] = (mask & ((int)((i*mask+127.0)/255.0)))<<shift;
}
}
if (nargs >= 4)
fmt->xorval = args[3];
break;
}
case DDJVU_FORMAT_PALETTE8:
{
if (nargs!=6*6*6 || !args)
return fmt_error(fmt);
{ // extra nesting for windows
for (int k=0; k<6*6*6; k++)
fmt->palette[k] = args[k];
}
{ // extra nesting for windows
int j=0;
for(int i=0; i<6; i++)
for(; j < (i+1)*0x33 - 0x19 && j<256; j++)
{
fmt->rgb[0][j] = i * 6 * 6;
fmt->rgb[1][j] = i * 6;
fmt->rgb[2][j] = i;
}
}
break;
}
case DDJVU_FORMAT_RGB24:
case DDJVU_FORMAT_BGR24:
case DDJVU_FORMAT_GREY8:
case DDJVU_FORMAT_LSBTOMSB:
case DDJVU_FORMAT_MSBTOLSB:
if (!nargs)
break;
default:
return fmt_error(fmt);
}
return fmt;
}
void
ddjvu_format_set_row_order(ddjvu_format_t *format, int top_to_bottom)
{
format->rtoptobottom = !! top_to_bottom;
}
void
ddjvu_format_set_y_direction(ddjvu_format_t *format, int top_to_bottom)
{
format->ytoptobottom = !! top_to_bottom;
}
void
ddjvu_format_set_ditherbits(ddjvu_format_t *format, int bits)
{
if (bits>0 && bits<=64)
format->ditherbits = bits;
}
void
ddjvu_format_set_gamma(ddjvu_format_t *format, double gamma)
{
if (gamma>=0.5 && gamma<=5.0)
format->gamma = gamma;
}
void
ddjvu_format_set_white(ddjvu_format_t *format,
unsigned char b, unsigned char g, unsigned char r)
{
format->white.b = b;
format->white.g = g;
format->white.r = r;
}
void
ddjvu_format_release(ddjvu_format_t *format)
{
delete format;
}
static void
fmt_convert_row(const GPixel *p, int w,
const ddjvu_format_t *fmt, char *buf)
{
const uint32_t (*r)[256] = fmt->rgb;
const uint32_t xorval = fmt->xorval;
switch(fmt->style)
{
case DDJVU_FORMAT_BGR24: /* truecolor 24 bits in BGR order */
{
memcpy(buf, (const char*)p, 3*w);
break;
}
case DDJVU_FORMAT_RGB24: /* truecolor 24 bits in RGB order */
{
while (--w >= 0) {
buf[0]=p->r; buf[1]=p->g; buf[2]=p->b;
buf+=3; p+=1;
}
break;
}
case DDJVU_FORMAT_RGBMASK16: /* truecolor 16 bits with masks */
{
uint16_t *b = (uint16_t*)buf;
while (--w >= 0) {
b[0]=(r[0][p->r]|r[1][p->g]|r[2][p->b])^xorval;
b+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_RGBMASK32: /* truecolor 32 bits with masks */
{
uint32_t *b = (uint32_t*)buf;
while (--w >= 0) {
b[0]=(r[0][p->r]|r[1][p->g]|r[2][p->b])^xorval;
b+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_GREY8: /* greylevel 8 bits */
{
while (--w >= 0) {
buf[0]=(5*p->r + 9*p->g + 2*p->b)>>4;
buf+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_PALETTE8: /* paletized 8 bits (6x6x6 color cube) */
{
const uint32_t *u = fmt->palette;
while (--w >= 0) {
buf[0] = u[r[0][p->r]+r[1][p->g]+r[2][p->b]];
buf+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_MSBTOLSB: /* packed bits, msb on the left */
{
int t = (5*fmt->white.r + 9*fmt->white.g + 2*fmt->white.b + 16);
t = t * 0xc / 0x10;
unsigned char s=0, m=0x80;
while (--w >= 0) {
if ( 5*p->r + 9*p->g + 2*p->b < t ) { s |= m; }
if (! (m >>= 1)) { *buf++ = s; s=0; m=0x80; }
p += 1;
}
if (m < 0x80) { *buf++ = s; }
break;
}
case DDJVU_FORMAT_LSBTOMSB: /* packed bits, lsb on the left */
{
int t = 5*fmt->white.r + 9*fmt->white.g + 2*fmt->white.b + 16;
t = t * 0xc / 0x10;
unsigned char s=0, m=0x1;
while (--w >= 0) {
if ( 5*p->r + 9*p->g + 2*p->b < t ) { s |= m; }
if (! (m <<= 1)) { *buf++ = s; s=0; m=0x1; }
p += 1;
}
if (m > 0x1) { *buf++ = s; }
break;
}
}
}
static void
fmt_convert(GPixmap *pm, const ddjvu_format_t *fmt, char *buffer, int rowsize)
{
int w = pm->columns();
int h = pm->rows();
// Loop on rows
if (fmt->rtoptobottom)
{
for(int r=h-1; r>=0; r--, buffer+=rowsize)
fmt_convert_row((*pm)[r], w, fmt, buffer);
}
else
{
for(int r=0; r<h; r++, buffer+=rowsize)
fmt_convert_row((*pm)[r], w, fmt, buffer);
}
}
static void
fmt_convert_row(unsigned char *p, unsigned char g[256][4], int w,
const ddjvu_format_t *fmt, char *buf)
{
const uint32_t (*r)[256] = fmt->rgb;
const uint32_t xorval = fmt->xorval;
switch(fmt->style)
{
case DDJVU_FORMAT_BGR24: /* truecolor 24 bits in BGR order */
{
while (--w >= 0) {
buf[0]=g[*p][0];
buf[1]=g[*p][1];
buf[2]=g[*p][2];
buf+=3; p+=1;
}
break;
}
case DDJVU_FORMAT_RGB24: /* truecolor 24 bits in RGB order */
{
while (--w >= 0) {
buf[0]=g[*p][2];
buf[1]=g[*p][1];
buf[2]=g[*p][0];
buf+=3; p+=1;
}
break;
}
case DDJVU_FORMAT_RGBMASK16: /* truecolor 16 bits with masks */
{
uint16_t *b = (uint16_t*)buf;
while (--w >= 0) {
unsigned char x = *p;
b[0]=(r[0][g[x][2]]|r[1][g[x][1]]|r[2][g[x][0]])^xorval;
b+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_RGBMASK32: /* truecolor 32 bits with masks */
{
uint32_t *b = (uint32_t*)buf;
while (--w >= 0) {
unsigned char x = *p;
b[0]=(r[0][g[x][2]]|r[1][g[x][1]]|r[2][g[x][0]])^xorval;
b+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_GREY8: /* greylevel 8 bits */
{
while (--w >= 0) {
buf[0]=g[*p][3];
buf+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_PALETTE8: /* paletized 8 bits (6x6x6 color cube) */
{
const uint32_t *u = fmt->palette;
while (--w >= 0) {
unsigned char x = *p;
buf[0] = u[r[0][g[x][0]]+r[1][g[x][1]]+r[2][g[x][2]]];
buf+=1; p+=1;
}
break;
}
case DDJVU_FORMAT_MSBTOLSB: /* packed bits, msb on the left */
{
int t = 5*fmt->white.r + 9*fmt->white.g + 2*fmt->white.b + 16;
t = t * 0xc / 0x100;
unsigned char s=0, m=0x80;
while (--w >= 0) {
unsigned char x = *p;
if ( g[x][3] < t ) { s |= m; }
if (! (m >>= 1)) { *buf++ = s; s=0; m=0x80; }
p += 1;
}
if (m < 0x80) { *buf++ = s; }
break;
}
case DDJVU_FORMAT_LSBTOMSB: /* packed bits, lsb on the left */
{
int t = 5*fmt->white.r + 9*fmt->white.g + 2*fmt->white.b + 16;
t = t * 0xc / 0x100;
unsigned char s=0, m=0x1;
while (--w >= 0) {
unsigned char x = *p;
if ( g[x][3] < t ) { s |= m; }
if (! (m <<= 1)) { *buf++ = s; s=0; m=0x1; }
p += 1;
}
if (m > 0x1) { *buf++ = s; }
break;
}
}
}
static void
fmt_convert(GBitmap *bm, const ddjvu_format_t *fmt, char *buffer, int rowsize)
{
int w = bm->columns();
int h = bm->rows();
int m = bm->get_grays();
// Gray levels
int i;
unsigned char g[256][4];
const GPixel &wh = fmt->white;
for (i=0; i<m; i++)
{
g[i][0] = wh.b - ( i * wh.b + (m - 1)/2 ) / (m - 1);
g[i][1] = wh.g - ( i * wh.g + (m - 1)/2 ) / (m - 1);
g[i][2] = wh.r - ( i * wh.r + (m - 1)/2 ) / (m - 1);
g[i][3] = (5*g[i][2] + 9*g[i][1] + 2*g[i][0])>>4;
}
for (i=m; i<256; i++)
g[i][0] = g[i][1] = g[i][2] = g[i][3] = 0;
// Loop on rows
if (fmt->rtoptobottom)
{
for(int r=h-1; r>=0; r--, buffer+=rowsize)
fmt_convert_row((*bm)[r], g, w, fmt, buffer);
}
else
{
for(int r=0; r<h; r++, buffer+=rowsize)
fmt_convert_row((*bm)[r], g, w, fmt, buffer);
}
}
static void
fmt_dither(GPixmap *pm, const ddjvu_format_t *fmt, int x, int y)
{
if (fmt->ditherbits < 8)
return;
else if (fmt->ditherbits < 15)
pm->ordered_666_dither(x, y);
else if (fmt->ditherbits < 24)
pm->ordered_32k_dither(x, y);
}
// ----------------------------------------
int
ddjvu_page_render(ddjvu_page_t *page,
const ddjvu_render_mode_t mode,
const ddjvu_rect_t *pagerect,
const ddjvu_rect_t *renderrect,
const ddjvu_format_t *format,
unsigned long rowsize,
char *imagebuffer )
{
G_TRY
{
GP<GPixmap> pm;
GP<GBitmap> bm;
GRect prect, rrect;
rect2grect(pagerect, prect);
rect2grect(renderrect, rrect);
if (format && format->ytoptobottom)
{
prect.ymin = renderrect->y + renderrect->h;
prect.ymax = prect.ymin + pagerect->h;
rrect.ymin = pagerect->y + pagerect->h;
rrect.ymax = rrect.ymin + renderrect->h;
}
DjVuImage *img = page->img;
if (img)
{
switch (mode)
{
case DDJVU_RENDER_COLOR:
pm = img->get_pixmap(rrect,prect, format->gamma,format->white);
if (! pm)
bm = img->get_bitmap(rrect,prect);
break;
case DDJVU_RENDER_BLACK:
bm = img->get_bitmap(rrect,prect);
if (! bm)
pm = img->get_pixmap(rrect,prect, format->gamma,format->white);
break;
case DDJVU_RENDER_MASKONLY:
bm = img->get_bitmap(rrect,prect);
break;
case DDJVU_RENDER_COLORONLY:
pm = img->get_pixmap(rrect,prect, format->gamma,format->white);
break;
case DDJVU_RENDER_BACKGROUND:
pm = img->get_bg_pixmap(rrect,prect, format->gamma,format->white);
break;
case DDJVU_RENDER_FOREGROUND:
pm = img->get_fg_pixmap(rrect,prect, format->gamma,format->white);
if (! pm)
bm = img->get_bitmap(rrect,prect);
break;
}
}
if (pm)
{
int dx = rrect.xmin - prect.xmin;
int dy = rrect.ymin - prect.xmin;
fmt_dither(pm, format, dx, dy);
fmt_convert(pm, format, imagebuffer, rowsize);
return 2;
}
else if (bm)
{
fmt_convert(bm, format, imagebuffer, rowsize);
return 1;
}
}
G_CATCH(ex)
{
ERROR1(page, ex);
}
G_ENDCATCH;
return 0;
}
// ----------------------------------------
// Thumbnails
void
ddjvu_thumbnail_p::callback(void *cldata)
{
ddjvu_thumbnail_p *thumb = (ddjvu_thumbnail_p*)cldata;
if (thumb->document)
{
GMonitorLock lock(&thumb->document->monitor);
if (thumb->pool && thumb->pool->is_eof())
{
GP<DataPool> pool = thumb->pool;
int size = pool->get_size();
thumb->pool = 0;
G_TRY
{
thumb->data.resize(0,size-1);
pool->get_data( (void*)(char*)thumb->data, 0, size);
}
G_CATCH_ALL
{
thumb->data.empty();
}
G_ENDCATCH;
if (thumb->document->doc)
{
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->p.m_thumbnail.pagenum = thumb->pagenum;
msg_push(xhead(DDJVU_THUMBNAIL, thumb->document), p);
}
}
}
}
ddjvu_status_t
ddjvu_thumbnail_status(ddjvu_document_t *document, int pagenum, int start)
{
G_TRY
{
GP<ddjvu_thumbnail_p> thumb;
DjVuDocument* doc = document->doc;
if (doc)
{
GMonitorLock lock(&document->monitor);
GPosition p = document->thumbnails.contains(pagenum);
if (p)
thumb = document->thumbnails[p];
}
if (!thumb && doc)
{
GP<DataPool> pool = doc->get_thumbnail(pagenum, !start);
if (pool)
{
GMonitorLock lock(&document->monitor);
thumb = new ddjvu_thumbnail_p;
thumb->document = document;
thumb->pagenum = pagenum;
thumb->pool = pool;
document->thumbnails[pagenum] = thumb;
}
if (thumb)
pool->add_trigger(-1, ddjvu_thumbnail_p::callback,
(void*)(ddjvu_thumbnail_p*)thumb);
}
if (! thumb)
return DDJVU_JOB_NOTSTARTED;
else if (thumb->pool)
return DDJVU_JOB_STARTED;
else if (thumb->data.size() > 0)
return DDJVU_JOB_OK;
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return DDJVU_JOB_FAILED;
}
int
ddjvu_thumbnail_render(ddjvu_document_t *document, int pagenum,
int *wptr, int *hptr,
const ddjvu_format_t *format,
unsigned long rowsize,
char *imagebuffer)
{
G_TRY
{
GP<ddjvu_thumbnail_p> thumb;
ddjvu_status_t status = ddjvu_thumbnail_status(document,pagenum,FALSE);
if (status == DDJVU_JOB_OK)
{
GMonitorLock lock(&document->monitor);
thumb = document->thumbnails[pagenum];
}
if (! (thumb && wptr && hptr))
return FALSE;
if (! (thumb->data.size() > 0))
return FALSE;
/* Decode wavelet data */
int size = thumb->data.size();
char *data = (char*)thumb->data;
GP<IW44Image> iw = IW44Image::create_decode();
iw->decode_chunk(ByteStream::create_static((void*)data, size));
int w = iw->get_width();
int h = iw->get_height();
/* Restore aspect ratio */
double dw = (double)w / *wptr;
double dh = (double)h / *hptr;
if (dw > dh)
*hptr = (int)(h / dw);
else
*wptr = (int)(w / dh);
if (! imagebuffer)
return TRUE;
/* Render and scale image */
GP<GPixmap> pm = iw->get_pixmap();
double thumbgamma = document->doc->get_thumbnails_gamma();
pm->color_correct(format->gamma/thumbgamma, format->white);
GP<GPixmapScaler> scaler = GPixmapScaler::create(w, h, *wptr, *hptr);
GP<GPixmap> scaledpm = GPixmap::create();
GRect scaledrect(0, 0, *wptr, *hptr);
scaler->scale(GRect(0, 0, w, h), *pm, scaledrect, *scaledpm);
/* Convert */
fmt_dither(scaledpm, format, 0, 0);
fmt_convert(scaledpm, format, imagebuffer, rowsize);
return TRUE;
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return FALSE;
}
// ----------------------------------------
// Threaded jobs
struct DJVUNS ddjvu_runnablejob_s : public ddjvu_job_s
{
bool mystop;
int myprogress;
ddjvu_status_t mystatus;
// methods
ddjvu_runnablejob_s();
ddjvu_status_t start();
void progress(int p);
// thread function
virtual ddjvu_status_t run() = 0;
// virtual port functions:
virtual bool inherits(const GUTF8String&);
virtual ddjvu_status_t status();
virtual void stop();
private:
static void cbstart(void*);
};
ddjvu_runnablejob_s::ddjvu_runnablejob_s()
: mystop(false), myprogress(-1),
mystatus(DDJVU_JOB_NOTSTARTED)
{
}
void
ddjvu_runnablejob_s::progress(int x)
{
if ((mystatus>=DDJVU_JOB_OK) || (x>myprogress && x<100))
{
GMonitorLock lock(&monitor);
GP<ddjvu_message_p> p = new ddjvu_message_p;
p->p.m_progress.status = mystatus;
p->p.m_progress.percent = myprogress = x;
msg_push(xhead(DDJVU_PROGRESS,this),p);
}
}
ddjvu_status_t
ddjvu_runnablejob_s::start()
{
GMonitorLock lock(&monitor);
if (mystatus==DDJVU_JOB_NOTSTARTED && myctx)
{
GThread thr;
thr.create(cbstart, (void*)this);
monitor.wait();
}
return mystatus;
}
void
ddjvu_runnablejob_s::cbstart(void *arg)
{
GP<ddjvu_runnablejob_s> self = (ddjvu_runnablejob_s*)arg;
{
GMonitorLock lock(&self->monitor);
self->mystatus = DDJVU_JOB_STARTED;
self->monitor.signal();
}
ddjvu_status_t r;
G_TRY
{
G_TRY
{
self->progress(0);
r = self->run();
}
G_CATCH(ex)
{
ERROR1(self, ex);
G_RETHROW;
}
G_ENDCATCH;
}
G_CATCH_ALL
{
r = DDJVU_JOB_FAILED;
if (self && self->mystop)
r = DDJVU_JOB_STOPPED;
}
G_ENDCATCH;
{
GMonitorLock lock(&self->monitor);
self->mystatus = r;
}
if (self && self->mystatus> DDJVU_JOB_OK)
self->progress(self->myprogress);
else
self->progress(100);
}
bool
ddjvu_runnablejob_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_runnablejob_s")
|| ddjvu_job_s::inherits(classname);
}
ddjvu_status_t
ddjvu_runnablejob_s::status()
{
return mystatus;
}
void
ddjvu_runnablejob_s::stop()
{
mystop = true;
}
// ----------------------------------------
// Printing
struct DJVUNS ddjvu_printjob_s : public ddjvu_runnablejob_s
{
DjVuToPS printer;
GUTF8String pages;
GP<ByteStream> obs;
virtual ddjvu_status_t run();
// virtual port functions:
virtual bool inherits(const GUTF8String&);
// progress
static void cbrefresh(void*);
static void cbprogress(double, void*);
static void cbinfo(int, int, int, DjVuToPS::Stage, void*);
double progress_low;
double progress_high;
};
bool
ddjvu_printjob_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_printjob_s")
|| ddjvu_runnablejob_s::inherits(classname);
}
ddjvu_status_t
ddjvu_printjob_s::run()
{
mydoc->doc->wait_for_complete_init();
progress_low = 0;
progress_high = 1;
printer.set_refresh_cb(cbrefresh, (void*)this);
printer.set_dec_progress_cb(cbprogress, (void*)this);
printer.set_prn_progress_cb(cbprogress, (void*)this);
printer.set_info_cb(cbinfo, (void*)this);
printer.print(*obs, mydoc->doc, pages);
return DDJVU_JOB_OK;
}
void
ddjvu_printjob_s::cbrefresh(void *data)
{
ddjvu_printjob_s *self = (ddjvu_printjob_s*)data;
if (self->mystop)
{
msg_push(xhead(DDJVU_INFO,self), msg_prep_info("Print job stopped"));
G_THROW(DataPool::Stop);
}
}
void
ddjvu_printjob_s::cbprogress(double done, void *data)
{
ddjvu_printjob_s *self = (ddjvu_printjob_s*)data;
double &low = self->progress_low;
double &high = self->progress_high;
double progress = low;
if (done >= 1)
progress = high;
else if (done >= 0)
progress = low + done * (high-low);
self->progress((int)(progress * 100));
ddjvu_printjob_s::cbrefresh(data);
}
void
ddjvu_printjob_s::cbinfo(int pnum, int pcnt, int ptot,
DjVuToPS::Stage stage, void *data)
{
ddjvu_printjob_s *self = (ddjvu_printjob_s*)data;
double &low = self->progress_low;
double &high = self->progress_high;
low = 0;
high = 1;
if (ptot > 0)
{
double step = 1.0 / (double)ptot;
low = (double)pcnt * step;
if (stage != DjVuToPS::DECODING)
low += step / 2.0;
high = low + step / 2.0;
}
if (low < 0)
low = 0;
if (low > 1)
low = 1;
if (high < low)
high = low;
if (high > 1)
high = 1;
self->progress((int)(low * 100));
ddjvu_printjob_s::cbrefresh(data);
}
static void
complain(GUTF8String opt, const char *msg)
{
GUTF8String message;
if (opt.length() > 0)
message = "Parsing \"" + opt + "\": " + msg;
else
message = msg;
G_EMTHROW(GException((const char*)message));
}
ddjvu_job_t *
ddjvu_document_print(ddjvu_document_t *document, FILE *output,
int optc, const char * const * optv)
{
ddjvu_printjob_s *job = 0;
G_TRY
{
job = new ddjvu_printjob_s;
ref(job);
job->myctx = document->myctx;
job->mydoc = document;
// parse options (see djvups(1))
DjVuToPS::Options &options = job->printer.options;
GUTF8String &pages = job->pages;
while (optc>0)
{
// normalize
GNativeString narg(optv[0]);
GUTF8String uarg = narg;
const char *s1 = (const char*)narg;
if (s1[0] == '-') s1++;
if (s1[0] == '-') s1++;
// separate arguments
const char *s2 = s1;
while (*s2 && *s2 != '=') s2++;
GUTF8String s( s1, s2-s1 );
GUTF8String arg( s2[0] && s2[1] ? s2+1 : "" );
// rumble!
if (s == "page" || s == "pages")
{
if (pages.length())
pages = pages + ",";
pages = pages + arg;
}
else if (s == "format")
{
if (arg == "ps")
options.set_format(DjVuToPS::Options::PS);
else if (arg == "eps")
options.set_format(DjVuToPS::Options::EPS);
else
complain(uarg,"Invalid format. Use \"ps\" or \"eps\".");
}
else if (s == "level")
{
int endpos;
int lvl = arg.toLong(0, endpos);
if (endpos != (int)arg.length() || lvl < 1 || lvl > 4)
complain(uarg,"Invalid Postscript language level.");
options.set_level(lvl);
}
else if (s == "orient" || s == "orientation")
{
if (arg == "a" || arg == "auto" )
options.set_orientation(DjVuToPS::Options::AUTO);
else if (arg == "l" || arg == "landscape" )
options.set_orientation(DjVuToPS::Options::LANDSCAPE);
else if (arg == "p" || arg == "portrait" )
options.set_orientation(DjVuToPS::Options::PORTRAIT);
else
complain(uarg,"Invalid orientation. Use \"auto\", "
"\"landscape\" or \"portrait\".");
}
else if (s == "mode")
{
if (arg == "c" || arg == "color" )
options.set_mode(DjVuToPS::Options::COLOR);
else if (arg == "black" || arg == "bw")
options.set_mode(DjVuToPS::Options::BW);
else if (arg == "fore" || arg == "foreground")
options.set_mode(DjVuToPS::Options::FORE);
else if (arg == "back" || arg == "background" )
options.set_mode(DjVuToPS::Options::BACK);
else
complain(uarg,"Invalid mode. Use \"color\", \"bw\", "
"\"foreground\", or \"background\".");
}
else if (s == "zoom")
{
if (arg == "auto" || arg == "fit" || arg == "fit_page")
options.set_zoom(0);
else if (arg == "1to1" || arg == "onetoone")
options.set_zoom(100);
else
{
int endpos;
int z = arg.toLong(0,endpos);
if (endpos != (int)arg.length() || z < 25 || z > 2400)
complain(uarg,"Invalid zoom factor.");
options.set_zoom(z);
}
}
else if (s == "color")
{
if (arg == "yes" || arg == "")
options.set_color(true);
else if (arg == "no")
options.set_color(false);
else
complain(uarg,"Invalid argument. Use \"yes\" or \"no\".");
}
else if (s == "gray" || s == "grayscale")
{
if (arg.length())
complain(uarg,"No argument was expected.");
options.set_color(false);
}
else if (s == "srgb" || s == "colormatch")
{
if (arg == "yes" || arg == "")
options.set_sRGB(true);
else if (arg == "no")
options.set_sRGB(false);
else
complain(uarg,"Invalid argument. Use \"yes\" or \"no\".");
}
else if (s == "gamma")
{
int endpos;
double g = arg.toDouble(0,endpos);
if (endpos != (int)arg.length() || g < 0.3 || g > 5.0)
complain(uarg,"Invalid gamma factor. "
"Use a number in range 0.3 ... 5.0.");
options.set_gamma(g);
}
else if (s == "copies")
{
int endpos;
int n = arg.toLong(0, endpos);
if (endpos != (int)arg.length() || n < 1 || n > 999999)
complain(uarg,"Invalid number of copies.");
options.set_copies(n);
}
else if (s == "frame")
{
if (arg == "yes" || arg == "")
options.set_frame(true);
else if (arg == "no")
options.set_frame(false);
else
complain(uarg,"Invalid argument. Use \"yes\" or \"no\".");
}
else if (s == "cropmarks")
{
if (arg == "yes" || arg == "")
options.set_cropmarks(true);
else if (arg == "no")
options.set_cropmarks(false);
else
complain(uarg,"Invalid argument. Use \"yes\" or \"no\".");
}
else if (s == "text")
{
if (arg == "yes" || arg == "")
options.set_text(true);
else if (arg == "no")
options.set_text(false);
else
complain(uarg,"Invalid argument. Use \"yes\" or \"no\".");
}
else if (s == "booklet")
{
if (arg == "no")
options.set_bookletmode(DjVuToPS::Options::OFF);
else if (arg == "recto")
options.set_bookletmode(DjVuToPS::Options::RECTO);
else if (arg == "verso")
options.set_bookletmode(DjVuToPS::Options::VERSO);
else if (arg == "rectoverso" || arg=="yes" || arg=="")
options.set_bookletmode(DjVuToPS::Options::RECTOVERSO);
else
complain(uarg,"Invalid argument."
"Use \"no\", \"yes\", \"recto\", or \"verso\".");
}
else if (s == "bookletmax")
{
int endpos;
int n = arg.toLong(0, endpos);
if (endpos != (int)arg.length() || n < 0 || n > 999999)
complain(uarg,"Invalid argument.");
options.set_bookletmax(n);
}
else if (s == "bookletalign")
{
int endpos;
int n = arg.toLong(0, endpos);
if (endpos != (int)arg.length() || n < -720 || n > +720)
complain(uarg,"Invalid argument.");
options.set_bookletalign(n);
}
else if (s == "bookletfold")
{
int endpos = 0;
int m = 250;
int n = arg.toLong(0, endpos);
if (endpos>0 && endpos<(int)arg.length() && arg[endpos]=='+')
m = arg.toLong(endpos+1, endpos);
if (endpos != (int)arg.length() || m<0 || m>720 || n<0 || n>9999 )
complain(uarg,"Invalid argument.");
options.set_bookletfold(n,m);
}
else
{
complain(uarg, "Unrecognized option.");
}
// Next option
optc -= 1;
optv += 1;
}
// go
job->obs = ByteStream::create(output, "wb", false);
job->start();
}
G_CATCH(ex)
{
if (job)
unref(job);
job = 0;
ERROR1(document, ex);
}
G_ENDCATCH;
return job;
}
// ----------------------------------------
// Saving
struct DJVUNS ddjvu_savejob_s : public ddjvu_runnablejob_s
{
GP<ByteStream> obs;
GURL odir;
GUTF8String oname;
GUTF8String pages;
GTArray<char> comp_flags;
GArray<GUTF8String> comp_ids;
GPArray<DjVuFile> comp_files;
GMonitor monitor;
// thread routine
virtual ddjvu_status_t run();
// virtual port functions:
virtual bool inherits(const GUTF8String&);
virtual void notify_file_flags_changed(const DjVuFile*, long, long);
// helpers
bool parse_pagespec(const char *s, int npages, bool *flags);
void mark_included_files(DjVuFile *file);
};
bool
ddjvu_savejob_s::inherits(const GUTF8String &classname)
{
return (classname == "ddjvu_savejob_s")
|| ddjvu_runnablejob_s::inherits(classname);
}
void
ddjvu_savejob_s::notify_file_flags_changed(const DjVuFile *file,
long mask, long)
{
if (mask & (DjVuFile::ALL_DATA_PRESENT | DjVuFile::DATA_PRESENT |
DjVuFile::DECODE_FAILED | DjVuFile::DECODE_STOPPED |
DjVuFile::STOPPED | DjVuFile::DECODE_STOPPED ))
{
GMonitorLock lock(&monitor);
monitor.signal();
}
}
bool
ddjvu_savejob_s::parse_pagespec(const char *s, int npages, bool *flags)
{
int spec = 0;
int both = 1;
int start_page = 1;
int end_page = npages;
int pageno;
char *p = (char*)s;
while (*p)
{
spec = 0;
while (*p==' ')
p += 1;
if (! *p)
break;
if (*p>='0' && *p<='9') {
end_page = strtol(p, &p, 10);
spec = 1;
} else if (*p=='$') {
spec = 1;
end_page = npages;
p += 1;
} else if (both) {
end_page = 1;
} else {
end_page = npages;
}
while (*p==' ')
p += 1;
if (both) {
start_page = end_page;
if (*p == '-') {
p += 1;
both = 0;
continue;
}
}
both = 1;
while (*p==' ')
p += 1;
if (*p && *p != ',')
return false;
if (*p == ',')
p += 1;
if (! spec)
return false;
if (end_page < 0)
end_page = 0;
if (start_page < 0)
start_page = 0;
if (end_page > npages)
end_page = npages;
if (start_page > npages)
start_page = npages;
if (start_page <= end_page)
for(pageno=start_page; pageno<=end_page; pageno++)
flags[pageno-1] = true;
else
for(pageno=start_page; pageno>=end_page; pageno--)
flags[pageno-1] = true;
}
if (!spec)
return false;
return true;
}
void
ddjvu_savejob_s::mark_included_files(DjVuFile *file)
{
GP<DataPool> pool = file->get_init_data_pool();
GP<ByteStream> str(pool->get_stream());
GP<IFFByteStream> iff(IFFByteStream::create(str));
GUTF8String chkid;
if (!iff->get_chunk(chkid))
return;
while (iff->get_chunk(chkid))
{
if (chkid == "INCL")
{
GP<ByteStream> incl = iff->get_bytestream();
GUTF8String fileid;
char buffer[1024];
int length;
while((length=incl->read(buffer, 1024)))
fileid += GUTF8String(buffer, length);
for (int i=0; i<comp_ids.size(); i++)
if (fileid == comp_ids[i] && !comp_flags[i])
comp_flags[i] = 1;
}
iff->close_chunk();
}
iff->close_chunk();
pool->clear_stream();
}
ddjvu_status_t
ddjvu_savejob_s::run()
{
DjVuDocument *doc = mydoc->doc;
doc->wait_for_complete_init();
// Determine which pages to save
int npages = doc->get_pages_num();
GTArray<bool> page_flags(0, npages-1);
if (!pages)
{
for (int pageno=0; pageno<npages; pageno++)
page_flags[pageno] = true;
}
else
{
const char *s = pages;
while (*s && *s!='=')
s += 1;
for (int pageno=0; pageno<npages; pageno++)
page_flags[pageno] = false;
if ((*s != '=') || !parse_pagespec(s+1, npages, (bool*)page_flags))
complain(pages,"Illegal page specification");
if (doc->get_doc_type()==DjVuDocument::OLD_BUNDLED ||
doc->get_doc_type()==DjVuDocument::OLD_INDEXED )
complain(pages,"Saving subsets of obsolete formats is not supported");
}
// Determine which component files to save
int ncomps;
if (doc->get_doc_type()==DjVuDocument::BUNDLED ||
doc->get_doc_type()==DjVuDocument::INDIRECT)
{
GP<DjVmDir> dir = doc->get_djvm_dir();
ncomps = dir->get_files_num();
comp_ids.resize(ncomps - 1);
comp_flags.resize(ncomps - 1);
comp_files.resize(ncomps - 1);
int pageno = 0;
GPList<DjVmDir::File> flist = dir->get_files_list();
GPosition pos=flist;
for (int comp=0; comp<ncomps; ++pos, ++comp)
{
DjVmDir::File *file = flist[pos];
comp_ids[comp] = file->get_load_name();
comp_flags[comp] = 0;
if (file->is_page() && page_flags[pageno++])
comp_flags[comp] = 1;
}
}
else
{
ncomps = npages;
comp_flags.resize(ncomps - 1);
comp_files.resize(ncomps - 1);
for (int comp=0; comp<ncomps; ++comp)
comp_flags[comp] = page_flags[comp];
}
// Download
get_portcaster()->add_route(doc, this);
while (!mystop)
{
int comp;
int wanted = 0;
int loaded = 0;
int asked = 0;
for (comp=0; comp<ncomps; comp++)
{
int flags = comp_flags[comp];
if (flags > 2)
loaded += 1;
else if (flags < 2)
continue;
else if (!comp_files[comp]->is_data_present())
asked += 1;
else
{
comp_flags[comp] += 1;
mark_included_files(comp_files[comp]);
}
}
for (comp=0; comp<ncomps; comp++)
if (comp_flags[comp] > 0)
wanted += 1;
progress(loaded * 100 / wanted);
if (wanted == loaded)
break;
for (comp=0; comp<ncomps && asked < 2; comp++)
if (comp_flags[comp] == 1)
{
if (comp_ids.size() > 0)
comp_files[comp] = doc->get_djvu_file(comp_ids[comp]);
else
comp_files[comp] = doc->get_djvu_file(comp);
comp_flags[comp] += 1;
if (!comp_files[comp]->is_data_present())
asked += 1;
}
GMonitorLock lock(&monitor);
for (comp=0; comp<ncomps; comp++)
if (comp_flags[comp] == 2)
if (! comp_files[comp]->is_data_present())
{
monitor.wait();
break;
}
}
if (mystop)
G_THROW(DataPool::Stop);
// Saving!
GP<DjVmDoc> djvm;
if (! pages)
{
djvm = doc->get_djvm_doc();
}
else
{
djvm = DjVmDoc::create();
GP<DjVmDir> dir = doc->get_djvm_dir();
GPList<DjVmDir::File> flist = dir->get_files_list();
GPosition pos=flist;
int pageno = 0;
for (int comp=0; comp<ncomps; ++pos, ++comp)
{
if (flist[pos]->is_page())
pageno += 1;
if (comp_flags[comp])
{
GP<DjVmDir::File> f = new DjVmDir::File(*flist[pos]);
if (f->is_page() && f->get_save_name()==f->get_title())
f->set_title(GUTF8String(pageno));
GP<DjVuFile> file = comp_files[comp];
GP<DataPool> data = file->get_init_data_pool();
djvm->insert_file(f, data);
}
}
}
if (obs)
djvm->write(obs);
else if (odir.is_valid() && oname.length() > 0)
djvm->expand(odir, oname);
return DDJVU_JOB_OK;
}
ddjvu_job_t *
ddjvu_document_save(ddjvu_document_t *document, FILE *output,
int optc, const char * const * optv)
{
ddjvu_savejob_s *job = 0;
G_TRY
{
job = new ddjvu_savejob_s;
ref(job);
job->myctx = document->myctx;
job->mydoc = document;
bool indirect = false;
// parse options
while (optc>0)
{
GNativeString narg(optv[0]);
GUTF8String uarg = narg;
const char *s1 = (const char*)narg;
if (s1[0] == '-') s1++;
if (s1[0] == '-') s1++;
// separate arguments
if (!strncmp(s1, "page=", 5) ||
!strncmp(s1, "pages=", 6) )
{
if (job->pages.length())
complain(uarg,"multiple page specifications");
job->pages = uarg;
}
else if (!strncmp(s1, "indirect=", 9))
{
GURL oname = GURL::Filename::UTF8(s1 + 9);
job->odir = oname.base();
job->oname = oname.fname();
indirect = true;
}
else
{
complain(uarg, "Unrecognized option.");
}
// next option
optc -= 1;
optv += 1;
}
// go
if (!indirect)
job->obs = ByteStream::create(output, "wb", false);
else
job->obs = 0;
job->start();
}
G_CATCH(ex)
{
if (job)
unref(job);
job = 0;
ERROR1(document, ex);
}
G_ENDCATCH;
return job;
}
// ----------------------------------------
// S-Expressions (generic)
static miniexp_t
miniexp_status(ddjvu_status_t status)
{
if (status < DDJVU_JOB_OK)
return miniexp_dummy;
else if (status == DDJVU_JOB_STOPPED)
return miniexp_symbol("stopped");
else if (status > DDJVU_JOB_OK)
return miniexp_symbol("failed");
return miniexp_nil;
}
static void
miniexp_protect(ddjvu_document_t *document, miniexp_t expr)
{
{ // extra nesting for windows
for(miniexp_t p=document->protect; miniexp_consp(p); p=miniexp_cdr(p))
if (miniexp_car(p) == expr)
return;
}
if (miniexp_consp(expr) || miniexp_objectp(expr))
document->protect = miniexp_cons(expr, document->protect);
}
void
ddjvu_miniexp_release(ddjvu_document_t *document, miniexp_t expr)
{
miniexp_t q = miniexp_nil;
miniexp_t p = document->protect;
while (miniexp_consp(p))
{
if (miniexp_car(p) != expr)
q = p;
else if (q)
miniexp_rplacd(q, miniexp_cdr(p));
else
document->protect = miniexp_cdr(p);
p = miniexp_cdr(p);
}
}
// ----------------------------------------
// S-Expressions (outline)
static miniexp_t
outline_sub(const GP<DjVmNav> &nav, int &pos, int count)
{
GP<DjVmNav::DjVuBookMark> entry;
minivar_t p,q,s;
while (count > 0 && pos < nav->getBookMarkCount())
{
nav->getBookMark(entry, pos++);
q = outline_sub(nav, pos, entry->count);
s = miniexp_string((const char*)(entry->url));
q = miniexp_cons(s, q);
s = miniexp_string((const char*)(entry->displayname));
q = miniexp_cons(s, q);
p = miniexp_cons(q, p);
count--;
}
return miniexp_reverse(p);
}
miniexp_t
ddjvu_document_get_outline(ddjvu_document_t *document)
{
G_TRY
{
ddjvu_status_t status = document->status();
if (status != DDJVU_JOB_OK)
return miniexp_status(status);
DjVuDocument *doc = document->doc;
if (doc)
{
GP<DjVmNav> nav = doc->get_djvm_nav();
if (! nav)
return miniexp_nil;
minivar_t result;
int pos = 0;
result = outline_sub(nav, pos, nav->getBookMarkCount());
result = miniexp_cons(miniexp_symbol("bookmarks"), result);
miniexp_protect(document, result);
return result;
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return miniexp_status(DDJVU_JOB_FAILED);
}
// ----------------------------------------
// S-Expressions (text)
static struct zone_names_s {
const char *name;
DjVuTXT::ZoneType ztype;
char separator;
} zone_names[] = {
{ "page", DjVuTXT::PAGE, 0 },
{ "column", DjVuTXT::COLUMN, DjVuTXT::end_of_column },
{ "region", DjVuTXT::REGION, DjVuTXT::end_of_region },
{ "para", DjVuTXT::PARAGRAPH, DjVuTXT::end_of_paragraph },
{ "line", DjVuTXT::LINE, DjVuTXT::end_of_line },
{ "word", DjVuTXT::WORD, ' ' },
{ "char", DjVuTXT::CHARACTER, 0 },
{ 0, (DjVuTXT::ZoneType)0 ,0 }
};
static miniexp_t
pagetext_sub(const GP<DjVuTXT> &txt, DjVuTXT::Zone &zone,
DjVuTXT::ZoneType detail)
{
int zinfo;
for (zinfo=0; zone_names[zinfo].name; zinfo++)
if (zone.ztype == zone_names[zinfo].ztype)
break;
minivar_t p;
minivar_t a;
bool gather = zone.children.isempty();
{ // extra nesting for windows
for (GPosition pos=zone.children; pos; ++pos)
if (zone.children[pos].ztype > detail)
gather = true;
}
if (gather)
{
const char *data = (const char*)(txt->textUTF8) + zone.text_start;
int length = zone.text_length;
if (length>0 && data[length-1]==zone_names[zinfo].separator)
length -= 1;
a = miniexp_substring(data, length);
p = miniexp_cons(a, p);
}
else
{
for (GPosition pos=zone.children; pos; ++pos)
{
a = pagetext_sub(txt, zone.children[pos], detail);
p = miniexp_cons(a, p);
}
}
p = miniexp_reverse(p);
const char *s = zone_names[zinfo].name;
if (s)
{
p = miniexp_cons(miniexp_number(zone.rect.ymax), p);
p = miniexp_cons(miniexp_number(zone.rect.xmax), p);
p = miniexp_cons(miniexp_number(zone.rect.ymin), p);
p = miniexp_cons(miniexp_number(zone.rect.xmin), p);
p = miniexp_cons(miniexp_symbol(s), p);
return p;
}
return miniexp_nil;
}
miniexp_t
ddjvu_document_get_pagetext(ddjvu_document_t *document, int pageno,
const char *maxdetail)
{
G_TRY
{
ddjvu_status_t status = document->status();
if (status != DDJVU_JOB_OK)
return miniexp_status(status);
DjVuDocument *doc = document->doc;
if (doc)
{
document->pageinfoflag = true;
GP<DjVuFile> file = doc->get_djvu_file(pageno);
if (! file || ! file->is_data_present() )
return miniexp_dummy;
GP<ByteStream> bs = file->get_text();
if (! bs)
return miniexp_nil;
GP<DjVuText> text = DjVuText::create();
text->decode(bs);
GP<DjVuTXT> txt = text->txt;
if (! txt)
return miniexp_nil;
minivar_t result;
DjVuTXT::ZoneType detail = DjVuTXT::CHARACTER;
{ // extra nesting for windows
for (int i=0; zone_names[i].name; i++)
if (maxdetail && !strcmp(maxdetail, zone_names[i].name))
detail = zone_names[i].ztype;
}
result = pagetext_sub(txt, txt->page_zone, detail);
miniexp_protect(document, result);
return result;
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return miniexp_status(DDJVU_JOB_FAILED);
}
// ----------------------------------------
// S-Expressions (annotations)
// The difficulty here lies with the syntax of strings in annotation chunks.
// - Early versions of djvu only had one possible escape
// sequence (\") in annotation strings. All other characters
// are accepted literally until reaching the closing double quote.
// - Current versions of djvu understand the usual backslash escapes.
// All non printable ascii characters must however be escaped.
// This is a subset of the miniexp syntax.
// We first check if strings in the annotation chunk obey the modern syntax.
// The compatibility mode is turned on if they contain non printable ascii
// characters or illegal backslash sequences. Function <anno_getc()> then
// creates the proper escapes on the fly.
static struct {
const char *s;
char buf[8];
int blen;
int state;
bool compat;
bool eof;
} anno_dat;
static bool
anno_compat(const char *s)
{
int state = 0;
bool compat = false;
while (s && *s && !compat)
{
int i = (int)(unsigned char)*s++;
switch(state)
{
case 0:
if (i == '\"')
state = '\"';
break;
case '\"':
if (i == '\"')
state = 0;
else if (i == '\\')
state = '\\';
else if (isascii(i) && !isprint(i))
compat = true;
break;
case '\\':
if (!strchr("01234567abtnvfr\"\\",i))
compat = true;
state = '\"';
break;
}
}
return compat;
}
static int
anno_getc(void)
{
if (anno_dat.blen>0)
{
anno_dat.blen--;
char c = anno_dat.buf[0];
{ // extra nesting for windows
for (int i=0; i<anno_dat.blen; i++)
anno_dat.buf[i] = anno_dat.buf[i+1];
}
return c;
}
if (! *anno_dat.s)
return EOF;
int c = (int)(unsigned char)*anno_dat.s++;
if (anno_dat.compat)
{
switch (anno_dat.state)
{
case 0:
if (c == '\"')
anno_dat.state = '\"';
break;
case '\"':
if (c == '\"')
anno_dat.state = 0;
else if (c == '\\')
anno_dat.state = '\\';
else if (isascii(c) && !isprint(c))
{
sprintf(anno_dat.buf,"%03o", c);
anno_dat.blen = strlen(anno_dat.buf);
c = '\\';
}
break;
case '\\':
anno_dat.state = '\"';
if (c != '\"')
{
sprintf(anno_dat.buf,"\\%03o", c);
anno_dat.blen = strlen(anno_dat.buf);
c = '\\';
}
break;
}
}
return c;
}
static int
anno_ungetc(int c)
{
if (c == EOF)
return EOF;
if (anno_dat.blen>=(int)sizeof(anno_dat.buf))
return EOF;
{ // extra nesting for windows
for (int i=anno_dat.blen; i>0; i--)
anno_dat.buf[i] = anno_dat.buf[i-1];
}
anno_dat.blen += 1;
anno_dat.buf[0] = c;
return c;
}
static void
anno_sub(ByteStream *bs, miniexp_t &result)
{
// Read bs
GUTF8String raw;
char buffer[1024];
int length;
while ((length=bs->read(buffer, sizeof(buffer))))
raw += GUTF8String(buffer, length);
// Prepare
miniexp_t a;
anno_dat.s = (const char*)raw;
anno_dat.compat = anno_compat(anno_dat.s);
anno_dat.blen = 0;
anno_dat.state = 0;
anno_dat.eof = false;
int (*saved_getc)(void) = minilisp_getc;
int (*saved_ungetc)(int) = minilisp_ungetc;
// Process
minilisp_getc = anno_getc;
minilisp_ungetc = anno_ungetc;
while (* anno_dat.s )
if ((a = miniexp_read()) != miniexp_dummy)
result = miniexp_cons(a, result);
// Restore
minilisp_getc = saved_getc;
minilisp_ungetc = saved_ungetc;
}
static miniexp_t
get_bytestream_anno(GP<ByteStream> annobs)
{
if (! (annobs && annobs->size()))
return miniexp_nil;
GP<IFFByteStream> iff = IFFByteStream::create(annobs);
GUTF8String chkid;
minivar_t result;
while (iff->get_chunk(chkid))
{
GP<ByteStream> bs;
if (chkid == "ANTa")
bs = iff->get_bytestream();
else if (chkid == "ANTz")
bs = BSByteStream::create(iff->get_bytestream());
if (bs)
anno_sub(bs, result);
iff->close_chunk();
}
return miniexp_reverse(result);
}
static miniexp_t
get_file_anno(GP<DjVuFile> file)
{
// Make sure all data is present
if (! file || ! file->is_all_data_present())
{
if (file && file->is_data_present())
{
if (! file->are_incl_files_created())
file->process_incl_chunks();
if (! file->are_incl_files_created())
{
if (file->get_flags() & DjVuFile::STOPPED)
return miniexp_status(DDJVU_JOB_STOPPED);
return miniexp_status(DDJVU_JOB_FAILED);
}
}
return miniexp_dummy;
}
// Access annotation data
return get_bytestream_anno(file->get_merged_anno());
}
miniexp_t
ddjvu_document_get_pageanno(ddjvu_document_t *document, int pageno)
{
G_TRY
{
ddjvu_status_t status = document->status();
if (status != DDJVU_JOB_OK)
return miniexp_status(status);
DjVuDocument *doc = document->doc;
if (doc)
{
document->pageinfoflag = true;
minivar_t result = get_file_anno( doc->get_djvu_file(pageno) );
if (miniexp_consp(result))
miniexp_protect(document, result);
return result;
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return miniexp_status(DDJVU_JOB_FAILED);
}
miniexp_t
ddjvu_document_get_anno(ddjvu_document_t *document, int compat)
{
G_TRY
{
ddjvu_status_t status = document->status();
if (status != DDJVU_JOB_OK)
return miniexp_status(status);
DjVuDocument *doc = document->doc;
if (doc)
{
#if EXPERIMENTAL_DOCUMENT_ANNOTATIONS
// not yet implemented
GP<ByteStream> anno = doc->get_document_anno();
if (anno)
return get_bytestream_anno(anno);
#endif
if (compat)
{
// look for shared annotations
int doc_type = doc->get_doc_type();
if (doc_type != DjVuDocument::BUNDLED &&
doc_type != DjVuDocument::INDIRECT )
return miniexp_nil;
GP<DjVmDir> dir = doc->get_djvm_dir();
int filenum = dir->get_files_num();
GP<DjVmDir::File> fdesc;
for (int i=0; i<filenum; i++)
{
GP<DjVmDir::File> f = dir->pos_to_file(i);
if (!f->is_shared_anno())
continue;
if (fdesc)
return miniexp_nil;
fdesc = f;
}
if (fdesc)
{
GUTF8String id = fdesc->get_load_name();
return get_file_anno(doc->get_djvu_file(id));
}
}
return miniexp_nil;
}
}
G_CATCH(ex)
{
ERROR1(document, ex);
}
G_ENDCATCH;
return miniexp_status(DDJVU_JOB_FAILED);
}
/* ------ helpers for annotations ---- */
static const char *
simple_anno_sub(miniexp_t p, miniexp_t s, int i)
{
const char *result = 0;
while (miniexp_consp(p))
{
miniexp_t a = miniexp_car(p);
p = miniexp_cdr(p);
if (miniexp_car(a) == s)
{
miniexp_t q = miniexp_nth(i, a);
if (miniexp_symbolp(q))
result = miniexp_to_name(q);
}
}
return result;
}
const char *
ddjvu_anno_get_bgcolor(miniexp_t p)
{
return simple_anno_sub(p, miniexp_symbol("background"), 1);
}
const char *
ddjvu_anno_get_zoom(miniexp_t p)
{
return simple_anno_sub(p, miniexp_symbol("zoom"), 1);
}
const char *
ddjvu_anno_get_mode(miniexp_t p)
{
return simple_anno_sub(p, miniexp_symbol("mode"), 1);
}
const char *
ddjvu_anno_get_horizalign(miniexp_t p)
{
return simple_anno_sub(p, miniexp_symbol("align"), 1);
}
const char *
ddjvu_anno_get_vertalign(miniexp_t p)
{
return simple_anno_sub(p, miniexp_symbol("align"), 2);
}
miniexp_t *
ddjvu_anno_get_hyperlinks(miniexp_t annotations)
{
miniexp_t p;
miniexp_t s_maparea = miniexp_symbol("maparea");
int i = 0;
for (p = annotations; miniexp_consp(p); p = miniexp_cdr(p))
if (miniexp_caar(p) == s_maparea)
i += 1;
miniexp_t *k = (miniexp_t*)malloc((1+i)*sizeof(miniexp_t));
if (! k) return 0;
i = 0;
for (p = annotations; miniexp_consp(p); p = miniexp_cdr(p))
if (miniexp_caar(p) == s_maparea)
k[i++] = miniexp_car(p);
k[i] = 0;
return k;
}
static void
metadata_sub(miniexp_t p, GMap<miniexp_t,miniexp_t> &m)
{
miniexp_t s_metadata = miniexp_symbol("metadata");
while (miniexp_consp(p))
{
if (miniexp_caar(p) == s_metadata)
{
miniexp_t q = miniexp_cdar(p);
while (miniexp_consp(q))
{
miniexp_t a = miniexp_car(q);
q = miniexp_cdr(q);
if (miniexp_consp(a) &&
miniexp_symbolp(miniexp_car(a)) &&
miniexp_stringp(miniexp_cadr(a)) )
{
m[miniexp_car(a)] = miniexp_cadr(a);
}
}
}
p = miniexp_cdr(p);
}
}
miniexp_t *
ddjvu_anno_get_metadata_keys(miniexp_t p)
{
minivar_t l;
GMap<miniexp_t,miniexp_t> m;
metadata_sub(p, m);
int i = m.size();
miniexp_t *k = (miniexp_t*)malloc((1+i)*sizeof(miniexp_t));
if (! k) return 0;
i = 0;
{ // extra nesting for windows
for (GPosition p=m; p; ++p)
k[i++] = m.key(p);
}
k[i] = 0;
return k;
}
const char *
ddjvu_anno_get_metadata(miniexp_t p, miniexp_t key)
{
GMap<miniexp_t,miniexp_t> m;
metadata_sub(p, m);
if (m.contains(key))
return miniexp_to_str(m[key]);
return 0;
}
const char *
ddjvu_anno_get_xmp(miniexp_t p)
{
miniexp_t s = miniexp_symbol("xmp");
while (miniexp_consp(p))
{
miniexp_t a = miniexp_car(p);
p = miniexp_cdr(p);
if (miniexp_car(a) == s)
{
miniexp_t q = miniexp_nth(1, a);
if (miniexp_stringp(q))
return miniexp_to_str(q);
}
}
return 0;
}
// ----------------------------------------
// Backdoors
GP<DjVuImage>
ddjvu_get_DjVuImage(ddjvu_page_t *page)
{
return page->img;
}
GP<DjVuDocument>
ddjvu_get_DjVuDocument(ddjvu_document_t *document)
{
return document->doc;
}
| zoozooll/MyExercise | orion-viewer-master/orion-viewer/jni/djvu/libdjvu/ddjvuapi.cpp | C++ | apache-2.0 | 102,863 |
//
// DoraemonMockApiCell.h
// DoraemonKit
//
// Created by didi on 2019/11/15.
//
#import "DoraemonMockBaseCell.h"
NS_ASSUME_NONNULL_BEGIN
@interface DoraemonMockApiCell : DoraemonMockBaseCell
@end
NS_ASSUME_NONNULL_END
| didi/DoraemonKit | iOS/DoraemonKit/Src/Core/Plugin/Platform/Mock/View/List/Cell/DoraemonMockApiCell.h | C | apache-2.0 | 229 |
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application;
/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),
));
/*
|--------------------------------------------------------------------------
| Bind Paths
|--------------------------------------------------------------------------
|
| Here we are binding the paths configured in paths.php to the app. You
| should not be changing these here. If you need to change these you
| may do so within the paths.php file and they will be bound here.
|
*/
$app->bindInstallPaths(require __DIR__.'/paths.php');
/*
|--------------------------------------------------------------------------
| Load The Application
|--------------------------------------------------------------------------
|
| Here we will load this Illuminate application. We will keep this in a
| separate location so we can isolate the creation of an application
| from the actual running of the application with a given request.
|
*/
$framework = $app['path.base'].'/vendor/laravel/framework/src';
require $framework.'/Illuminate/Foundation/start.php';
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| kornvollis/smaragd | bootstrap/start.php | PHP | apache-2.0 | 2,317 |
import difflib
import inflect
import itertools
import logging
import netaddr
import os
import re
import toposort
import yaml
import hotcidr.state
def inflect_a(s, p=inflect.engine()):
x = p.plural(s)
if p.compare(s, x) == 'p:s':
return s
return p.a(s)
logging.basicConfig(format='%(levelname)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
class Validator(object):
logger = logging.getLogger('validation')
info = logger.warn
warn = logger.warn
error = logger.error
fatal = logger.fatal
def load(self, x):
if x not in self.files:
try:
with open(os.path.join(self.rootdir, x)) as f:
try:
self.files[x] = hotcidr.state.load(f)
except yaml.YAMLError:
self.fatal("Invalid YAML file %s" % x)
except IOError:
self.fatal("Could not read file %s" % x)
return self.files[x]
def register_check(self, f):
if f not in self.checks:
self.checks.append(f)
else:
raise Exception("Function %s is already registered" % f.__name__)
def register_checks(self, *fs):
for f in fs:
self.register_check(f)
required_map = {}
def validate(self, wrap=True):
# TODO: spawn multiple processes
l = {f: Validator.required_map[f]
if f in Validator.required_map
else set()
for f in self.checks}
for f in toposort.toposort_flatten(l, sort=False):
if wrap:
try:
f(self)
except:
self.fatal("Unexpected exception raised by %s" %
f.__name__)
raise
else:
f(self)
def __init__(self, rootdir):
self.rootdir = rootdir
self.checks = []
self.files = {}
def has_rules(g):
for i in g:
if isinstance(i, tuple):
if len(i) > 1 and 'rules' in i[1]:
yield i
elif 'rules' in i:
yield i
def requires(*a):
def decorator(f):
Validator.required_map[f] = set(a)
return f
return decorator
def load_groups(self, forced=False):
if forced or not hasattr(self, 'groups'):
groupsdir = os.path.join(self.rootdir, 'groups')
groups = os.listdir(groupsdir)
self.groups = {}
for x in groups:
if os.path.isfile(os.path.join(groupsdir, x)):
if x.endswith('.yaml'):
self.groups[x[:-5]] = self.load(os.path.join('groups', x))
def load_boxes(self, forced=False):
if forced or not hasattr(self, 'boxes'):
self.boxes = self.load('boxes.yaml')
@requires(load_groups, load_boxes)
def find_unused_groups(self):
#TODO: include groups used in 'location' field
used = set(itertools.chain(*(b['groups'] for b in self.boxes.values()
if 'groups' in b)))
for g in set(self.groups.keys()) - used:
self.info("Group %s is unused" % g)
@requires(load_groups, load_boxes)
def validate_groups(self):
used = set(itertools.chain(*(b['groups'] for b in self.boxes.values()
if 'groups' in b)))
valid_groups = set(self.groups.keys())
for g in used - valid_groups:
guess = difflib.get_close_matches(g, valid_groups)
if guess:
guess = " (Did you mean %s?)" % guess[0]
else:
guess = ""
self.fatal("%s is not defined%s" % (g, guess))
@requires(load_groups)
def validate_group_names(self):
valid_chars = set(
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
' ._-:/()#,@[]+=&;{}!$*'
)
for name in self.groups.keys():
if any(c not in valid_chars for c in name):
self.fatal("%s is not a valid group name" % name)
@requires(load_boxes)
def validate_aws_instance_id(self):
for name in self.boxes.keys():
if not re.match(r'^i\-[0-9a-f]{8}$', name):
self.fatal("Instance ID %s is not a valid AWS instance ID" % name)
@requires(load_groups)
def validate_aws_group_id(self):
seen = {}
for group_name, group in self.groups.items():
if 'id' in group:
name = group['id']
if not re.match(r'^sg\-[0-9a-f]{8}$', name):
self.fatal("%s has an invalid AWS group ID" % group_name)
elif name in seen:
if seen[name]:
self.fatal("%s has a duplicate AWS group ID" % seen[name])
seen[name] = False
self.fatal("%s has a duplicate AWS group ID" % group_name)
else:
seen[name] = group_name
@requires(load_groups)
def validate_protocols(self):
for group_name, group in has_rules(self.groups.iteritems()):
for rule_num, rule in enumerate(group['rules'], 1):
if 'protocol' not in rule:
self.error("Rule %d in %s is missing a protocol" %
(rule_num, group_name))
elif rule['protocol'] == '-1':
self.error("Rule %d in %s has an invalid protocol" %
(rule_num, group_name))
@requires(load_groups)
def validate_ports(self):
#TODO: handle ICMP fromport
def port(x, default=-1):
try:
r = int(x)
if 1 <= r <= 65535:
return r
except ValueError:
pass
for group_name, group in has_rules(self.groups.iteritems()):
for rule_num, rule in enumerate(group['rules'], 1):
valid = True
if 'fromport' not in rule:
self.error("Rule %d in %s is missing a fromport" %
(rule_num, group_name))
valid = False
if 'toport' not in rule:
self.error("Rule %d in %s is missing a toport" %
(rule_num, group_name))
valid = False
if valid:
fromport = port(rule['fromport'])
toport = port(rule['toport'])
valid = True
if not fromport:
self.error("Rule %d in %s has an invalid fromport" %
(rule_num, group_name))
valid = False
if not toport:
self.error("Rule %d in %s has an invalid toport" %
(rule_num, group_name))
valid = False
if valid:
if fromport > toport:
self.error("Rule %d in %s has an invalid port range" %
(rule_num, group_name))
elif (toport - fromport) >= 100:
self.warn("Rule %d in %s has a large port range" %
(rule_num, group_name))
@requires(load_groups)
def validate_rule_fields(self):
for group_name, group in has_rules(self.groups.iteritems()):
for rule_num, rule in enumerate(group['rules'], 1):
for field in ('description',):
if field not in rule:
self.warn("Rule %d in %s is missing %s" %
(rule_num, group_name, inflect_a(field)))
@requires(load_groups)
def validate_group_fields(self):
for group_name, group in self.groups.iteritems():
for field in ('description', 'rules'):
if field not in group:
self.warn("%s is missing %s" % (group_name, inflect_a(field)))
@requires(load_boxes)
def validate_instance_fields(self):
for box_id, box in self.boxes.iteritems():
for field in ('ip', 'domain', 'groups'):
if field not in box:
self.warn("Box %s is missing %s" %
(box_id, inflect_a(field)))
@requires(load_groups)
def validate_locations(self):
valid_groups = set(self.groups.keys())
for group_name, group in has_rules(self.groups.iteritems()):
for rule_num, rule in enumerate(group['rules'], 1):
if 'location' in rule:
if rule['location'] not in valid_groups:
try:
ip = netaddr.IPNetwork(rule['location'])
if str(ip.cidr) != rule['location']:
self.warn("Location for rule %d in %s "
"will be interpreted as %s" %
(rule_num, group_name, ip.cidr))
except netaddr.AddrFormatError:
self.error("Rule %d in %s has an invalid location" %
(rule_num, group_name))
else:
self.error("Rule %d in %s is missing a location" %
(rule_num, group_name))
| ViaSat/hotcidr | HotCIDR/hotcidr/validation.py | Python | apache-2.0 | 8,940 |
package manipulators
/** NgramSplitter splits plain strings into ngrams and provides utilities for calculating min overlap and search range
*
* @constructor create list of ngrams
* @param plainstr Original string
*/
class NgramSplitter(plainstr: String) {
val str = plainstr;
var grams = List[String]();
/*
* Splits string to ngrams
*/
def getChar(index:Int):Char = {
if (index < 0 || index >= str.length) '$'
else {
val s = str charAt index
if (s == ' ') '_'
else s
}
}
// Generates ngrams
def generate_ngrams():List[String] = {
var s = "";
for( i <- 1 to str.length+2) {
s = ""
for (idx <- i-3 to i-1) s = s + getChar(idx)
grams = grams ::: List(s);
}
grams
}
// Returns all ngrams as a List
def ngrams():List[String] = {
grams
}
// Return search range with threshold a
// min: a^2 * |X|
// max: |X| / a^2
def search_range(a:Double):(Int, Int) = {
((a*a*grams.length).toInt, (grams.length/(a*a)).toInt)
}
def min_overlap(a:Double, l:Int):Int = {
(a * Math.sqrt(grams.length * l)).toInt
}
} | theikkila/fuzzydb | src/main/scala/manipulators/NgramSplitter.scala | Scala | apache-2.0 | 1,061 |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.util;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.spi.InternalCompletableFuture;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.util.ExceptionUtil.sneakyThrow;
/**
* Generic implementation of a completed {@link InternalCompletableFuture}.
*/
public class SimpleCompletedFuture<E> implements InternalCompletableFuture<E> {
private final Object result;
/**
* Creates a completed future with the given result. The result can be
* null.
*
* <p>Note: If the result is an instance of Throwable, this future will be
* completed exceptionally. That is, {@link #get} will throw the exception
* rather than return it.
*/
public SimpleCompletedFuture(E result) {
this.result = result;
}
public SimpleCompletedFuture(Throwable exceptionalResult) {
this.result = exceptionalResult;
}
@SuppressWarnings("unchecked")
@Override
public E join() {
if (result instanceof Throwable) {
sneakyThrow((Throwable) result);
}
return (E) result;
}
@Override
public boolean complete(Object value) {
return false;
}
@SuppressWarnings("unchecked")
@Override
public void andThen(ExecutionCallback<E> callback) {
if (result instanceof Throwable) {
callback.onFailure((Throwable) result);
} else {
callback.onResponse((E) result);
}
}
@Override
public void andThen(final ExecutionCallback<E> callback, Executor executor) {
executor.execute(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
if (result instanceof Throwable) {
callback.onFailure((Throwable) result);
} else {
callback.onResponse((E) result);
}
}
});
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return result instanceof CancellationException;
}
@Override
public boolean isDone() {
return true;
}
@SuppressWarnings("unchecked")
@Override
public E get() throws ExecutionException {
if (result instanceof Throwable) {
throw new ExecutionException((Throwable) result);
}
return (E) result;
}
@Override
public E get(long timeout, TimeUnit unit) throws ExecutionException {
return get();
}
}
| tufangorel/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/SimpleCompletedFuture.java | Java | apache-2.0 | 3,386 |
/*
Derby - Class
org.apache.derbyTesting.functionTests.tests.jdbcapi.AuthenticationTest
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.derbyTesting.functionTests.tests.jdbcapi;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Locale;
import java.util.Properties;
import javax.sql.DataSource;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Tests authentication and connection level authorization.
*
*/
public class AuthenticationTest extends BaseJDBCTestCase {
private static final String PASSWORD_SUFFIX = "suf2ix";
private static final String USERS[] =
{"APP","dan","kreg","jeff","ames","jerry","francois","jamie","howardR",
"\"eVe\"","\"fred@derby.com\"", "\"123\"" };
private static final String zeus = "\u0396\u0395\u03A5\u03A3";
private static final String apollo = "\u0391\u09A0\u039F\u039B\u039B\u039A\u0390";
private static final String BUILTIN_ALGO_PROP =
"derby.authentication.builtin.algorithm";
private static final String USER_PREFIX = "derby.user.";
private static final String NO_SUCH_ALGO = "XBCXW";
/** Creates a new instance of the Test */
public AuthenticationTest(String name) {
super(name);
}
/**
* Ensure all connections are not in auto commit mode.
*/
protected void initializeConnection(Connection conn) throws SQLException {
conn.setAutoCommit(false);
}
public static Test suite() {
TestSuite suite = new TestSuite("AuthenticationTest");
suite.addTest(baseSuite("AuthenticationTest:embedded"));
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite("AuthenticationTest:client")));
return suite;
}
public static Test baseSuite(String name) {
TestSuite suite = new TestSuite("AuthenticationTest");
Test test = new AuthenticationTest(
"testConnectShutdownAuthentication");
setBaseProps(suite, test);
test = new AuthenticationTest("testUserCasing");
setBaseProps(suite, test);
test = new AuthenticationTest("testUserFunctions");
setBaseProps(suite, test);
test = new AuthenticationTest("testNotFullAccessUsers");
setBaseProps(suite, test);
test = new AuthenticationTest("testUserAccessRoutines");
setBaseProps(suite, test);
test = new AuthenticationTest(
"testChangePasswordAndDatabasePropertiesOnly");
setBaseProps(suite, test);
// only part of this fixture runs with network server / client
test = new AuthenticationTest("testGreekCharacters");
setBaseProps(suite, test);
test = new AuthenticationTest("testSystemShutdown");
setBaseProps(suite, test);
test = new AuthenticationTest("testDefaultHashAlgorithm");
setBaseProps(suite, test);
// The test cases below test the configurable hash authentication
// mechanism added in DERBY-4483. Set the property that specifies the
// hash algorithm to some valid value for these tests. Not all tests
// depend on the property being set prior to their invocation, but by
// setting it in a decorator we ensure that it will be automatically
// cleared on tear down, so that it will be safe for all of these tests
// to change the property without worrying about resetting it later.
Properties confHashProps = new Properties();
confHashProps.setProperty(BUILTIN_ALGO_PROP, "MD5");
test = new AuthenticationTest("testVariousBuiltinAlgorithms");
setBaseProps(suite, test, confHashProps);
test = new AuthenticationTest("testNoCollisionsWithConfigurableHash");
setBaseProps(suite, test, confHashProps);
test = new AuthenticationTest("testInvalidAlgorithmName");
setBaseProps(suite, test, confHashProps);
// This test needs to run in a new single use database as we're setting
// a number of properties
return TestConfiguration.singleUseDatabaseDecorator(suite);
}
protected static void setBaseProps(TestSuite suite, Test test)
{
setBaseProps(suite, test, null);
}
private static void setBaseProps(
TestSuite suite, Test test, Properties extraDbProps)
{
// Use DatabasePropertyTestSetup.builtinAuthentication decorator
// to set the user properties required by this test (and shutdown
// the database for the property to take effect).
// DatabasePropertyTestSetup uses SYSCS_SET_DATABASE_PROPERTY
// so that is database level setting.
// Additionally use DatabasePropertyTestSetup to add some
// possibly useful settings
// Finally SystemPropertyTestSetup sets up system level users
Properties props = new Properties();
props.setProperty("derby.infolog.append", "true");
props.setProperty("derby.debug.true", "AuthenticationTrace");
if (extraDbProps != null) {
props.putAll(extraDbProps);
}
Properties sysprops = new Properties();
sysprops.put("derby.user.system", "admin");
sysprops.put("derby.user.mickey", "mouse");
test = DatabasePropertyTestSetup.builtinAuthentication(test,
USERS, PASSWORD_SUFFIX);
test = new DatabasePropertyTestSetup (test, props, true);
suite.addTest(new SystemPropertyTestSetup (test, sysprops));
}
protected void setUp() throws Exception {
setDatabaseProperty("derby.database.defaultConnectionMode",
null, getConnection());
setDatabaseProperty("derby.database.readOnlyAccessUsers",
null, getConnection());
setDatabaseProperty("derby.database.fullAccessUsers",
null, getConnection());
commit();
}
protected void tearDown() throws Exception {
removeSystemProperty("derby.connection.requireAuthentication");
removeSystemProperty("derby.user." +apollo);
super.tearDown();
}
/**
* Test how user names behave with casing.
* @throws SQLException
*/
public void testUserCasing() throws SQLException
{
for (int i = 0; i < USERS.length; i++)
{
String jdbcUserName = USERS[i];
boolean delimited = jdbcUserName.charAt(0) == '"';
String normalUserName;
if (delimited)
{
normalUserName = jdbcUserName.substring(1,
jdbcUserName.length() - 1);
}
else
{
normalUserName = jdbcUserName.toUpperCase(Locale.ENGLISH);
}
String password = USERS[i] + PASSWORD_SUFFIX;
userCasingTest(jdbcUserName, normalUserName, password);
if (!delimited)
{
if (!normalUserName.equals(jdbcUserName))
{
// Test connecting via the normalized name
// but only if it wasn't already tested.
// E.g. connect as "DAN" for user DAN as opposed
// to the user being defined as dan (regular identifier).
// DERBY-3150 disable this test until bug is fixed.
//userCasingTest(normalUserName, normalUserName, password);
}
// Test with the normalized name quoted as a delimited identifer.
// E.g. connect as "DAN" for user DAN
// DERBY-3150 disable this test until bug is fixed.
// userCasingTest("\"" + normalUserName + "\"",
// normalUserName, password);
}
}
// Now test that setting the user connection authorizaton
// with the various names works correctly. Use the first user
// to set the access on others to avoid setting a user to read-only
// and then not being able to reset it.
PreparedStatement psGetAccess = prepareStatement(
"VALUES SYSCS_UTIL.SYSCS_GET_USER_ACCESS(?)");
CallableStatement csSetAccess = prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_USER_ACCESS(?, ?)");
setDatabaseProperty("derby.database.fullAccessUsers",
USERS[0], getConnection());
setDatabaseProperty("derby.database.readOnlyAccessUsers",
null, getConnection());
commit();
// Yes - skip the first user, see above.
for (int i = 1; i < USERS.length; i++)
{
String jdbcUserName = USERS[i];
boolean delimited = jdbcUserName.charAt(0) == '"';
String normalUserName;
if (delimited)
{
normalUserName = jdbcUserName.substring(1,
jdbcUserName.length() - 1);
}
else
{
normalUserName = jdbcUserName.toUpperCase(Locale.ENGLISH);
}
String password = USERS[i] + PASSWORD_SUFFIX;
// Set the access with the database property
setDatabaseProperty("derby.database.readOnlyAccessUsers",
jdbcUserName, getConnection());
commit();
Connection connUser = openDefaultConnection(jdbcUserName, password);
// DERBY-2738 (network client always returns false for isReadOnly)
if (usingEmbedded())
assertTrue(jdbcUserName + ":isReadOnly()",
connUser.isReadOnly());
connUser.close();
psGetAccess.setString(1, normalUserName);
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(),
"READONLYACCESS");
commit();
// clear the property.
setDatabaseProperty("derby.database.readOnlyAccessUsers",
null, getConnection());
commit();
// Test it was reset back
connUser = openDefaultConnection(jdbcUserName, password);
assertFalse(connUser.isReadOnly());
connUser.close();
psGetAccess.setString(1, normalUserName);
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(),
"FULLACCESS");
commit();
// Set to be read-only via the procedure which uses
// the normal user name.
csSetAccess.setString(1, normalUserName);
csSetAccess.setString(2, "READONLYACCESS");
csSetAccess.executeUpdate();
commit();
connUser = openDefaultConnection(jdbcUserName, password);
// DERBY-2738 (network client always returns false for isReadOnly)
if (usingEmbedded())
assertTrue(jdbcUserName + ":isReadOnly()",
connUser.isReadOnly());
connUser.close();
psGetAccess.setString(1, normalUserName);
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(),
"READONLYACCESS");
commit();
}
}
/**
* Test the user casing obtaining connections a variety of ways.
* @param jdbcUserName User name to be used to obtain the connection via JDBC
* @param normalUserName Normalized form of the user connection.
* @param password Password for the user.
* @throws SQLException
*/
private void userCasingTest(String jdbcUserName, String normalUserName,
String password) throws SQLException
{
// Default test mechanism to get a connection.
userCasingTest(jdbcUserName, normalUserName,
openDefaultConnection(jdbcUserName, password));
DataSource ds = JDBCDataSource.getDataSource();
// DataSource using explict user
userCasingTest(jdbcUserName, normalUserName,
ds.getConnection(jdbcUserName, password));
JDBCDataSource.setBeanProperty(ds, "user", jdbcUserName);
JDBCDataSource.setBeanProperty(ds, "password", password);
userCasingTest(jdbcUserName, normalUserName,
ds.getConnection());
}
/**
*
* @param jdbcUserName User name as passed into the JDBC connection request.
* @param normalUserName Normalized user name.
* @param connUser Connection for the user, closed by this method.
* @throws SQLException
*/
private void userCasingTest(String jdbcUserName, String normalUserName,
Connection connUser) throws SQLException
{
assertNormalUserName(normalUserName, connUser);
// DatabaseMetaData.getUserName() returns the user name used
// to make the request via JDBC.
assertEquals("DatabaseMetaData.getUserName()",
jdbcUserName, connUser.getMetaData().getUserName());
Statement s = connUser.createStatement();
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_USER_ACCESS(" +
"CURRENT_USER, 'FULLACCESS')");
s.close();
JDBC.cleanup(connUser);
}
/**
* Assert that the user name returned by various mechanisms
* matches the normal user name.
* @param normalUserName
* @param connUser
* @throws SQLException
*/
private void assertNormalUserName(String normalUserName, Connection connUser)
throws SQLException
{
Statement s = connUser.createStatement();
JDBC.assertSingleValueResultSet(s.executeQuery("VALUES CURRENT_USER"),
normalUserName);
JDBC.assertSingleValueResultSet(s.executeQuery("VALUES SESSION_USER"),
normalUserName);
JDBC.assertSingleValueResultSet(s.executeQuery("VALUES {fn user()}"),
normalUserName);
s.close();
}
// roughly based on old functionTests test users.sql, except that
// test used 2 databases. Possibly that was on the off-chance that
// a second database would not work correctly - but that will not
// be tested now.
public void testConnectShutdownAuthentication() throws SQLException {
String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
// check connections while fullAccess (default) is set
// note that builtinAuthentication has been set, as well as
// authentication=true.
// first try connection without user password
assertConnectionFail(dbName);
assertConnectionOK(dbName, "system", ("admin"));
assertConnectionWOUPOK(dbName, "system", ("admin"));
assertConnectionOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertConnectionWOUPOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
// try shutdown as non-owner
assertShutdownOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertConnectionOK(dbName, "system", ("admin"));
assertShutdownWOUPOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertConnectionOK(dbName, "system", ("admin"));
assertShutdownOK(dbName, "system", "admin");
assertConnectionOK(dbName, "system", ("admin"));
assertShutdownWOUPOK(dbName, "system", "admin");
assertConnectionOK(dbName, "system", ("admin"));
// try shutdown as owner
assertShutdownUsingConnAttrsOK(dbName, "APP", ("APP" + PASSWORD_SUFFIX));
// ensure that a password is encrypted
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
Statement stmt = conn1.createStatement();
ResultSet rs = stmt.executeQuery(
"values SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.user.dan')");
rs.next();
assertNotSame(("dan"+PASSWORD_SUFFIX), rs.getString(1));
conn1.commit();
conn1.close();
// specify full-access users.
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.fullAccessUsers",
"APP,system,nomen,francois,jeff", conn1);
setDatabaseProperty(
"derby.database.defaultConnectionMode","NoAccess", conn1);
conn1.commit();
conn1.close();
// check the system wide user
assertConnectionOK(dbName, "system", "admin");
// check the non-existent, but allowed user
assertConnectionFail("08004", dbName, "nomen", "nescio");
assertConnectionWOUPFail("08004", dbName, "nomen", "nescio");
// attempt to shutdown db as one of the allowed users, but not db owner
assertShutdownOK(dbName, "francois", ("francois" + PASSWORD_SUFFIX));
// attempt shutdown as db owner
assertConnectionOK(dbName, "system", "admin");
assertShutdownWOUPOK(dbName, "APP", ("APP" + PASSWORD_SUFFIX));
// check simple connect ok as another allowed user, also revive db
assertConnectionOK(dbName, "jeff", ("jeff" + PASSWORD_SUFFIX));
// but dan wasn't on the list
assertConnectionFail("08004", dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertShutdownFail("08004", dbName, "dan", ("dan" + PASSWORD_SUFFIX));
// now change fullAccessUsers & test again
conn1 =
openDefaultConnection("francois", ("francois" + PASSWORD_SUFFIX));
setDatabaseProperty("derby.database.fullAccessUsers",
"jeff,dan,francois,jamie", conn1);
conn1.commit();
conn1.close();
assertConnectionOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertShutdownOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
assertConnectionOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
// but dbo was not on list...
assertShutdownFail("08004", dbName, "APP", ("APP" + PASSWORD_SUFFIX));
// now add dbo back in...
conn1 = openDefaultConnection("francois", ("francois" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","NoAccess", conn1);
setDatabaseProperty(
"derby.database.fullAccessUsers",
"APP,jeff,dan,francois,jamie", conn1);
conn1.commit();
conn1.close();
// Invalid logins
// bad user
assertConnectionFail("08004", dbName, "badUser", "badPwd");
// just checking that it's still not working if we try again
assertConnectionFail("08004", dbName, "badUser", "badPwd");
// system is not on the list...
assertConnectionFail("08004", dbName, "system", "admin");
// dan's on the list, but this isn't the pwd
assertConnectionFail("08004", dbName, "dan", "badPwd");
assertConnectionFail("08004", dbName, "jamie", ("dan" + PASSWORD_SUFFIX));
// check some shutdowns
assertShutdownFail("08004", dbName, "system", "admin");
assertShutdownFail("08004", dbName, "badUser", "badPwd");
assertShutdownFail("08004", dbName, "dan", "badPwd");
assertShutdownFail("08004", dbName, "badUser", ("dan" + PASSWORD_SUFFIX));
// try some system shutdowns. Note, that all these work, because
// we have not set require authentication at system level.
// try system shutdown with wrong user - should work
assertSystemShutdownOK("", "badUser", ("dan" + PASSWORD_SUFFIX));
openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX)).close(); // revive
// with 'allowed' user but bad pwd - will succeed
assertSystemShutdownOK("", "dan", ("jeff" + PASSWORD_SUFFIX));
openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX)).close(); // revive
// dbo, but bad pwd - will succeed
assertSystemShutdownOK("", "APP", ("POO"));
openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX)).close(); // revive
// allowed user but not dbo - will also succeed
assertSystemShutdownOK("", "dan", ("dan" + PASSWORD_SUFFIX));
openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX)).close(); // revive
// expect Derby system shutdown, which gives XJ015 error.
assertSystemShutdownOK("", "APP", ("APP" + PASSWORD_SUFFIX));
// so far so good. set back security properties
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
conn1.commit();
stmt.close();
conn1.close();
}
// Experiment using USER, CURRENT_USER, etc.
// also tests actual write activity
public void testUserFunctions() throws SQLException
{
// use valid user/pwd to set the full accessusers.
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.fullAccessUsers",
"francois,jeff,ames,jerry,jamie,dan,system", conn1);
setDatabaseProperty(
"derby.database.defaultConnectionMode","NoAccess", conn1);
conn1.commit();
// we should still be connected as dan
Statement stmt = conn1.createStatement();
assertUpdateCount(stmt, 0,
"create table APP.t1(c1 varchar(30) check (UPPER(c1) <> 'JAMIE'))");
assertUpdateCount(stmt, 1, "insert into APP.t1 values USER");
conn1.commit();
stmt.close();
conn1.close();
useUserValue(1, "jeff", "insert into APP.t1 values CURRENT_USER");
useUserValue(1, "ames", "insert into APP.t1 values SESSION_USER");
useUserValue(1, "jerry", "insert into APP.t1 values {fn user()}");
assertUserValue(new String[] {"DAN","JEFF","AMES","JERRY"},
"dan", "select * from APP.t1");
// attempt some usage in where clause
useUserValue(1,
"dan", "update APP.t1 set c1 = 'edward' where c1 = USER");
assertUserValue(new String[] {"JEFF"},"jeff",
"select * from APP.t1 where c1 like CURRENT_USER");
useUserValue(1, "ames",
"update APP.t1 set c1 = 'sema' where SESSION_USER = c1");
useUserValue(1, "jerry",
"update APP.t1 set c1 = 'yrrej' where c1 like {fn user()}");
assertUserValue(new String[] {"edward","JEFF","sema","yrrej"},
"dan", "select * from APP.t1");
useUserValue(4, "francois", "update APP.T1 set c1 = USER");
assertUserValue(
new String[] {"FRANCOIS","FRANCOIS","FRANCOIS","FRANCOIS"},
"dan", "select * from APP.t1");
// check that attempt to insert 'jamie' gives a check violation
conn1 = openDefaultConnection("jamie", ("jamie" + PASSWORD_SUFFIX));
stmt = conn1.createStatement();
try {
stmt.execute("insert into APP.t1 values CURRENT_USER");
} catch (SQLException sqle) {
assertSQLState("23513", sqle);
}
stmt.close();
conn1.rollback();
conn1.close();
// Note: there is not much point in attempting to write with an invalid
// user, that's already tested in the testConnectionShutdown fixture
// reset
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
stmt = conn1.createStatement();
assertUpdateCount(stmt, 0, "drop table APP.t1");
conn1.commit();
stmt.close();
conn1.close();
}
public void testChangePasswordAndDatabasePropertiesOnly()
throws SQLException
{
String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
// use valid user/pwd to set the full accessusers.
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty("derby.database.fullAccessUsers",
"dan,jeff,system", conn1);
setDatabaseProperty(
"derby.database.defaultConnectionMode","NoAccess", conn1);
setDatabaseProperty(
"derby.database.requireAuthentication","true", conn1);
conn1.commit();
// check the system wide user
assertConnectionOK(dbName, "system", "admin");
assertConnectionFail("08004", dbName, "system", "otherSysPwd");
assertConnectionOK(dbName, "jeff", ("jeff" + PASSWORD_SUFFIX));
assertConnectionFail("08004", dbName, "jeff", "otherPwd");
setDatabaseProperty("derby.user.jeff", "otherPwd", conn1);
conn1.commit();
// should have changed ok.
assertConnectionOK(dbName, "jeff", "otherPwd");
// note: if we do this:
// setDatabaseProperty("derby.user.system", "scndSysPwd", conn1);
// conn1.commit();
// i.e. adding the same user (but different pwd) at database level,
// then we cannot connect anymore using that user name, not with
// either password.
// force database props only
setDatabaseProperty(
"derby.database.propertiesOnly","true", conn1);
conn1.commit();
// now, should not be able to logon as system user
assertConnectionFail("08004", dbName, "system", "admin");
// reset propertiesOnly
setDatabaseProperty(
"derby.database.propertiesOnly","false", conn1);
conn1.commit();
conn1.close();
assertConnectionOK(dbName, "system", "admin");
// try changing system's pwd
setSystemProperty("derby.user.system", "thrdSysPwd");
// can we get in as system user with changed pwd
assertConnectionOK(dbName, "system", "thrdSysPwd");
// reset
// first change system's pwd back
setSystemProperty("derby.user.system", "admin");
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
setDatabaseProperty(
"derby.database.propertiesOnly","false", conn1);
conn1.commit();
conn1.close();
}
public void testNotFullAccessUsers() throws SQLException
{
// use valid user/pwd to set the full accessusers.
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
// Test duplicates on the list of users
try {
setDatabaseProperty("derby.database.fullAccessUsers",
"dan,jamie,dan", conn1);
fail("Duplicate allowed on derby.database.fullAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.fullAccessUsers",
"dan,jamie,DaN", conn1);
fail("Duplicate allowed on derby.database.fullAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.fullAccessUsers",
"dan,jamie,\"DAN\"", conn1);
fail("Duplicate allowed on derby.database.fullAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.fullAccessUsers",
"\"dan\",jamie,\"dan\"", conn1);
fail("Duplicate allowed on derby.database.fullAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.readOnlyAccessUsers",
"dan,jamie,dan", conn1);
fail("Duplicate allowed on derby.database.readOnlyAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.readOnlyAccessUsers",
"dan,jamie,DaN", conn1);
fail("Duplicate allowed on derby.database.readOnlyAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.readOnlyAccessUsers",
"dan,jamie,\"DAN\"", conn1);
fail("Duplicate allowed on derby.database.readOnlyAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
try {
setDatabaseProperty("derby.database.readOnlyAccessUsers",
"\"dan\",jamie,\"dan\"", conn1);
fail("Duplicate allowed on derby.database.readOnlyAccessUsers");
} catch (SQLException e) {
assertSQLState("4250D", e);
}
setDatabaseProperty("derby.database.fullAccessUsers",
"dan,jamie,system", conn1);
// cannot set a user to both full and readonly access...
assertFailSetDatabaseProperty(
"derby.database.readOnlyAccessUsers", "jamie", conn1);
setDatabaseProperty(
"derby.database.readOnlyAccessUsers", "ames,mickey", conn1);
setDatabaseProperty(
"derby.database.defaultConnectionMode","NoAccess", conn1);
setDatabaseProperty(
"derby.database.requireAuthentication","true", conn1);
conn1.commit();
PreparedStatement psGetAccess = conn1.prepareStatement(
"VALUES SYSCS_UTIL.SYSCS_GET_USER_ACCESS(?)");
psGetAccess.setString(1, "JAMIE");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "DAN");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "SYSTEM");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "AMES");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
psGetAccess.setString(1, "MICKEY");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
// unknown user
psGetAccess.setString(1, "hagrid");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "NOACCESS");
conn1.commit();
// now add/switch some names using the utility method
CallableStatement csSetAccess = conn1.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_USER_ACCESS(?, ?)");
// Change AMES, everyone else is unchanged
csSetAccess.setString(1, "AMES");
csSetAccess.setString(2, "FULLACCESS");
csSetAccess.execute();
psGetAccess.setString(1, "AMES");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "MICKEY");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
psGetAccess.setString(1, "JAMIE");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "DAN");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "SYSTEM");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
// and change AMES back again
csSetAccess.setString(1, "AMES");
csSetAccess.setString(2, "READONLYACCESS");
csSetAccess.execute();
psGetAccess.setString(1, "AMES");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
psGetAccess.setString(1, "MICKEY");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
psGetAccess.setString(1, "JAMIE");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "DAN");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "SYSTEM");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
// add a new users in
csSetAccess.setString(1, "BOND");
csSetAccess.setString(2, "FULLACCESS");
csSetAccess.execute();
csSetAccess.setString(1, "JAMES");
csSetAccess.setString(2, "READONLYACCESS");
csSetAccess.execute();
conn1.commit();
psGetAccess.setString(1, "BOND");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
psGetAccess.setString(1, "JAMES");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
conn1.commit();
// and remove them
csSetAccess.setString(1, "BOND");
csSetAccess.setString(2, null);
csSetAccess.execute();
csSetAccess.setString(1, "JAMES");
csSetAccess.setString(2, null);
csSetAccess.execute();
conn1.commit();
psGetAccess.setString(1, "BOND");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "NOACCESS");
psGetAccess.setString(1, "JAMES");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "NOACCESS");
conn1.commit();
psGetAccess.close();
csSetAccess.close();
// we should still be connected as dan
Statement stmt = conn1.createStatement();
assertUpdateCount(stmt, 0,
"create table APP.t1(c1 varchar(30) check (UPPER(c1) <> 'JAMIE'))");
assertUpdateCount(stmt, 1, "insert into APP.t1 values USER");
conn1.commit();
stmt.close();
conn1.close();
// check full access system level user can update
conn1 = openDefaultConnection("system", "admin");
stmt = conn1.createStatement();
assertUpdateCount(stmt, 1, "update APP.t1 set c1 = USER");
conn1.commit();
stmt.close();
conn1.close();
// read only users
assertUserValue(new String[] {"SYSTEM"},"ames",
"select * from APP.t1"); // should succeed
conn1 = openDefaultConnection("ames", ("ames"+PASSWORD_SUFFIX));
// DERBY-2738 (network client always returns false for isReadOnly)
if (usingEmbedded())
assertTrue(conn1.isReadOnly());
stmt = conn1.createStatement();
assertStatementError(
"25502", stmt, "delete from APP.t1 where c1 = 'SYSTEM'");
assertStatementError("25502", stmt, "insert into APP.t1 values USER");
assertStatementError(
"25502", stmt, "update APP.t1 set c1 = USER where c1 = 'SYSTEM'");
assertStatementError("25503", stmt, "create table APP.t2 (c1 int)");
conn1.commit();
stmt.close();
conn1.close();
// read-only system level user
conn1 = openDefaultConnection("mickey", "mouse");
// DERBY-2738 (network client always returns false for isReadOnly)
if (usingEmbedded())
assertTrue(conn1.isReadOnly());
stmt = conn1.createStatement();
assertStatementError(
"25502", stmt, "delete from APP.t1 where c1 = 'SYSTEM'");
conn1.rollback();
conn1.close();
// reset
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
stmt = conn1.createStatement();
assertUpdateCount(stmt, 0, "drop table APP.t1");
conn1.commit();
stmt.close();
conn1.close();
}
/**
* Test the procedure and function that provide short-cuts
* to setting and getting connection level access.
* @throws SQLException
*/
public void testUserAccessRoutines() throws SQLException
{
// use valid user/pwd to set the full accessusers.
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
PreparedStatement psGetAccess = conn1.prepareStatement(
"VALUES SYSCS_UTIL.SYSCS_GET_USER_ACCESS(?)");
CallableStatement csSetAccess = conn1.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_USER_ACCESS(?, ?)");
csSetAccess.setString(1, "DAN");
csSetAccess.setString(2, "FULLACCESS");
csSetAccess.execute();
// Invalid users
csSetAccess.setString(1, null);
csSetAccess.setString(2, "FULLACCESS");
assertStatementError("28502", csSetAccess);
// Random user will now have only READONLYACCESS
setDatabaseProperty(
"derby.database.defaultConnectionMode","READONLYACCESS", conn1);
conn1.commit();
psGetAccess.setString(1, "TONYBLAIR");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "READONLYACCESS");
conn1.commit();
// Random user will now have FULLACCESS
setDatabaseProperty(
"derby.database.defaultConnectionMode","FULLACCESS", conn1);
conn1.commit();
psGetAccess.setString(1, "TONYBLAIR");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
conn1.commit();
// and still full access
setDatabaseProperty(
"derby.database.defaultConnectionMode", null, conn1);
conn1.commit();
psGetAccess.setString(1, "TONYBLAIR");
JDBC.assertSingleValueResultSet(psGetAccess.executeQuery(), "FULLACCESS");
conn1.commit();
conn1.close();
}
public void testGreekCharacters() throws SQLException {
String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
setSystemProperty("derby.user." + apollo, zeus);
Connection conn1 = openDefaultConnection(
"dan", ("dan" + PASSWORD_SUFFIX));
// add a database level user
setDatabaseProperty(("derby.user." + zeus), apollo, conn1);
setDatabaseProperty("derby.database.fullAccessUsers",
("dan,system,APP" + zeus + "," + apollo) , conn1);
conn1.commit();
conn1.close();
assertConnectionOK(dbName, zeus, apollo);
assertConnectionFail("08004", dbName, apollo, apollo);
// shutdown as non-dbo
assertShutdownOK(dbName, zeus, apollo);
assertConnectionOK(dbName, apollo, zeus);
// wrong credentials
assertShutdownFail("08004", dbName, zeus, zeus);
// shutdown as non-dbo
assertShutdownOK(dbName, apollo, zeus);
assertConnectionOK(dbName, apollo, zeus);
// shutdown as dbo
assertShutdownUsingSetShutdownOK(
dbName, "APP", ("APP" + PASSWORD_SUFFIX));
conn1 = openDefaultConnection(zeus, apollo);
Statement stmt = conn1.createStatement();
assertUpdateCount(stmt, 0,
"create table APP.t1(c1 varchar(30))");
assertUpdateCount(stmt, 1, "insert into APP.t1 values USER");
conn1.commit();
assertUserValue(new String[] {zeus}, zeus, apollo,
"select * from APP.t1 where c1 like CURRENT_USER");
stmt.close();
conn1.close();
// reset
conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
stmt = conn1.createStatement();
if (usingEmbedded())
assertUpdateCount(stmt, 0, "drop table APP.t1");
conn1.commit();
stmt.close();
conn1.close();
}
// tests system shutdown with setting required authentication at
// system level
public void testSystemShutdown() throws SQLException
{
String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
// just for the setting the stage, recheck connections while fullAccess
// (default) is set at database level.
// first try connection with valid user/password
assertConnectionOK(dbName, "system", ("admin"));
assertConnectionOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
// try ensuring system level is set for authentication
setSystemProperty("derby.connection.requireAuthentication", "true");
// bring down the database
assertShutdownUsingSetShutdownOK(
dbName, "APP", "APP" + PASSWORD_SUFFIX);
// recheck
assertConnectionOK(dbName, "system", "admin");
assertConnectionOK(dbName, "dan", ("dan" + PASSWORD_SUFFIX));
// bring down server to ensure settings take effect
assertSystemShutdownOK("", "badUser", ("dan" + PASSWORD_SUFFIX));
openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX)).close(); // revive
// try system shutdown with wrong user
assertSystemShutdownFail("08004", "", "badUser", ("dan" + PASSWORD_SUFFIX));
// with 'allowed' user but bad pwd
assertSystemShutdownFail("08004", "", "dan", ("jeff" + PASSWORD_SUFFIX));
// APP, but bad pwd
assertSystemShutdownFail("08004", "", "APP", ("POO"));
// note: we don't have a database, so no point checking for dbo.
// expect Derby system shutdown, which gives XJ015 error.
assertSystemShutdownOK("", "system", "admin");
// reset.
Connection conn1 = openDefaultConnection("dan", ("dan" + PASSWORD_SUFFIX));
setDatabaseProperty(
"derby.database.defaultConnectionMode","fullAccess", conn1);
setDatabaseProperty(
"derby.connection.requireAuthentication","false", conn1);
setSystemProperty("derby.connection.requireAuthentication", "false");
conn1.commit();
conn1.close();
openDefaultConnection("system", "admin").close();
assertShutdownUsingSetShutdownOK(
dbName, "APP", "APP" + PASSWORD_SUFFIX);
assertSystemShutdownOK("", "system", "admin");
openDefaultConnection("system", "admin").close(); // just so teardown works.
}
/**
* DERBY-4483: Test that the database by default has the configurable
* hash authentication scheme enabled.
*/
public void testDefaultHashAlgorithm() throws SQLException {
// SHA-256 should be the default hash algorithm now, if it's supported
// on the platform. Otherwise, we fall back to SHA-1.
String expected = supportsAlgorithm("SHA-256") ? "SHA-256" : "SHA-1";
assertEquals(expected, getDatabaseProperty(BUILTIN_ALGO_PROP));
}
/**
* Check if a message digest algorithm is supported on this platform.
*
* @param algorithm the algorithm to check
* @return true if the algorithm is supported, false otherwise
*/
private boolean supportsAlgorithm(String algorithm) {
try {
MessageDigest.getInstance(algorithm);
return true;
} catch (NoSuchAlgorithmException nsae) {
return false;
}
}
/**
* DERBY-4483: Test that setting the property
* {@code derby.authentication.builtin.algorithm} changes which hash
* algorithm is used to protect the stored password token.
*/
public void testVariousBuiltinAlgorithms() throws SQLException {
setAutoCommit(true);
String[] algorithms = { null, "MD5", "SHA-1", "SHA-256", "SHA-512" };
for (int i = 0; i < algorithms.length; i++) {
String algo = algorithms[i];
if (algo != null && !supportsAlgorithm(algo)) {
// DERBY-4602: Skip algorithms not supported on this platform
continue;
}
setDatabaseProperty(BUILTIN_ALGO_PROP, algo);
for (int j = 0; j < USERS.length; j++) {
String user = USERS[j];
String password = user + PASSWORD_SUFFIX;
String userProp = USER_PREFIX + user;
// Set the password for the user
setDatabaseProperty(userProp, password);
// Get the stored password token and verify that it
// hashed the way we expect it to be
String token = getDatabaseProperty(userProp);
if (algo == null) {
assertTrue("Expected old authentication schema: " + token,
token.startsWith("3b60"));
} else {
assertTrue("Expected configurable hash schema: " + token,
token.startsWith("3b61"));
assertTrue("Expected algorithm " + algo + ":" + token,
token.endsWith(":" + algo));
}
// Verify that we can still connect as that user
openDefaultConnection(user, password).close();
}
}
}
/**
* DERBY-4483: Test that slightly different passwords result in different
* hashes, and also that using the same password for different users
* results in a unique hashes with the configurable hash authentication
* scheme.
*/
public void testNoCollisionsWithConfigurableHash() throws SQLException {
assertNotNull("hash algorithm not set up",
getDatabaseProperty(BUILTIN_ALGO_PROP));
// Store a set of generated password tokens to detect collisions
HashSet tokens = new HashSet();
for (int i = 0; i < USERS.length; i++) {
String user = USERS[i];
String userProp = USER_PREFIX + user;
assertNotNull("missing user " + user,
getDatabaseProperty(userProp));
// Start with the password "testing", and then change one of the
// characters
char[] pw = new char[] { 't', 'e', 's', 't', 'i', 'n', 'g' };
for (int j = 0; j < 100; j++) {
String pass = new String(pw);
setDatabaseProperty(userProp, pass);
assertTrue("collision detected",
tokens.add(getDatabaseProperty(userProp)));
pw[pw.length / 2]++;
}
}
}
/**
* DERBY-4483: Test that we fail gracefully if an invalid algorithm name
* is specified in {@code derby.authentication.builtin.algorithm}.
*/
public void testInvalidAlgorithmName() throws SQLException {
setDatabaseProperty(BUILTIN_ALGO_PROP, "not-a-valid-name");
for (int i = 0; i < USERS.length; i++) {
try {
setDatabaseProperty(USER_PREFIX + USERS[i], "abcdef");
fail();
} catch (SQLException sqle) {
assertSQLState(NO_SUCH_ALGO, sqle);
}
}
}
protected void assertFailSetDatabaseProperty(
String propertyName, String value, Connection conn)
throws SQLException {
CallableStatement setDBP = conn.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
setDBP.setString(1, propertyName);
setDBP.setString(2, value);
// user jamie cannot be both readOnly and fullAccess
assertStatementError("4250C", setDBP);
setDBP.close();
}
protected void setDatabaseProperty(
String propertyName, String value, Connection conn)
throws SQLException {
CallableStatement setDBP = conn.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
setDBP.setString(1, propertyName);
setDBP.setString(2, value);
setDBP.execute();
setDBP.close();
}
/**
* Set a database property in the default connection.
*/
void setDatabaseProperty(String propertyName, String value)
throws SQLException
{
setDatabaseProperty(propertyName, value, getConnection());
}
protected void useUserValue(int expectedUpdateCount, String user, String sql)
throws SQLException
{
Connection conn1 = openDefaultConnection(user, user + PASSWORD_SUFFIX);
Statement stmt = conn1.createStatement();
assertUpdateCount(stmt, expectedUpdateCount, sql);
conn1.commit();
stmt.close();
conn1.close();
}
// verify that the return value is the expected value, and
// we have the expected number of rows returning from the query
// in this test, it will be one of the user names through
// use of CURRENT_USER, SESSION_USER etc.
protected void assertUserValue(
String[] expected, String user, String password, String sql)
throws SQLException
{
Connection conn1 = openDefaultConnection(user, password);
Statement stmt = conn1.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int i = 0;
while (rs.next())
{
assertEquals(expected[i],rs.getString(1));
i++;
}
assertEquals(expected.length, i);
conn1.commit();
stmt.close();
conn1.close();
}
// convenience method, password is often using PASSWORD_SUFFIX
protected void assertUserValue(String[] expected, String user, String sql)
throws SQLException {
assertUserValue(expected, user, (user + PASSWORD_SUFFIX), sql);
}
// get a connection using ds.getConnection(user, password)
protected void assertConnectionOK(
String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
Connection conn = ds.getConnection(user, password);
assertNotNull(conn);
conn.close();
}
// get a connection, using setUser / setPassword, and ds.getConnection()
protected void assertConnectionWOUPOK(
String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
Connection conn = ds.getConnection();
assertNotNull(conn);
conn.close();
}
protected void assertConnectionFail(
String expectedSqlState, String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
try {
ds.getConnection(user, password);
fail("Connection should've been refused/failed");
}
catch (SQLException e) {
assertSQLState(expectedSqlState, e);
}
}
// same action as with assertConnectionFail, but using ds.getConnection()
// instead of ds.getConnection(user, password). So, setting user and
// password using appropriate ds.set method.
protected void assertConnectionWOUPFail(
String expectedError, String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
try {
ds.getConnection();
fail("Connection should've been refused/failed");
}
catch (SQLException e) {
assertSQLState(expectedError, e);
}
}
protected void assertShutdownUsingSetShutdownOK(
String dbName, String user, String password) throws SQLException {
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection(user, password);
fail("expected shutdown to fail");
} catch (SQLException e) {
// expect 08006 on successful shutdown
assertSQLState("08006", e);
}
}
protected void assertShutdownUsingConnAttrsOK(
String dbName, String user, String password) throws SQLException {
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(
ds, "connectionAttributes", "shutdown=true");
try {
ds.getConnection(user, password);
fail("expected shutdown to fail");
} catch (SQLException e) {
// expect 08006 on successful shutdown
assertSQLState("08006", e);
}
}
// same action as with assertShutdownOK, but using ds.getConnection()
// instead of ds.getConnection(user, password). So, setting user and
// password using appropriate ds.set method.
protected void assertShutdownWOUPOK(
String dbName, String user, String password)
throws SQLException {
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
try {
ds.getConnection();
fail("expected shutdown to fail");
} catch (SQLException e) {
// expect 08006 on successful shutdown
assertSQLState("08006", e);
}
}
protected void assertShutdownFail(
String expectedSqlState, String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection(user, password);
fail("expected shutdown to fail");
} catch (SQLException e) {
assertSQLState(expectedSqlState, e);
}
}
protected void assertShutdownOK(
String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection(user, password);
fail("expected shutdown to fail");
} catch (SQLException e) {
assertSQLState("08006", e);
}
}
protected void assertShutdownWOUPFail(
String expectedSqlState, String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
try {
ds.getConnection();
fail("expected shutdown to fail");
} catch (SQLException e) {
assertSQLState(expectedSqlState, e);
}
}
protected void assertSystemShutdownOK(
String dbName, String user, String password)
throws SQLException {
DataSource ds;
if (usingEmbedded())
{
// we cannot use JDBCDataSource.getDataSource() (which uses the
// default database name), unless we specifically clear the
// databaseName. Otherwise, only the database will be shutdown.
// The alternative is to use jDBCDataSource.getDatasource(dbName),
// where dbName is an empty string - this will in the current code
// be interpreted as a system shutdown.
ds = JDBCDataSource.getDataSource();
JDBCDataSource.clearStringBeanProperty(ds, "databaseName");
}
else
{
// With client, we cannot user clearStringBeanProperty on the
// databaseName, that will result in error 08001 -
// Required DataSource property databaseName not set.
// So, we pass an empty string as databaseName, which the current
// code interprets as a system shutdown.
ds = JDBCDataSource.getDataSource(dbName);
}
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection(user, password);
fail("expected system shutdown resulting in XJ015 error");
} catch (SQLException e) {
// expect XJ015, system shutdown, on successful shutdown
assertSQLState("XJ015", e);
}
}
protected void assertSystemShutdownFail(
String expectedError, String dbName, String user, String password)
throws SQLException {
DataSource ds;
if (usingEmbedded())
{
ds = JDBCDataSource.getDataSource();
JDBCDataSource.clearStringBeanProperty(ds, "databaseName");
}
else
{
// note: with network server/client, you can't set the databaseName
// to null, that results in error 08001 - Required DataSource
// property databaseName not set.
// so, we rely on passing of an empty string for databaseName,
// which in the current code is interpreted as system shutdown.
ds = JDBCDataSource.getDataSource(dbName);
}
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
try {
ds.getConnection();
fail("expected shutdown to fail");
} catch (SQLException e) {
assertSQLState(expectedError, e);
}
}
public void assertConnectionFail(String dbName) throws SQLException {
// Get the default data source but clear the user and
// password set by the configuration.
DataSource ds = JDBCDataSource.getDataSource(dbName);
// Reset to no user/password though client requires
// a valid name, so reset to the default
if (usingDerbyNetClient())
JDBCDataSource.setBeanProperty(ds, "user", "APP");
else
JDBCDataSource.clearStringBeanProperty(ds, "user");
JDBCDataSource.clearStringBeanProperty(ds, "password");
try {
ds.getConnection();
fail("expected connection to fail");
} catch (SQLException e) {
assertSQLState("08004", e);
}
}
}
| kavin256/Derby | java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/AuthenticationTest.java | Java | apache-2.0 | 61,215 |
<?php
/**
* Writes the single character \x00 to indicate End of compiled data
*
* @phpstub
*
* @param resource $filehandle
*
* @return bool
*/
function bcompiler_write_footer($filehandle)
{
} | schmittjoh/php-stubs | res/php/bcompiler/functions/bcompiler-write-footer.php | PHP | apache-2.0 | 201 |
/*
* Copyright 2020 the original 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.openrewrite;
import org.openrewrite.internal.lang.Nullable;
import java.util.Spliterators;
import java.util.UUID;
import static java.util.stream.StreamSupport.stream;
public interface ScopedVisitorSupport {
UUID getScope();
Cursor getCursor();
default boolean isScope() {
return isScope(getCursor().getTree());
}
default boolean isScope(@Nullable Tree t) {
return t != null && getScope().equals(t.getId());
}
default boolean isScopeInCursorPath() {
Tree t = getCursor().getTree();
return (t != null && t.getId().equals(getScope())) ||
stream(Spliterators.spliteratorUnknownSize(getCursor().getPath(), 0), false)
.anyMatch(p -> p.getId().equals(getScope()));
}
}
| nebula-plugins/java-source-refactor | rewrite-core/src/main/java/org/openrewrite/ScopedVisitorSupport.java | Java | apache-2.0 | 1,391 |
// 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.
#include <vector>
#include <mesos/mesos.hpp>
#include <process/owned.hpp>
#include <process/gtest.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/gtest.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/uuid.hpp>
#include "linux/fs.hpp"
#include "slave/paths.hpp"
#include "slave/containerizer/mesos/containerizer.hpp"
#include "slave/containerizer/mesos/isolators/filesystem/linux.hpp"
#include "tests/cluster.hpp"
#include "tests/environment.hpp"
#include "tests/mesos.hpp"
#include "tests/containerizer/docker_archive.hpp"
using process::Future;
using process::Owned;
using process::PID;
using std::map;
using std::string;
using std::vector;
using mesos::internal::master::Master;
using mesos::internal::slave::Containerizer;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::LinuxFilesystemIsolatorProcess;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::Slave;
using mesos::master::detector::MasterDetector;
using mesos::slave::ContainerTermination;
using mesos::slave::Isolator;
namespace mesos {
namespace internal {
namespace tests {
class LinuxFilesystemIsolatorTest : public MesosTest
{
protected:
Fetcher fetcher;
};
// This test verifies that the root filesystem of the container is
// properly changed to the one that's provisioned by the provisioner.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_ChangeRootFilesystem)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"[ ! -d '" + sandbox.get() + "' ]");
executor.mutable_container()->CopyFrom(createContainerInfo("test_image"));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
}
// This test verifies that the metrics about the number of executors
// that have root filesystem specified is correctly reported.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_Metrics)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a long running task so we can reliably capture the moment it's alive.
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"sleep 1000");
executor.mutable_container()->CopyFrom(createContainerInfo("test_image"));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
JSON::Object stats = Metrics();
EXPECT_EQ(1u, stats.values.count(
"containerizer/mesos/filesystem/containers_new_rootfs"));
EXPECT_EQ(
1, stats.values["containerizer/mesos/filesystem/containers_new_rootfs"]);
containerizer->destroy(containerId);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WTERMSIG_EQ(SIGKILL, wait->get().status());
}
// This test verifies that a volume with a relative host path is
// properly created in the container's sandbox and is properly mounted
// in the container's mount namespace.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromSandbox)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"echo abc > /tmp/file");
executor.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp", "tmp", Volume::RW)}));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
EXPECT_SOME_EQ("abc\n", os::read(path::join(directory, "tmp", "file")));
}
// This test verifies that a volume with an absolute host path as
// well as an absolute container path is properly mounted in the
// container's mount namespace.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHost)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"test -d /tmp/dir");
executor.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp", sandbox.get(), Volume::RW)}));
string dir = path::join(sandbox.get(), "dir");
ASSERT_SOME(os::mkdir(dir));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
}
// This test verifies that a file volume with an absolute host
// path as well as an absolute container path is properly mounted
// in the container's mount namespace.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_FileVolumeFromHost)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"test -f /tmp/test/file.txt");
string file = path::join(sandbox.get(), "file");
ASSERT_SOME(os::touch(file));
executor.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp/test/file.txt", file, Volume::RW)}));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY_FOR(launch, Seconds(60));
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
}
// This test verifies that a volume with an absolute host path and a
// relative container path is properly mounted in the container's
// mount namespace. The mount point will be created in the sandbox.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_VolumeFromHostSandboxMountPoint)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"test -d mountpoint/dir");
executor.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("mountpoint", sandbox.get(), Volume::RW)}));
string dir = path::join(sandbox.get(), "dir");
ASSERT_SOME(os::mkdir(dir));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
}
// This test verifies that a file volume with an absolute host path
// and a relative container path is properly mounted in the container's
// mount namespace. The mount point will be created in the sandbox.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_FileVolumeFromHostSandboxMountPoint)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"test -f mountpoint/file.txt");
string file = path::join(sandbox.get(), "file");
ASSERT_SOME(os::touch(file));
executor.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("mountpoint/file.txt", file, Volume::RW)}));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY_FOR(launch, Seconds(60));
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
}
// This test verifies that persistent volumes are properly mounted in
// the container's root filesystem.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolumeWithRootFilesystem)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"echo abc > volume/file");
executor.add_resources()->CopyFrom(createPersistentVolume(
Megabytes(32),
"test_role",
"persistent_volume_id",
"volume"));
executor.mutable_container()->CopyFrom(createContainerInfo("test_image"));
// Create a persistent volume.
string volume = slave::paths::getPersistentVolumePath(
flags.work_dir,
"test_role",
"persistent_volume_id");
ASSERT_SOME(os::mkdir(volume));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
EXPECT_SOME_EQ("abc\n", os::read(path::join(volume, "file")));
}
// This test verifies that persistent volumes are properly mounted if
// the container does not specify a root filesystem.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolumeWithoutRootFilesystem)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"echo abc > volume/file");
executor.add_resources()->CopyFrom(createPersistentVolume(
Megabytes(32),
"test_role",
"persistent_volume_id",
"volume"));
// Create a persistent volume.
string volume = slave::paths::getPersistentVolumePath(
flags.work_dir,
"test_role",
"persistent_volume_id");
ASSERT_SOME(os::mkdir(volume));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait->get().status());
EXPECT_SOME_EQ("abc\n", os::read(path::join(volume, "file")));
}
// This test verifies that multiple containers with images can be
// launched simultaneously with no interference.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_MultipleContainers)
{
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image1"));
AWAIT_READY(DockerArchive::create(registry, "test_image2"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId1;
containerId1.set_value(UUID::random().toString());
ContainerID containerId2;
containerId2.set_value(UUID::random().toString());
ExecutorInfo executor1 = createExecutorInfo(
"test_executor1",
"sleep 1000");
executor1.mutable_container()->CopyFrom(createContainerInfo("test_image1"));
// Create a persistent volume for container 1. We do this because
// we want to test container 2 cleaning up multiple mounts.
executor1.add_resources()->CopyFrom(createPersistentVolume(
Megabytes(32),
"test_role",
"persistent_volume_id",
"volume"));
string volume = slave::paths::getPersistentVolumePath(
flags.work_dir,
"test_role",
"persistent_volume_id");
ASSERT_SOME(os::mkdir(volume));
string directory1 = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory1));
Future<bool> launch1 = containerizer->launch(
containerId1,
None(),
executor1,
directory1,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch1);
ExecutorInfo executor2 = createExecutorInfo(
"test_executor2",
"[ ! -d '" + sandbox.get() + "' ]");
executor2.mutable_container()->CopyFrom(createContainerInfo("test_image2"));
string directory2 = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory2));
Future<bool> launch2 = containerizer->launch(
containerId2,
None(),
executor2,
directory2,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch1);
// Wait on the containers.
Future<Option<ContainerTermination>> wait1 =
containerizer->wait(containerId1);
Future<Option<ContainerTermination>> wait2 =
containerizer->wait(containerId2);
containerizer->destroy(containerId1);
AWAIT_READY(wait1);
ASSERT_SOME(wait1.get());
ASSERT_TRUE(wait1->get().has_status());
EXPECT_WTERMSIG_EQ(SIGKILL, wait1->get().status());
AWAIT_READY(wait2);
ASSERT_SOME(wait2.get());
ASSERT_TRUE(wait2->get().has_status());
EXPECT_WEXITSTATUS_EQ(0, wait2->get().status());
}
// This test verifies the case where we don't need a bind mount for
// slave's working directory because the mount containing it is
// already a shared mount in its own peer group.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_WorkDirMountNotNeeded)
{
Try<string> directory = environment->mkdtemp();
ASSERT_SOME(directory);
// Make 'sandbox' a shared mount in its own peer group.
ASSERT_SOME(os::shell(
"mount --bind %s %s && "
"mount --make-private %s &&"
"mount --make-shared %s",
directory->c_str(),
directory->c_str(),
directory->c_str(),
directory->c_str()));
// Slave's working directory is under 'sandbox'.
slave::Flags flags = CreateSlaveFlags();
flags.work_dir = path::join(directory.get(), "slave");
ASSERT_SOME(os::mkdir(flags.work_dir));
Try<Isolator*> isolator = LinuxFilesystemIsolatorProcess::create(flags);
ASSERT_SOME(isolator);
Try<fs::MountInfoTable> table = fs::MountInfoTable::read();
ASSERT_SOME(table);
// Verifies that there's no mount for slave's working directory.
bool mountFound = false;
foreach (const fs::MountInfoTable::Entry& entry, table->entries) {
if (entry.target == flags.work_dir) {
mountFound = true;
}
}
EXPECT_FALSE(mountFound);
delete isolator.get();
}
// This test verifies the case where we do need a bind mount for
// slave's working directory because the mount containing it is not a
// shared mount in its own peer group.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_WorkDirMountNeeded)
{
Try<string> directory = environment->mkdtemp();
ASSERT_SOME(directory);
// Make 'sandbox' a private mount.
ASSERT_SOME(os::shell(
"mount --bind %s %s && "
"mount --make-private %s",
directory->c_str(),
directory->c_str(),
directory->c_str()));
slave::Flags flags = CreateSlaveFlags();
flags.work_dir = path::join(directory.get(), "slave");
ASSERT_SOME(os::mkdir(flags.work_dir));
Try<Isolator*> isolator = LinuxFilesystemIsolatorProcess::create(flags);
ASSERT_SOME(isolator);
Try<fs::MountInfoTable> table = fs::MountInfoTable::read();
ASSERT_SOME(table);
bool mountFound = false;
foreach (const fs::MountInfoTable::Entry& entry, table->entries) {
if (entry.target == flags.work_dir) {
EXPECT_SOME(entry.shared());
mountFound = true;
}
}
EXPECT_TRUE(mountFound);
delete isolator.get();
}
// This test tries to catch the regression for MESOS-7366. It verifies
// that the persistent volume mount points in the sandbox will be
// cleaned up even if there is still reference to the volume.
TEST_F(LinuxFilesystemIsolatorTest, ROOT_PersistentVolumeMountPointCleanup)
{
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
ExecutorInfo executor = createExecutorInfo(
"test_executor",
"sleep 1000");
// Create a persistent volume.
executor.add_resources()->CopyFrom(createPersistentVolume(
Megabytes(32),
"test_role",
"persistent_volume_id",
"volume"));
string volume = slave::paths::getPersistentVolumePath(
flags.work_dir,
"test_role",
"persistent_volume_id");
ASSERT_SOME(os::mkdir(volume));
string directory = path::join(flags.work_dir, "sandbox");
ASSERT_SOME(os::mkdir(directory));
Future<bool> launch = containerizer->launch(
containerId,
None(),
executor,
directory,
None(),
SlaveID(),
map<string, string>(),
false);
AWAIT_READY(launch);
ASSERT_SOME(os::touch(path::join(directory, "volume", "abc")));
// This keeps a reference to the persistent volume mount.
Try<int_fd> fd = os::open(
path::join(directory, "volume", "abc"),
O_WRONLY | O_TRUNC | O_CLOEXEC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
ASSERT_SOME(fd);
containerizer->destroy(containerId);
Future<Option<ContainerTermination>> wait = containerizer->wait(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait->get().has_status());
EXPECT_WTERMSIG_EQ(SIGKILL, wait.get()->status());
// Verifies that mount point has been removed.
EXPECT_FALSE(os::exists(path::join(directory, "volume", "abc")));
os::close(fd.get());
}
// End to end Mesos integration tests for linux filesystem isolator.
class LinuxFilesystemIsolatorMesosTest : public LinuxFilesystemIsolatorTest {};
// This test verifies that the framework can launch a command task
// that specifies a container image.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_ChangeRootFilesystemCommandExecutor)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
const Offer& offer = offers.get()[0];
TaskInfo task = createTask(
offer.slave_id(),
offer.resources(),
"test -d " + flags.sandbox_directory);
task.mutable_container()->CopyFrom(createContainerInfo("test_image"));
driver.launchTasks(offer.id(), {task});
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
driver.stop();
driver.join();
}
// This test verifies that the framework can launch a command task
// that specifies both container image and host volumes.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_ChangeRootFilesystemCommandExecutorWithHostVolumes)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
const Offer& offer = offers.get()[0];
// Preparing two volumes:
// - host_path: dir1, container_path: /tmp
// - host_path: dir2, container_path: relative_dir
string dir1 = path::join(sandbox.get(), "dir1");
ASSERT_SOME(os::mkdir(dir1));
string testFile = path::join(dir1, "testfile");
ASSERT_SOME(os::touch(testFile));
string dir2 = path::join(sandbox.get(), "dir2");
ASSERT_SOME(os::mkdir(dir2));
TaskInfo task = createTask(
offer.slave_id(),
offer.resources(),
"test -f /tmp/testfile && test -d " +
path::join(flags.sandbox_directory, "relative_dir"));
task.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp", dir1, Volume::RW),
createVolumeFromHostPath("relative_dir", dir2, Volume::RW)}));
driver.launchTasks(offer.id(), {task});
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
driver.stop();
driver.join();
}
// This test verifies that the framework can launch a command task
// that specifies both container image and persistent volumes.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_ChangeRootFilesystemCommandExecutorPersistentVolume)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:2;mem:1024;disk(role1):1024";
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_role("role1");
MesosSchedulerDriver driver(
&sched,
frameworkInfo,
master.get()->pid,
DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(frameworkId);
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
Offer offer = offers.get()[0];
string dir1 = path::join(sandbox.get(), "dir1");
ASSERT_SOME(os::mkdir(dir1));
Resource persistentVolume = createPersistentVolume(
Megabytes(64),
"role1",
"id1",
"path1",
None(),
None(),
frameworkInfo.principal());
// We use the filter explicitly here so that the resources will not
// be filtered for 5 seconds (the default).
Filters filters;
filters.set_refuse_seconds(0);
TaskInfo task = createTask(
offer.slave_id(),
Resources::parse("cpus:1;mem:512").get() + persistentVolume,
"echo abc > path1/file");
task.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp", dir1, Volume::RW)}));
// Create the persistent volumes and launch task via `acceptOffers`.
driver.acceptOffers(
{offer.id()},
{CREATE(persistentVolume), LAUNCH({task})},
filters);
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
// NOTE: The command executor's id is the same as the task id.
ExecutorID executorId;
executorId.set_value(task.task_id().value());
string directory = slave::paths::getExecutorLatestRunPath(
flags.work_dir,
offer.slave_id(),
frameworkId.get(),
executorId);
EXPECT_FALSE(os::exists(path::join(directory, "path1")));
string volumePath = slave::paths::getPersistentVolumePath(
flags.work_dir,
"role1",
"id1");
EXPECT_SOME_EQ("abc\n", os::read(path::join(volumePath, "file")));
driver.stop();
driver.join();
}
// This test verifies that persistent volumes are unmounted properly
// after a checkpointed framework disappears and the slave restarts.
//
// TODO(jieyu): Even though the command task specifies a new
// filesystem root, the executor (command executor) itself does not
// change filesystem root (uses the host filesystem). We need to add a
// test to test the scenario that the executor itself changes rootfs.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_RecoverOrphanedPersistentVolume)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:2;mem:1024;disk(role1):1024";
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Try<MesosContainerizer*> create =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
Owned<Containerizer> containerizer(create.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(
detector.get(),
containerizer.get(),
flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_role("role1");
frameworkInfo.set_checkpoint(true);
MesosSchedulerDriver driver(
&sched,
frameworkInfo,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_FALSE(offers->empty());
Offer offer = offers.get()[0];
string dir1 = path::join(sandbox.get(), "dir1");
ASSERT_SOME(os::mkdir(dir1));
Resource persistentVolume = createPersistentVolume(
Megabytes(64),
"role1",
"id1",
"path1",
None(),
None(),
frameworkInfo.principal());
// Create a task that does nothing for a long time.
TaskInfo task = createTask(
offer.slave_id(),
Resources::parse("cpus:1;mem:512").get() + persistentVolume,
"sleep 1000");
task.mutable_container()->CopyFrom(createContainerInfo(
"test_image",
{createVolumeFromHostPath("/tmp", dir1, Volume::RW)}));
Future<TaskStatus> status;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&status))
.WillRepeatedly(DoDefault());
Future<Nothing> ack =
FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement);
// Create the persistent volumes and launch task via `acceptOffers`.
driver.acceptOffers(
{offer.id()},
{CREATE(persistentVolume), LAUNCH({task})});
AWAIT_READY(status);
EXPECT_EQ(TASK_RUNNING, status->state());
// Wait for the ACK to be checkpointed.
AWAIT_READY(ack);
Future<hashset<ContainerID>> containers = containerizer->containers();
AWAIT_READY(containers);
ASSERT_EQ(1u, containers->size());
ContainerID containerId = *containers->begin();
// Restart the slave.
slave.get()->terminate();
// Wipe the slave meta directory so that the slave will treat the
// above running task as an orphan.
ASSERT_SOME(os::rmdir(slave::paths::getMetaRootDir(flags.work_dir)));
Future<Nothing> _recover = FUTURE_DISPATCH(_, &Slave::_recover);
// Recreate the containerizer using the same helper as above.
containerizer.reset();
create = MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(create);
containerizer.reset(create.get());
slave = StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
// Wait until slave recovery is complete.
AWAIT_READY(_recover);
// Wait until the orphan containers are cleaned up.
AWAIT_READY(containerizer->wait(containerId));
Try<fs::MountInfoTable> table = fs::MountInfoTable::read();
ASSERT_SOME(table);
// All mount targets should be under this directory.
string directory = slave::paths::getSandboxRootDir(flags.work_dir);
// Verify that the orphaned container's persistent volume and
// the rootfs are unmounted.
foreach (const fs::MountInfoTable::Entry& entry, table->entries) {
EXPECT_FALSE(strings::contains(entry.target, directory))
<< "Target was not unmounted: " << entry.target;
}
driver.stop();
driver.join();
}
// This test verifies that the environment variables for sandbox
// (i.e., MESOS_SANDBOX) is set properly.
TEST_F(LinuxFilesystemIsolatorMesosTest, ROOT_SandboxEnvironmentVariable)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
const Offer& offer = offers.get()[0];
TaskInfo task = createTask(
offer.slave_id(),
offer.resources(),
strings::format(
"if [ \"$MESOS_SANDBOX\" != \"%s\" ]; then exit 1; fi &&"
"if [ ! -d \"$MESOS_SANDBOX\" ]; then exit 1; fi",
flags.sandbox_directory).get());
task.mutable_container()->CopyFrom(createContainerInfo("test_image"));
driver.launchTasks(offer.id(), {task});
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
driver.stop();
driver.join();
}
// This test verifies that the volume usage accounting for sandboxes
// with bind-mounted volumes (while linux filesystem isolator is used)
// works correctly by creating a file within the volume the size of
// which exceeds the sandbox quota.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_VolumeUsageExceedsSandboxQuota)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:2;mem:128;disk(role1):128";
flags.isolation = "disk/du,filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
// NOTE: We can't pause the clock because we need the reaper to reap
// the 'du' subprocess.
flags.container_disk_watch_interval = Milliseconds(1);
flags.enforce_container_disk_quota = true;
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_role("role1");
MesosSchedulerDriver driver(
&sched,
frameworkInfo,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
// We request a sandbox (1MB) that is smaller than the persistent
// volume (4MB) and attempt to create a file in that volume that is
// twice the size of the sanbox (2MB).
Resources volume = createPersistentVolume(
Megabytes(4),
"role1",
"id1",
"volume_path",
None(),
None(),
frameworkInfo.principal());
Resources taskResources =
Resources::parse("cpus:1;mem:64;disk(role1):1").get() + volume;
// We sleep to give quota enforcement (du) a chance to kick in.
TaskInfo task = createTask(
offers.get()[0].slave_id(),
taskResources,
"dd if=/dev/zero of=volume_path/file bs=1048576 count=2 && sleep 1");
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
driver.acceptOffers(
{offers.get()[0].id()},
{CREATE(volume),
LAUNCH({task})});
AWAIT_READY(statusRunning);
EXPECT_EQ(task.task_id(), statusRunning->task_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(task.task_id(), statusFinished->task_id());
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
driver.stop();
driver.join();
}
// Tests that the task fails when it attempts to write to a persistent volume
// mounted as read-only. Note that although we use a shared persistent volume,
// the behavior is the same for non-shared persistent volumes.
TEST_F(LinuxFilesystemIsolatorMesosTest,
ROOT_WriteAccessSharedPersistentVolumeReadOnlyMode)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
string registry = path::join(sandbox.get(), "registry");
AWAIT_READY(DockerArchive::create(registry, "test_image"));
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:2;mem:128;disk(role1):128";
flags.isolation = "filesystem/linux,docker/runtime";
flags.docker_registry = registry;
flags.docker_store_dir = path::join(sandbox.get(), "store");
flags.image_providers = "docker";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_role("role1");
frameworkInfo.add_capabilities()->set_type(
FrameworkInfo::Capability::SHARED_RESOURCES);
MesosSchedulerDriver driver(
&sched,
frameworkInfo,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
// We create a shared volume which shall be used by the task to
// write to that volume.
Resource volume = createPersistentVolume(
Megabytes(4),
"role1",
"id1",
"volume_path",
None(),
None(),
frameworkInfo.principal(),
true); // Shared volume.
// The task uses the shared volume as read-only.
Resource roVolume = volume;
roVolume.mutable_disk()->mutable_volume()->set_mode(Volume::RO);
Resources taskResources =
Resources::parse("cpus:1;mem:64;disk(role1):1").get() + roVolume;
TaskInfo task = createTask(
offers.get()[0].slave_id(),
taskResources,
"echo hello > volume_path/file");
// The task fails to write to the volume since the task's resources
// intends to use the volume as read-only.
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFailed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFailed));
driver.acceptOffers(
{offers.get()[0].id()},
{CREATE(volume),
LAUNCH({task})});
AWAIT_READY(statusRunning);
EXPECT_EQ(task.task_id(), statusRunning->task_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFailed);
EXPECT_EQ(task.task_id(), statusFailed->task_id());
EXPECT_EQ(TASK_FAILED, statusFailed->state());
driver.stop();
driver.join();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
| craimbert/mesos | src/tests/containerizer/linux_filesystem_isolator_tests.cpp | C++ | apache-2.0 | 46,246 |
package com.navalgame;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | JU-2094/NavalGame | app/src/test/java/com/navalgame/ExampleUnitTest.java | Java | apache-2.0 | 391 |
/*
* Copyright 2016-2102 Appleframework(http://www.appleframework.com) Group.
*
* 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.appleframework.pay.account.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.appleframework.pay.common.core.exception.BizException;
/**
* 账户服务业务异常类,异常代码8位数字组成,前4位固定1001打头,后4位自定义
* http://www.appleframework.com
* @author:Cruise.Xu
*/
public class AccountBizException extends BizException {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(AccountBizException.class);
public static final AccountBizException ACCOUNT_NOT_EXIT = new AccountBizException(10010001, "账户不存在");
public static final AccountBizException ACCOUNT_SUB_AMOUNT_OUTLIMIT = new AccountBizException(10010002, "余额不足,减款超限");
public static final AccountBizException ACCOUNT_UN_FROZEN_AMOUNT_OUTLIMIT = new AccountBizException(10010003, "解冻金额超限");
public static final AccountBizException ACCOUNT_FROZEN_AMOUNT_OUTLIMIT = new AccountBizException(10010004, "冻结金额超限");
public static final AccountBizException ACCOUNT_TYPE_IS_NULL = new AccountBizException(10010005, "账户类型不能为空");
public AccountBizException() {
}
public AccountBizException(int code, String msgFormat, Object... args) {
super(code, msgFormat, args);
}
public AccountBizException(int code, String msg) {
super(code, msg);
}
/**
* 实例化异常
*
* @param msgFormat
* @param args
* @return
*/
public AccountBizException newInstance(String msgFormat, Object... args) {
return new AccountBizException(this.code, msgFormat, args);
}
public AccountBizException print() {
logger.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
return this;
}
}
| xushaomin/apple-pay | apple-pay-service/src/main/java/com/appleframework/pay/account/exception/AccountBizException.java | Java | apache-2.0 | 2,412 |
package com.kifile.android.cornerstone.core;
import android.support.annotation.NonNull;
/**
* AbstractFetcherConverter is used to transform a data to another type.
*
* @author kifile
*/
public abstract class AbstractFetcherConverter<FROM, TO> implements DataFetcher<TO> {
private DataFetcher<FROM> mProxy;
/**
* Wrap the DataFetcher will be transformed.
*
* @param proxy
*/
public AbstractFetcherConverter(DataFetcher<FROM> proxy) {
mProxy = proxy;
}
@Override
public TO fetch() throws FetchException, ConvertException {
FROM data = mProxy.fetch();
if (data == null) {
throw new FetchException("Proxy return null.");
}
return convert(data);
}
protected abstract TO convert(@NonNull FROM from) throws ConvertException;
}
| kifile/Cornerstone | framework/src/main/java/com/kifile/android/cornerstone/core/AbstractFetcherConverter.java | Java | apache-2.0 | 836 |
// Copyright 2016-2019 Authors of Cilium
//
// 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 ctmap
import (
"bytes"
"fmt"
"unsafe"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/tuple"
)
// mapType is a type of connection tracking map.
type mapType int
const (
// mapTypeIPv4TCPLocal and friends are map types which correspond to a
// combination of the following attributes:
// * IPv4 or IPv6;
// * TCP or non-TCP (shortened to Any)
// * Local (endpoint-specific) or global (endpoint-oblivious).
mapTypeIPv4TCPLocal mapType = iota
mapTypeIPv6TCPLocal
mapTypeIPv4TCPGlobal
mapTypeIPv6TCPGlobal
mapTypeIPv4AnyLocal
mapTypeIPv6AnyLocal
mapTypeIPv4AnyGlobal
mapTypeIPv6AnyGlobal
mapTypeMax
)
// String renders the map type into a user-readable string.
func (m mapType) String() string {
switch m {
case mapTypeIPv4TCPLocal:
return "Local IPv4 TCP CT map"
case mapTypeIPv6TCPLocal:
return "Local IPv6 TCP CT map"
case mapTypeIPv4TCPGlobal:
return "Global IPv4 TCP CT map"
case mapTypeIPv6TCPGlobal:
return "Global IPv6 TCP CT map"
case mapTypeIPv4AnyLocal:
return "Local IPv4 non-TCP CT map"
case mapTypeIPv6AnyLocal:
return "Local IPv6 non-TCP CT map"
case mapTypeIPv4AnyGlobal:
return "Global IPv4 non-TCP CT map"
case mapTypeIPv6AnyGlobal:
return "Global IPv6 non-TCP CT map"
}
return fmt.Sprintf("Unknown (%d)", int(m))
}
func (m mapType) isIPv4() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv4TCPGlobal, mapTypeIPv4AnyLocal, mapTypeIPv4AnyGlobal:
return true
}
return false
}
func (m mapType) isIPv6() bool {
switch m {
case mapTypeIPv6TCPLocal, mapTypeIPv6TCPGlobal, mapTypeIPv6AnyLocal, mapTypeIPv6AnyGlobal:
return true
}
return false
}
func (m mapType) isLocal() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv6TCPLocal, mapTypeIPv4AnyLocal, mapTypeIPv6AnyLocal:
return true
}
return false
}
func (m mapType) isGlobal() bool {
switch m {
case mapTypeIPv4TCPGlobal, mapTypeIPv6TCPGlobal, mapTypeIPv4AnyGlobal, mapTypeIPv6AnyGlobal:
return true
}
return false
}
func (m mapType) isTCP() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv6TCPLocal, mapTypeIPv4TCPGlobal, mapTypeIPv6TCPGlobal:
return true
}
return false
}
type CtKey interface {
bpf.MapKey
// ToNetwork converts fields to network byte order.
ToNetwork() CtKey
// ToHost converts fields to host byte order.
ToHost() CtKey
// Dump contents of key to buffer. Returns true if successful.
Dump(buffer *bytes.Buffer, reverse bool) bool
// GetFlags flags containing the direction of the CtKey.
GetFlags() uint8
GetTupleKey() tuple.TupleKey
}
// CtKey4 is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey4 struct {
tuple.TupleKey4
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey4) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts CtKey4 ports to network byte order.
func (k *CtKey4) ToNetwork() CtKey {
n := *k
n.SourcePort = byteorder.HostToNetwork(n.SourcePort).(uint16)
n.DestPort = byteorder.HostToNetwork(n.DestPort).(uint16)
return &n
}
// ToHost converts CtKey ports to host byte order.
func (k *CtKey4) ToHost() CtKey {
n := *k
n.SourcePort = byteorder.NetworkToHost(n.SourcePort).(uint16)
n.DestPort = byteorder.NetworkToHost(n.DestPort).(uint16)
return &n
}
// GetFlags returns the tuple's flags.
func (k *CtKey4) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey4) String() string {
return fmt.Sprintf("%s:%d, %d, %d, %d", k.DestAddr, k.SourcePort, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey4) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the value for
// next header in the key is nonzero.
func (k *CtKey4) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrDest = k.SourceAddr.IP().String()
} else {
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s %d:%d ",
k.NextHeader.String(), addrDest, k.SourcePort,
k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s %d:%d ",
k.NextHeader.String(), addrDest, k.DestPort,
k.SourcePort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey4) GetTupleKey() tuple.TupleKey {
return &k.TupleKey4
}
// CtKey4Global is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey4Global struct {
tuple.TupleKey4Global
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey4Global) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts ports to network byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey4Global type here into a local key type in the nested
// TupleKey4Global field.
func (k *CtKey4Global) ToNetwork() CtKey {
return &CtKey4Global{
TupleKey4Global: *k.TupleKey4Global.ToNetwork().(*tuple.TupleKey4Global),
}
}
// ToHost converts ports to host byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey4Global type here into a local key type in the nested
// TupleKey4Global field.
func (k *CtKey4Global) ToHost() CtKey {
return &CtKey4Global{
TupleKey4Global: *k.TupleKey4Global.ToHost().(*tuple.TupleKey4Global),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey4Global) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey4Global) String() string {
return fmt.Sprintf("%s:%d --> %s:%d, %d, %d", k.SourceAddr, k.SourcePort, k.DestAddr, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey4Global) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the
// value for next header in the key is nonzero.
func (k *CtKey4Global) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrSource, addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrSource = k.DestAddr.IP().String()
addrDest = k.SourceAddr.IP().String()
} else {
addrSource = k.SourceAddr.IP().String()
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey4Global) GetTupleKey() tuple.TupleKey {
return &k.TupleKey4Global
}
// CtKey6 is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey6 struct {
tuple.TupleKey6
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey6) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts CtKey6 ports to network byte order.
func (k *CtKey6) ToNetwork() CtKey {
return &CtKey6{
TupleKey6: *k.TupleKey6.ToNetwork().(*tuple.TupleKey6),
}
}
// ToHost converts CtKey ports to host byte order.
func (k *CtKey6) ToHost() CtKey {
return &CtKey6{
TupleKey6: *k.TupleKey6.ToHost().(*tuple.TupleKey6),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey6) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey6) String() string {
return fmt.Sprintf("[%s]:%d, %d, %d, %d", k.DestAddr, k.SourcePort, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey6) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the value for
// next header in the key is nonzero.
func (k *CtKey6) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrDest = k.SourceAddr.IP().String()
} else {
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s %d:%d ",
k.NextHeader.String(), addrDest, k.SourcePort,
k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s %d:%d ",
k.NextHeader.String(), addrDest, k.DestPort,
k.SourcePort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey6) GetTupleKey() tuple.TupleKey {
return &k.TupleKey6
}
// CtKey6Global is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey6Global struct {
tuple.TupleKey6Global
}
const SizeofCtKey6Global = int(unsafe.Sizeof(CtKey6Global{}))
// NewValue creates a new bpf.MapValue.
func (k *CtKey6Global) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts ports to network byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey6Global type here into a local key type in the nested
// TupleKey6Global field.
func (k *CtKey6Global) ToNetwork() CtKey {
return &CtKey6Global{
TupleKey6Global: *k.TupleKey6Global.ToNetwork().(*tuple.TupleKey6Global),
}
}
// ToHost converts ports to host byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey6Global type here into a local key type in the nested
// TupleKey6Global field.
func (k *CtKey6Global) ToHost() CtKey {
return &CtKey6Global{
TupleKey6Global: *k.TupleKey6Global.ToHost().(*tuple.TupleKey6Global),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey6Global) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey6Global) String() string {
return fmt.Sprintf("[%s]:%d --> [%s]:%d, %d, %d", k.SourceAddr, k.SourcePort, k.DestAddr, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey6Global) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the
// value for next header in the key is nonzero.
func (k *CtKey6Global) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrSource, addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrSource = k.DestAddr.IP().String()
addrDest = k.SourceAddr.IP().String()
} else {
addrSource = k.SourceAddr.IP().String()
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey6Global) GetTupleKey() tuple.TupleKey {
return &k.TupleKey6Global
}
// CtEntry represents an entry in the connection tracking table.
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapValue
type CtEntry struct {
RxPackets uint64 `align:"rx_packets"`
RxBytes uint64 `align:"rx_bytes"`
TxPackets uint64 `align:"tx_packets"`
TxBytes uint64 `align:"tx_bytes"`
Lifetime uint32 `align:"lifetime"`
Flags uint16 `align:"rx_closing"`
// RevNAT is in network byte order
RevNAT uint16 `align:"rev_nat_index"`
IfIndex uint16 `align:"ifindex"`
TxFlagsSeen uint8 `align:"tx_flags_seen"`
RxFlagsSeen uint8 `align:"rx_flags_seen"`
SourceSecurityID uint32 `align:"src_sec_id"`
LastTxReport uint32 `align:"last_tx_report"`
LastRxReport uint32 `align:"last_rx_report"`
}
const SizeofCtEntry = int(unsafe.Sizeof(CtEntry{}))
// GetValuePtr returns the unsafe.Pointer for s.
func (c *CtEntry) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(c) }
const (
RxClosing = 1 << iota
TxClosing
Nat64
LBLoopback
SeenNonSyn
NodePort
ProxyRedirect
DSR
MaxFlags
)
func (c *CtEntry) flagsString() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Flags=%#04x [ ", c.Flags))
if (c.Flags & RxClosing) != 0 {
buffer.WriteString("RxClosing ")
}
if (c.Flags & TxClosing) != 0 {
buffer.WriteString("TxClosing ")
}
if (c.Flags & Nat64) != 0 {
buffer.WriteString("Nat64 ")
}
if (c.Flags & LBLoopback) != 0 {
buffer.WriteString("LBLoopback ")
}
if (c.Flags & SeenNonSyn) != 0 {
buffer.WriteString("SeenNonSyn ")
}
if (c.Flags & NodePort) != 0 {
buffer.WriteString("NodePort ")
}
if (c.Flags & ProxyRedirect) != 0 {
buffer.WriteString("ProxyRedirect ")
}
if (c.Flags & DSR) != 0 {
buffer.WriteString("DSR ")
}
unknownFlags := c.Flags
unknownFlags &^= MaxFlags - 1
if unknownFlags != 0 {
buffer.WriteString(fmt.Sprintf("Unknown=%#04x ", unknownFlags))
}
buffer.WriteString("]")
return buffer.String()
}
// String returns the readable format
func (c *CtEntry) String() string {
return fmt.Sprintf("expires=%d RxPackets=%d RxBytes=%d RxFlagsSeen=%#02x LastRxReport=%d TxPackets=%d TxBytes=%d TxFlagsSeen=%#02x LastTxReport=%d %s RevNAT=%d SourceSecurityID=%d IfIndex=%d \n",
c.Lifetime,
c.RxPackets,
c.RxBytes,
c.RxFlagsSeen,
c.LastRxReport,
c.TxPackets,
c.TxBytes,
c.TxFlagsSeen,
c.LastTxReport,
c.flagsString(),
byteorder.NetworkToHost(c.RevNAT),
c.SourceSecurityID,
c.IfIndex)
}
| cilium-team/cilium | pkg/maps/ctmap/types.go | GO | apache-2.0 | 14,683 |
// -*- c++ -*-
//
// Copyright 2011 A.N.M. Imroz Choudhury
//
// NewCache.h
#ifndef NEW_CACHE_H
#define NEW_CACHE_H
// #define USE_STRING_INFO
// MTV headers.
#include <Core/Dataflow/BlockStream/BlockStreamReader.h>
#include <Core/Dataflow/TraceReader.h>
#include <Core/Util/BoostPointers.h>
#include <Tools/CacheSimulator/Cache.h>
#include <Tools/NewCacheSimulator/CacheLevel.h>
using Daly::CacheEntranceRecord;
using Daly::CacheEvictionRecord;
using Daly::CacheHitRecord;
// Boost headers.
#include <boost/enable_shared_from_this.hpp>
#include <boost/unordered_map.hpp>
// System headers.
#include <iostream>
#include <stdexcept>
#include <stdint.h>
#include <sstream>
#include <vector>
namespace MTV{
class AllocateExisting : public std::logic_error {
public:
AllocateExisting()
: std::logic_error("Attempt to allocate a block already present in the cache.")
{}
};
class UninitializedBlockstreamReader : public std::logic_error {
public:
UninitializedBlockstreamReader()
: std::logic_error("OPT or PES policy requested with uninitialized blockstream reader.")
{}
};
class UninitializedTraceReader : public std::logic_error {
public:
UninitializedTraceReader()
: std::logic_error("OPT or PES policy requested with uninitialized trace reader.")
{}
};
class NewCache : public boost::enable_shared_from_this<NewCache> {
friend class CacheLevel;
public:
BoostPointers(NewCache);
public:
class UnevenSets {};
public:
enum WriteMissPolicy{
WriteAllocate,
WriteNoAllocate
};
public:
static NewCache::ptr create(uint64_t blocksize, WriteMissPolicy write_miss_pol){
NewCache::ptr p(new NewCache(blocksize, write_miss_pol));
return p;
}
static NewCache::ptr newFromSpec(const std::string& specfile, TraceReader::ptr trace, BlockStreamReader::ptr bsreader, std::string& error);
static NewCache::ptr dummy(TraceReader::ptr trace, BlockStreamReader::ptr bsreader){
NewCache::ptr p(new NewCache(0, NewCache::WriteAllocate));
p->set_trace_reader(trace);
p->set_blockstream_reader(bsreader);
return p;
}
public:
WriteMissPolicy write_miss_policy() const {
return write_miss_pol;
}
uint64_t block_size() const {
return blocksize;
}
unsigned num_levels() const {
return levels.size();
}
CacheLevel::const_ptr level(unsigned i) const {
return levels[i];
}
void set_trace_reader(TraceReader::const_ptr _trace){
trace = _trace;
}
void set_blockstream_reader(BlockStreamReader::ptr _bs_reader){
bs_reader = _bs_reader;
}
CacheLevel::ptr add_level(CacheLevel::ptr level){
levels.push_back(level);
return level;
}
CacheLevel::ptr add_level(unsigned num_blocks, unsigned num_sets, CacheLevel::WritePolicy write_policy, CacheLevel::ReplacementPolicy repl_policy);
const std::vector<CacheHitRecord>& hitInfo() const {
return hit_info;
}
const std::vector<CacheEvictionRecord>& evictionInfo() const {
return eviction_info;
}
const std::vector<CacheEntranceRecord>& entranceInfo() const {
return entrance_info;
}
void load(const uint64_t addr);
void store(const uint64_t addr);
void print(std::ostream& out) const {
for(unsigned L=0; L<levels.size(); L++){
out << "L" << (L+1) << ":" << std::endl;
levels[L]->print(out, "\t");
}
}
#ifdef USE_STRING_INFO
const std::vector<std::string>& hits_string() const {
return hit_info_string;
}
const std::vector<std::string>& evictions_string() const {
return eviction_info_string;
}
const std::vector<std::string>& entrances_string() const {
return entrance_info_string;
}
#endif
const std::vector<Daly::CacheHitRecord>& hits() const {
return hit_info;
}
const std::vector<Daly::CacheEvictionRecord>& evictions() const {
return eviction_info;
}
const std::vector<Daly::CacheEntranceRecord>& entrances() const {
return entrance_info;
}
private:
NewCache(uint64_t blocksize, WriteMissPolicy write_miss_pol)
: blocksize(blocksize),
write_miss_pol(write_miss_pol)
{}
private:
void write_at_level(const unsigned level, const uint64_t addr);
private:
std::vector<CacheLevel::ptr> levels;
const unsigned blocksize;
const WriteMissPolicy write_miss_pol;
BlockStreamReader::ptr bs_reader;
TraceReader::const_ptr trace;
std::vector<Daly::CacheHitRecord> hit_info;
std::vector<Daly::CacheEvictionRecord> eviction_info;
std::vector<Daly::CacheEntranceRecord> entrance_info;
#ifdef USE_STRING_INFO
// String versions of the info records (to be obsoleted).
std::vector<std::string> hit_info_string;
std::vector<std::string> eviction_info_string;
std::vector<std::string> entrance_info_string;
#endif
};
}
#endif
| ronichoudhury/mtvx | Tools/NewCacheSimulator/NewCache.h | C | apache-2.0 | 4,975 |
//TEST FAILS
#include <string>
#include <cassert>
using namespace std;
int main(){
string str1, str2;
str1 = string("Test");
str2 = string(str1, 2);
assert(str2 < str1);
}
| ssvlab/esbmc-gpu | regression/esbmc-cpp/string/string_operator<_4_bug/main.cpp | C++ | apache-2.0 | 181 |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.geo.pose;
import boofcv.struct.calib.CameraPinholeBrown;
import boofcv.struct.calib.StereoParameters;
import boofcv.struct.sfm.StereoPose;
import georegression.geometry.ConvertRotation3D_F64;
import georegression.struct.EulerType;
import georegression.struct.se.Se3_F64;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Peter Abeles
*/
public class TestPnPStereoResidualReprojection extends CommonStereoMotionNPoint {
@Test void basicTest() {
Se3_F64 worldToLeft = new Se3_F64();
ConvertRotation3D_F64.eulerToMatrix(EulerType.XYZ, 0.1, 1, -0.2, worldToLeft.getR());
worldToLeft.getT().setTo(-0.3, 0.4, 1);
generateScene(10, worldToLeft, false);
PnPStereoResidualReprojection alg = new PnPStereoResidualReprojection();
alg.setModel(new StereoPose(worldToLeft, leftToRight));
// compute errors with perfect model
double[] error = new double[alg.getN()];
int index = alg.computeResiduals(pointPose.get(0), error, 0);
assertEquals(alg.getN(), index);
assertEquals(0, error[0], 1e-8);
assertEquals(0, error[1], 1e-8);
// compute errors with an incorrect model
worldToLeft.getR().set(2, 1, 2);
alg.setModel(new StereoPose(worldToLeft, leftToRight));
index = alg.computeResiduals(pointPose.get(0), error, 0);
assertEquals(alg.getN(), index);
assertTrue(Math.abs(error[0]) > 1e-8);
assertTrue(Math.abs(error[1]) > 1e-8);
}
@Test void compareToReprojection() {
Se3_F64 worldToLeft = new Se3_F64();
ConvertRotation3D_F64.eulerToMatrix(EulerType.XYZ, 0.1, 1, -0.2, worldToLeft.getR());
worldToLeft.getT().setTo(-0.3, 0.4, 1);
generateScene(10, worldToLeft, false);
// make the input model incorrect
worldToLeft.getR().set(2, 1, 2);
// compute the error in normalized image coordinates per element
PnPStereoResidualReprojection alg = new PnPStereoResidualReprojection();
alg.setModel(new StereoPose(worldToLeft, leftToRight));
// compute errors with perfect model
double[] error = new double[alg.getN()];
alg.computeResiduals(pointPose.get(0), error, 0);
double found = 0;
for (double e : error) {
found += e*e;
}
PnPStereoDistanceReprojectionSq validation = new PnPStereoDistanceReprojectionSq();
StereoParameters param = new StereoParameters();
param.right_to_left = this.param.right_to_left;
// intrinsic parameters are configured to be identical to normalized image coordinates
param.left = new CameraPinholeBrown(1, 1, 0, 0, 0, 0, 0).fsetRadial(0, 0);
param.right = new CameraPinholeBrown(1, 1, 0, 0, 0, 0, 0).fsetRadial(0, 0);
validation.setStereoParameters(param);
validation.setModel(worldToLeft);
double expected = validation.distance(pointPose.get(0));
assertEquals(expected, found, 1e-8);
}
}
| lessthanoptimal/BoofCV | main/boofcv-sfm/src/test/java/boofcv/alg/geo/pose/TestPnPStereoResidualReprojection.java | Java | apache-2.0 | 3,523 |
import {CollectionViewer} from '@angular/cdk/collections';
import {DataSource} from '@angular/cdk/table';
import {ChangeDetectionStrategy, Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator, PageEvent} from '@angular/material';
import {Store} from '@ngrx/store';
import {TranslateService} from '@ngx-translate/core';
import {Observable} from 'rxjs/Observable';
import {UtilService} from '../../../core/services/util.service';
import {Enlist} from '../../../shared/models/enlist';
import {
enlistActions, enlistHistoryPageActions, historyPageCount, historyPagePageSiz,
historyPageTasks
} from '../../store';
@Component({
selector: 'jwjh-enlist-history-page',
templateUrl: './enlist-history-page.component.html',
styleUrls: ['./enlist-history-page.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EnlistHistoryPageComponent extends DataSource<Enlist> implements OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
enlistDataSource = this;
displayedColumns = ['title', 'paymentMerchant', 'btns'];
enlists$: Observable<Enlist[]>;
count$: Observable<number>;
pageSize$: Observable<number>;
constructor(private store: Store<any>,
private translate: TranslateService,
private utilService: UtilService) {
super();
this.enlists$ = store.select(historyPageTasks);
this.count$ = store.select(historyPageCount);
this.pageSize$ = store.select(historyPagePageSiz);
this.store.dispatch(new enlistHistoryPageActions.List(0, 10));
}
ngOnInit(): void {
// todo provider MdPaginatorIntl
this.translate.get('PAGINATOR.ITEMSPERPAGELABEL')
.subscribe(s => this.paginator._intl.itemsPerPageLabel = s);
}
restart(task: Enlist) {
this.store.dispatch(new enlistActions.Restart(task.id));
}
delete(task: Enlist) {
this.utilService.showConfirm()
.subscribe(() => this.store.dispatch(new enlistActions.Delete(task.id)));
}
connect(collectionViewer: CollectionViewer): Observable<Enlist[]> {
return this.enlists$;
}
disconnect(collectionViewer: CollectionViewer): void {
}
onPage(ev: PageEvent) {
const pageSize = ev.pageSize;
const first = ev.pageIndex * pageSize;
this.store.dispatch(new enlistHistoryPageActions.List(first, pageSize));
}
}
| ixtf/japp-execution | client/src/app/enlist/containers/enlist-history-page/enlist-history-page.component.ts | TypeScript | apache-2.0 | 2,330 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.