code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
|---|---|---|---|---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `MultiTexCoord4f` mod in crate `gleam`.">
<meta name="keywords" content="rust, rustlang, rust-lang, MultiTexCoord4f">
<title>gleam::gl::MultiTexCoord4f - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a></p><script>window.sidebarCurrent = {name: 'MultiTexCoord4f', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content mod">
<h1 class='fqn'><span class='in-band'>Module <a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a class='mod' href=''>MultiTexCoord4f</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-43359' class='srclink' href='../../../src/gleam///home/servo/buildbot/slave/doc/build/target/debug/build/gleam-9662459d59abad25/out/gl_bindings.rs.html#14078-14094' title='goto source code'>[src]</a></span></h1>
<h2 id='reexports' class='section-header'><a href="#reexports">Reexports</a></h2>
<table><tr><td><code>use std::prelude::<a class='mod' href='../../../std/prelude/v1/index.html' title='std::prelude::v1'>v1</a>::*;</code></td></tr><tr><td><code>use super::{<a class='mod' href='../../../gleam/gl/storage/index.html' title='gleam::gl::storage'>storage</a>, <a class='fn' href='../../../gleam/gl/fn.metaloadfn.html' title='gleam::gl::metaloadfn'>metaloadfn</a>};</code></td></tr><tr><td><code>use super::<a class='struct' href='../../../gleam/gl/struct.FnPtr.html' title='gleam::gl::FnPtr'>FnPtr</a>;</code></td></tr></table><h2 id='functions' class='section-header'><a href="#functions">Functions</a></h2>
<table>
<tr class=' module-item'>
<td><a class='fn' href='fn.is_loaded.html'
title='gleam::gl::MultiTexCoord4f::is_loaded'>is_loaded</a></td>
<td class='docblock short'>
</td>
</tr>
<tr class=' module-item'>
<td><a class='fn' href='fn.load_with.html'
title='gleam::gl::MultiTexCoord4f::load_with'>load_with</a></td>
<td class='docblock short'>
</td>
</tr>
</table></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../../";
window.currentCrate = "gleam";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script async src="../../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
gleam/gl/MultiTexCoord4f/index.html
|
HTML
|
mpl-2.0
| 5,357
|
package common
import (
"context"
"fmt"
"log"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
)
// This step suppresses any messages that VMware product might show.
type StepSuppressMessages struct{}
func (s *StepSuppressMessages) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packersdk.Ui)
vmxPath := state.Get("vmx_path").(string)
log.Println("Suppressing messages in VMX")
if err := driver.SuppressMessages(vmxPath); err != nil {
err := fmt.Errorf("Error suppressing messages: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
}
func (s *StepSuppressMessages) Cleanup(state multistep.StateBag) {}
|
ricardclau/packer
|
builder/vmware/common/step_suppress_messages.go
|
GO
|
mpl-2.0
| 846
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `is_loaded` fn in crate `gleam`.">
<meta name="keywords" content="rust, rustlang, rust-lang, is_loaded">
<title>gleam::ffi::VertexAttribI1uiv::is_loaded - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>VertexAttribI1uiv</a></p><script>window.sidebarCurrent = {name: 'is_loaded', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>VertexAttribI1uiv</a>::<wbr><a class='fn' href=''>is_loaded</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-5211' class='srclink' href='../../../src/gleam/home/servo/buildbot/slave/doc/build/target/debug/build/gleam-8cc6d4d4d5b87928/out/gl_bindings.rs.html#5259-5261' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn is_loaded() -> <a class='primitive' href='../../../std/primitive.bool.html'>bool</a></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "gleam";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
gleam/ffi/VertexAttribI1uiv/fn.is_loaded.html
|
HTML
|
mpl-2.0
| 4,365
|
package org.playorm.nio.test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Logger;
import javax.net.ssl.SSLEngine;
import junit.framework.TestCase;
import org.playorm.nio.api.deprecated.ChannelServiceFactory;
import org.playorm.nio.api.libs.AsyncSSLEngine;
import org.playorm.nio.api.libs.BufferHelper;
import org.playorm.nio.api.libs.FactoryCreator;
import org.playorm.nio.api.libs.SSLEngineFactory;
import org.playorm.nio.api.libs.SSLListener;
import org.playorm.nio.api.testutil.CloneByteBuffer;
import org.playorm.nio.api.testutil.HandlerForTests;
import org.playorm.nio.api.testutil.MockSSLEngineFactory;
import biz.xsoftware.mock.CalledMethod;
import biz.xsoftware.mock.MockObject;
import biz.xsoftware.mock.MockObjectFactory;
/**
* Normally I would not separate out one class for testing, but when this
* is integrated with the ChanMgr, testing becomes non-deterministic with
* packets being separated and such. This allows more deterministic
* testing to fully test AsynchSSLEngine.
*
* @author dean.hiller
*/
public class TestNewAsynchSSLEngine2 extends TestCase {
private static final Logger log = Logger.getLogger(TestNewAsynchSSLEngine2.class.getName());
private BufferHelper helper = ChannelServiceFactory.bufferHelper(null);
private MockObject serverList = MockObjectFactory.createMock(SSLListener.class);
private MockObject clientList = MockObjectFactory.createMock(SSLListener.class);
private AsyncSSLEngine serverEngine;
private AsyncSSLEngine clientEngine;
@Override
protected void setUp() throws Exception {
HandlerForTests.setupLogging();
serverList.setDefaultBehavior("packetEncrypted", new CloneByteBuffer());
clientList.setDefaultBehavior("packetEncrypted", new CloneByteBuffer());
SSLEngineFactory sslEngineFactory = new MockSSLEngineFactory();
FactoryCreator creator = FactoryCreator.createFactory(null);
SSLEngine wrappedSvr = sslEngineFactory.createEngineForServerSocket();
serverEngine = creator.createSSLEngine("[serverAsynch] ", wrappedSvr, null);
serverEngine.setListener((SSLListener)serverList);
SSLEngine wrappedClient = sslEngineFactory.createEngineForSocket();
clientEngine = creator.createSSLEngine("[clientEngine] ", wrappedClient, null);
clientEngine.setListener((SSLListener)clientList);
}
@Override
protected void tearDown() throws Exception {
if(!clientEngine.isClosed())
closeWithExpects(clientEngine, clientList);
if(!serverEngine.isClosed())
closeWithExpects(serverEngine, serverList);
HandlerForTests.checkForWarnings();
clientList.expect(MockObject.NONE);
serverList.expect(MockObject.NONE);
}
private void closeWithExpects(AsyncSSLEngine engine, MockObject sslListener) throws IOException {
TestNewAsynchSSLEngine.closeWithExpects(engine, sslListener);
// engine.close();
//
// String[] methodNames = new String[2];
// methodNames[0] = "packetEncrypted";
// methodNames[1] = "closed";
// sslListener.expect(methodNames);
}
/**
* This tests the Runnable task being run in between packets such that it
* should not cause packet feeds to create new Runnables, and can
* run before all packets are in.
*/
public void testDelayedRunTask() throws Exception {
log.fine("B*******************************************");
clientEngine.beginHandshake();
CalledMethod m = clientList.expect("packetEncrypted");
ByteBuffer b = (ByteBuffer)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b, null);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
clientEngine.feedEncryptedPacket(b, null);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
serverEngine.feedEncryptedPacket(b0, null);
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b1, null);
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
//THIS IS THE DELAYED RUN TASK run after second feed of data to sslEngine...
r.run();
serverEngine.feedEncryptedPacket(b2, null);
String[] methodNames1 = new String[3];
methodNames1[0] = "packetEncrypted";
methodNames1[1] = "packetEncrypted";
methodNames1[2] = "encryptedLinkEstablished";
CalledMethod[] methods1 = serverList.expect(methodNames1);
ByteBuffer b01 = (ByteBuffer)methods1[0].getAllParams()[0];
clientEngine.feedEncryptedPacket(b01, null);
ByteBuffer b11 = (ByteBuffer)methods1[1].getAllParams()[0];
clientEngine.feedEncryptedPacket(b11, null);
clientList.expect("encryptedLinkEstablished");
log.fine("E*******************************************");
}
/**
* This tests the situation where the Runnable must tell the engine
* to reprocess the buffer itself.
*/
public void testReallyDelayedRunTask() throws Exception {
log.fine("B*******************************************");
clientEngine.beginHandshake();
CalledMethod m = clientList.expect("packetEncrypted");
ByteBuffer b = (ByteBuffer)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b, null);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
clientEngine.feedEncryptedPacket(b, null);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
serverEngine.feedEncryptedPacket(b0, null);
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b1, null);
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
serverEngine.feedEncryptedPacket(b2, null);
String[] methodNames1 = new String[3];
//THIS IS THE REALLY DELAYED RUN TASK run after all 3 packets are fed
//to ssl engine
r.run();
methodNames1[0] = "packetEncrypted";
methodNames1[1] = "packetEncrypted";
methodNames1[2] = "encryptedLinkEstablished";
CalledMethod[] methods1 = serverList.expect(methodNames1);
ByteBuffer b01 = (ByteBuffer)methods1[0].getAllParams()[0];
clientEngine.feedEncryptedPacket(b01, null);
ByteBuffer b11 = (ByteBuffer)methods1[1].getAllParams()[0];
clientEngine.feedEncryptedPacket(b11, null);
clientList.expect("encryptedLinkEstablished");
log.fine("E*******************************************");
}
public void testHalfPackets() throws Exception {
clientEngine.beginHandshake();
CalledMethod m = clientList.expect("packetEncrypted");
ByteBuffer b = (ByteBuffer)m.getAllParams()[0];
feedPacket(serverEngine, b);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
log.fine("remain1="+b.remaining());
feedPacket(clientEngine, b);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
feedPacket(serverEngine, b0);
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
feedPacket(serverEngine, b1);
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
feedPacket(serverEngine, b2);
methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "encryptedLinkEstablished";
methods = serverList.expect(methodNames);
b0 = (ByteBuffer)methods[0].getAllParams()[0];
feedPacket(clientEngine, b0);
b1 = (ByteBuffer)methods[1].getAllParams()[0];
feedPacket(clientEngine, b1);
clientList.expect("encryptedLinkEstablished");
}
public void testCombinedPackets() throws Exception {
clientEngine.beginHandshake();
CalledMethod m;
ByteBuffer b;
CalledMethod m1 = clientList.expect("packetEncrypted");
ByteBuffer b3 = (ByteBuffer)m1.getAllParams()[0];
serverEngine.feedEncryptedPacket(b3, null);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
clientEngine.feedEncryptedPacket(b, null);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
int total = b0.remaining()+b1.remaining()+b2.remaining();
ByteBuffer combined = ByteBuffer.allocate(total);
combined.put(b0);
combined.put(b1);
combined.put(b2);
helper.doneFillingBuffer(combined);
serverEngine.feedEncryptedPacket(combined, null);
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "encryptedLinkEstablished";
methods = serverList.expect(methodNames);
b0 = (ByteBuffer)methods[0].getAllParams()[0];
b1 = (ByteBuffer)methods[1].getAllParams()[0];
total = b0.remaining()+b1.remaining();
combined = ByteBuffer.allocate(total);
combined.put(b0);
combined.put(b1);
helper.doneFillingBuffer(combined);
clientEngine.feedEncryptedPacket(combined, null);
clientList.expect("encryptedLinkEstablished");
}
public void testOneAndHalfPackets() throws Exception {
clientEngine.beginHandshake();
CalledMethod m = clientList.expect("packetEncrypted");
ByteBuffer b = (ByteBuffer)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b, null);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
clientEngine.feedEncryptedPacket(b, null);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
int total = b0.remaining()+b1.remaining()+b2.remaining();
ByteBuffer combined = ByteBuffer.allocate(total);
combined.put(b0);
int lim = b1.limit();
b1.limit(3); //we only want to put part of b1 in payload
combined.put(b1);
helper.doneFillingBuffer(combined);
serverEngine.feedEncryptedPacket(combined, null);
combined.clear();
b1.limit(lim);
combined.put(b1);
combined.put(b2);
helper.doneFillingBuffer(combined);
serverEngine.feedEncryptedPacket(combined, null);
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "encryptedLinkEstablished";
methods = serverList.expect(methodNames);
b0 = (ByteBuffer)methods[0].getAllParams()[0];
b1 = (ByteBuffer)methods[1].getAllParams()[0];
total = b0.remaining()+b1.remaining();
combined = ByteBuffer.allocate(total);
combined.put(b0);
combined.put(b1);
helper.doneFillingBuffer(combined);
clientEngine.feedEncryptedPacket(combined, null);
clientList.expect("encryptedLinkEstablished");
}
public void testRunInMiddleOfPacket() throws Exception {
log.fine("B*******************************************");
clientEngine.beginHandshake();
CalledMethod m = clientList.expect("packetEncrypted");
ByteBuffer b = (ByteBuffer)m.getAllParams()[0];
serverEngine.feedEncryptedPacket(b, null);
m = serverList.expect("runTask");
Runnable r = (Runnable)m.getAllParams()[0];
r.run();
m = serverList.expect("packetEncrypted");
b = (ByteBuffer)m.getAllParams()[0];
clientEngine.feedEncryptedPacket(b, null);
m = clientList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
r.run();
String[] methodNames = new String[3];
methodNames[0] = "packetEncrypted";
methodNames[1] = "packetEncrypted";
methodNames[2] = "packetEncrypted";
CalledMethod[] methods = clientList.expect(methodNames);
ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0];
ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0];
ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0];
serverEngine.feedEncryptedPacket(b0, null);
m = serverList.expect("runTask");
r = (Runnable)m.getAllParams()[0];
int total = b1.remaining()+b2.remaining();
ByteBuffer combined = ByteBuffer.allocate(total);
int lim = b1.limit();
b1.limit(3); //we only want to put part of b1 in payload
combined.put(b1);
helper.doneFillingBuffer(combined);
serverEngine.feedEncryptedPacket(combined, null);
//run the task after some of the previous packet fed, then feed rest of packet
r.run();
combined.clear();
b1.limit(lim);
combined.put(b1);
combined.put(b2);
helper.doneFillingBuffer(combined);
serverEngine.feedEncryptedPacket(combined, null);
String[] methodNames1 = new String[3];
methodNames1[0] = "packetEncrypted";
methodNames1[1] = "packetEncrypted";
methodNames1[2] = "encryptedLinkEstablished";
CalledMethod[] methods1 = serverList.expect(methodNames1);
b0 = (ByteBuffer)methods1[0].getAllParams()[0];
clientEngine.feedEncryptedPacket(b0, null);
b1 = (ByteBuffer)methods1[1].getAllParams()[0];
clientEngine.feedEncryptedPacket(b1, null);
clientList.expect("encryptedLinkEstablished");
}
private void feedPacket(AsyncSSLEngine engine, ByteBuffer b) throws Exception {
TestNewAsynchSSLEngine.feedPacket(engine, b);
}
}
|
deanhiller/channelmanager2
|
input/javasrc/org/playorm/nio/test/TestNewAsynchSSLEngine2.java
|
Java
|
mpl-2.0
| 15,075
|
/*此标记表明此文件可被设计器更新,如果不允许此操作,请删除此行代码.design by:agebull designer date:2019/4/10 10:44:52*/
#region
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using Newtonsoft.Json;
using System.Data.Sql;
using Agebull.Common;
using Agebull.Common.OAuth;
using Agebull.EntityModel.Common;
using Agebull.EntityModel.SqlServer;
using Agebull.EntityModel.BusinessLogic.SqlServer;
using HPC.Projects.DataAccess;
#endregion
namespace HPC.Projects.BusinessLogic
{
/// <summary>
/// 用户
/// </summary>
public sealed partial class UserBusinessLogic : UiBusinessLogicBase<UserData,UserDataAccess,HpcSqlServerDb>
{
/*// <summary>
/// 保存前的操作
/// </summary>
/// <param name="data">数据</param>
/// <param name="isAdd">是否为新增</param>
/// <returns>如果为否将阻止后续操作</returns>
protected override bool OnSaving(UserData data, bool isAdd)
{
return base.OnSaving(data, isAdd);
}
/// <summary>
/// 保存完成后的操作
/// </summary>
/// <param name="data">数据</param>
/// <param name="isAdd">是否为新增</param>
/// <returns>如果为否将阻止后续操作</returns>
protected override bool OnSaved(UserData data, bool isAdd)
{
return base.OnSaved(data, isAdd);
}
/// <summary>
/// 被用户编辑的数据的保存前操作
/// </summary>
/// <param name="data">数据</param>
/// <param name="isAdd">是否为新增</param>
/// <returns>如果为否将阻止后续操作</returns>
protected override bool LastSavedByUser(UserData data, bool isAdd)
{
return base.LastSavedByUser(data, isAdd);
}
/// <summary>
/// 被用户编辑的数据的保存前操作
/// </summary>
/// <param name="data">数据</param>
/// <param name="isAdd">是否为新增</param>
/// <returns>如果为否将阻止后续操作</returns>
protected override bool PrepareSaveByUser(UserData data, bool isAdd)
{
return base.PrepareSaveByUser(data, isAdd);
}*/
}
}
|
agebullhu/AgebullDesigner
|
demo/src/HPC/HpcUser/Model/Business/User/UserBusinessLogic.cs
|
C#
|
mpl-2.0
| 2,573
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `ARRAY_BUFFER` constant in crate `servo`.">
<meta name="keywords" content="rust, rustlang, rust-lang, ARRAY_BUFFER">
<title>servo::gl::ARRAY_BUFFER - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a></p><script>window.sidebarCurrent = {name: 'ARRAY_BUFFER', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a>::<wbr><a class='constant' href=''>ARRAY_BUFFER</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-822' class='srclink' href='../../gleam/ffi/constant.ARRAY_BUFFER.html?gotosrc=822' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const ARRAY_BUFFER: <a class='primitive' href='../../std/primitive.u32.html'>u32</a><code> = </code><code>34962</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "servo";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
servo/gl/constant.ARRAY_BUFFER.html
|
HTML
|
mpl-2.0
| 4,199
|
/*global define*/
define('app/reload-addon-reloaded-per-user', ['lodash', 'TelemetryPromises', 'DevToolsMetrics', 'LatestVersions', 'FIREFOX_RELEASES'],
function(_, T, DevToolsMetrics, LatestVersions, FIREFOX_RELEASES) {
var metric = 'DEVTOOLS_RELOAD_ADDON_RELOAD_PER_USER_FLAG';
var options = { sanitized: false };
var ID = 'devtools-reload-addon-reloaded-per-user-chart';
var chart = {
title: 'Reload Addon Reloaded per User / Release (MAU)',
description: 'Per user, per release metric indicating the DevTools are being reloaded at least once',
width: 335,
height: 320,
left: 60,
legend: T.ALL_CHANNELS.filter((c) => c === 'nightly'),
markers: FIREFOX_RELEASES.nightly,
colors: _.values(FIREFOX_RELEASES.colors),
legend_target: '#' + ID + '-legend'
};
function evolutionMap(channel, evolutions) {
// map the data into the values we need
// histogram, index, date
return evolutions.map((h, i, date) => {
return {
channel: channel,
value: h.sum,
date: date
};
});
}
DevToolsMetrics.line(ID, chart);
LatestVersions.getLatestVersion().then((versions) => {
versions = _.filter(versions, { channel: "nightly"});
Promise.all(versions.map((target) => {
target.versions = [_.max(target.versions)];
return T.getEvolutions(target.channel, target.versions, metric, options).
then((evolutions) => T.reduceEvolutions(evolutions)).
then((evolutions) => evolutionMap(target.channel, evolutions)).
then(_.flatten);
})).then((data) => {
chart.data = data;
DevToolsMetrics.line(ID, chart);
});
});
}); // end define
|
clarkbw/devtools-metrics
|
js/app/reload-addon-reloaded-per-user.js
|
JavaScript
|
mpl-2.0
| 1,694
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html data-context="Build Apps" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>le_updateCtrl_interface.h File Reference - Legato Docs</title>
<meta content="legato™ is an open source Linux-based embedded platform designed to simplify connected IoT application development" name="description"/>
<meta content="legato, iot" name="keywords"/>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>
<meta content="19.02.0" name="legato-version"/>
<link href="resources/images/legato.ico" rel="shortcut icon"/>
<link href="resources/images/legato.ico" rel="icon" type="image/x-icon"/>
<link href="resources/images/legato.ico" rel="shortcut icon" type="image/x-icon"/>
<link href="resources/images/legato.ico" rel="apple-touch-icon" type="image/x-icon"/>
<link href="resources/css/style.css" media="screen" rel="stylesheet" type="text/css"/>
<link href="resources/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<!--[if IE]>
<script src="resources/js/html5shiv.js"></script>
<script src="resources/js/respond.js"></script>
<![endif]-->
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="resources/js/main.js"></script>
<script src="tocs/Build_Apps_API_Guides.json"></script>
</head>
<body>
<noscript>
<input class="modal-closing-trick" id="modal-closing-trick" type="checkbox"/>
<div id="nojs">
<label for="modal-closing-trick">
<span>You seem to not have Javascript <a href="http://enable-javascript.com">enabled</a>, so site functionality like the search and navigation tree won't work.</span>
</label>
</div>
</noscript>
<div class="wrapper">
<div class="fa fa-bars documentation" id="menu-trigger"></div>
<div id="top">
<header>
<nav>
<a class="navlink" href="/">Introduction</a><a class="navlink selected" href="buildAppsMain.html">Build Apps</a><a class="navlink" href="buildPlatformMain.html">Build Platform</a><a class="navlink" href="aboutMain.html">About</a>
</nav>
</header>
</div>
<div class="white" id="menudocumentation">
<header>
<a href="/"> <img alt="Back to Legato Homepage" id="logo" src="resources/images/legato_logo.png"/></a>
<h2>/ Build Apps</h2>
<nav class="secondary">
<a href="getStarted.html">Get Started</a><a href="concepts.html">Concepts</a><a class="link-selected" href="apiGuidesMain.html">API Guides</a><a href="tools.html">Tools</a><a href="howToMain.html">How To</a>
</nav>
<nav class="ui-front">
<i class="fa fa-search" id="search-icon"></i>
<input id="searchbox" placeholder="Search"/>
</nav>
</header>
</div>
<div id="resizable">
<div id="left">
<div id="tree1"></div>
</div>
</div>
<div class="content">
<div class="header">
<div class="summary">
<a href="#typedef-members">Typedefs</a> |
<a href="#enum-members">Enumerations</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<h1 class="title">le_updateCtrl_interface.h File Reference</h1> </div>
</div><div class="contents">
<div class="textblock"><code>#include "<a class="el" href="legato_8h_source.html">legato.h</a>"</code><br/>
</div>
<p><a href="le__updateCtrl__interface_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a>
Typedefs</h2></td></tr>
<tr class="memitem:a3bca9a80fd9e0d9e877a9cd8c2e0d650"><td align="right" class="memItemLeft" valign="top">typedef void(* </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a3bca9a80fd9e0d9e877a9cd8c2e0d650">le_updateCtrl_DisconnectHandler_t</a>) (void *)</td></tr>
<tr class="separator:a3bca9a80fd9e0d9e877a9cd8c2e0d650"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="enum-members"></a>
Enumerations</h2></td></tr>
<tr class="memitem:a0e65bfd2d86ab1ad2ee2e5fafae461ee"><td align="right" class="memItemLeft" valign="top">enum </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461ee">le_updateCtrl_SystemState_t</a> { <a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461eea9fb9401e89dc969fd974052f68ed436c">LE_UPDATECTRL_SYSTEMSTATE_GOOD</a> = 0,
<a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461eea7624900fa978ad25293fe92bde6ed50d">LE_UPDATECTRL_SYSTEMSTATE_BAD</a> = 1,
<a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461eea6c50c6e092ac98c3c955a6f903d3dfec">LE_UPDATECTRL_SYSTEMSTATE_PROBATION</a> = 2
}</td></tr>
<tr class="separator:a0e65bfd2d86ab1ad2ee2e5fafae461ee"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a1e59368455d91b7bf8a1e6bf4a04b672"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a1e59368455d91b7bf8a1e6bf4a04b672">le_updateCtrl_ConnectService</a> (void)</td></tr>
<tr class="separator:a1e59368455d91b7bf8a1e6bf4a04b672"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a02f087a33d15d3ed9dc5f67f64bfd104"><td align="right" class="memItemLeft" valign="top"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a02f087a33d15d3ed9dc5f67f64bfd104">le_updateCtrl_TryConnectService</a> (void)</td></tr>
<tr class="separator:a02f087a33d15d3ed9dc5f67f64bfd104"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7433ec6d73597f5783f8ab5c22a8a853"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a7433ec6d73597f5783f8ab5c22a8a853">le_updateCtrl_SetServerDisconnectHandler</a> (<a class="el" href="le__updateCtrl__interface_8h.html#a3bca9a80fd9e0d9e877a9cd8c2e0d650">le_updateCtrl_DisconnectHandler_t</a> disconnectHandler, void *contextPtr)</td></tr>
<tr class="separator:a7433ec6d73597f5783f8ab5c22a8a853"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:afaa9e08b6a161e3107c7f328d8dee1ed"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#afaa9e08b6a161e3107c7f328d8dee1ed">le_updateCtrl_DisconnectService</a> (void)</td></tr>
<tr class="separator:afaa9e08b6a161e3107c7f328d8dee1ed"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acdbc9dcc05455f0dd1020b875909c3ed"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#acdbc9dcc05455f0dd1020b875909c3ed">le_updateCtrl_Defer</a> (void)</td></tr>
<tr class="separator:acdbc9dcc05455f0dd1020b875909c3ed"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab3955f0e34df43a5fbe3e9eae16040d4"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#ab3955f0e34df43a5fbe3e9eae16040d4">le_updateCtrl_Allow</a> (void)</td></tr>
<tr class="separator:ab3955f0e34df43a5fbe3e9eae16040d4"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a88e55c6e0ee5c2cf52e6fcb75a9db87e"><td align="right" class="memItemLeft" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a88e55c6e0ee5c2cf52e6fcb75a9db87e">le_updateCtrl_LockProbation</a> (void)</td></tr>
<tr class="separator:a88e55c6e0ee5c2cf52e6fcb75a9db87e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a4ba5ace59bfe352c518c3f1eae6d0448"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a4ba5ace59bfe352c518c3f1eae6d0448">le_updateCtrl_UnlockProbation</a> (void)</td></tr>
<tr class="separator:a4ba5ace59bfe352c518c3f1eae6d0448"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8eaa5f533d5d677397642c7b44ce7bb3"><td align="right" class="memItemLeft" valign="top"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a8eaa5f533d5d677397642c7b44ce7bb3">le_updateCtrl_MarkGood</a> (bool force)</td></tr>
<tr class="separator:a8eaa5f533d5d677397642c7b44ce7bb3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9f6a3bf7a830eb04823ea6188c12109c"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#a9f6a3bf7a830eb04823ea6188c12109c">le_updateCtrl_FailProbation</a> (void)</td></tr>
<tr class="separator:a9f6a3bf7a830eb04823ea6188c12109c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab68e770c5caa42a6cd463a2827fe371e"><td align="right" class="memItemLeft" valign="top"><a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461ee">le_updateCtrl_SystemState_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="le__updateCtrl__interface_8h.html#ab68e770c5caa42a6cd463a2827fe371e">le_updateCtrl_GetSystemState</a> (void)</td></tr>
<tr class="separator:ab68e770c5caa42a6cd463a2827fe371e"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a id="details" name="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Legato <a class="el" href="c_updateCtrl.html">Update Control API</a> include file.</p>
<p class="copyright">Copyright (C) Sierra Wireless Inc. </p>
</div><h2 class="groupheader">Typedef Documentation</h2>
<a id="a3bca9a80fd9e0d9e877a9cd8c2e0d650"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a3bca9a80fd9e0d9e877a9cd8c2e0d650">◆ </a></span>le_updateCtrl_DisconnectHandler_t</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">typedef void(* le_updateCtrl_DisconnectHandler_t) (void *)</td>
</tr>
</table>
</div><div class="memdoc">
<p>Type for handler called when a server disconnects. </p>
</div>
</div>
<h2 class="groupheader">Enumeration Type Documentation</h2>
<a id="a0e65bfd2d86ab1ad2ee2e5fafae461ee"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a0e65bfd2d86ab1ad2ee2e5fafae461ee">◆ </a></span>le_updateCtrl_SystemState_t</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">enum <a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461ee">le_updateCtrl_SystemState_t</a></td>
</tr>
</table>
</div><div class="memdoc">
<p>State of the system. </p>
<table class="fieldtable">
<tr><th colspan="2">Enumerator</th></tr><tr><td class="fieldname"><a id="a0e65bfd2d86ab1ad2ee2e5fafae461eea9fb9401e89dc969fd974052f68ed436c"></a>LE_UPDATECTRL_SYSTEMSTATE_GOOD </td><td class="fielddoc"><p>"good" </p>
</td></tr>
<tr><td class="fieldname"><a id="a0e65bfd2d86ab1ad2ee2e5fafae461eea7624900fa978ad25293fe92bde6ed50d"></a>LE_UPDATECTRL_SYSTEMSTATE_BAD </td><td class="fielddoc"><p>"bad" </p>
</td></tr>
<tr><td class="fieldname"><a id="a0e65bfd2d86ab1ad2ee2e5fafae461eea6c50c6e092ac98c3c955a6f903d3dfec"></a>LE_UPDATECTRL_SYSTEMSTATE_PROBATION </td><td class="fielddoc"><p>"tried N" or untried. </p>
</td></tr>
</table>
</div>
</div>
<h2 class="groupheader">Function Documentation</h2>
<a id="ab3955f0e34df43a5fbe3e9eae16040d4"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ab3955f0e34df43a5fbe3e9eae16040d4">◆ </a></span>le_updateCtrl_Allow()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_Allow </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Allow updates to go ahead. </p>
</div>
</div>
<a id="a1e59368455d91b7bf8a1e6bf4a04b672"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a1e59368455d91b7bf8a1e6bf4a04b672">◆ </a></span>le_updateCtrl_ConnectService()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_ConnectService </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Connect the current client thread to the service providing this API. Block until the service is available.</p>
<p>For each thread that wants to use this API, either ConnectService or TryConnectService must be called before any other functions in this API. Normally, ConnectService is automatically called for the main thread, but not for any other thread. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p>
<p>This function is created automatically. </p>
</div>
</div>
<a id="acdbc9dcc05455f0dd1020b875909c3ed"></a>
<h2 class="memtitle"><span class="permalink"><a href="#acdbc9dcc05455f0dd1020b875909c3ed">◆ </a></span>le_updateCtrl_Defer()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_Defer </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Prevent all updates (and roll-backs) until further notice. </p>
</div>
</div>
<a id="afaa9e08b6a161e3107c7f328d8dee1ed"></a>
<h2 class="memtitle"><span class="permalink"><a href="#afaa9e08b6a161e3107c7f328d8dee1ed">◆ </a></span>le_updateCtrl_DisconnectService()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_DisconnectService </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Disconnect the current client thread from the service providing this API.</p>
<p>Normally, this function doesn't need to be called. After this function is called, there's no longer a connection to the service, and the functions in this API can't be used. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p>
<p>This function is created automatically. </p>
</div>
</div>
<a id="a9f6a3bf7a830eb04823ea6188c12109c"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a9f6a3bf7a830eb04823ea6188c12109c">◆ </a></span>le_updateCtrl_FailProbation()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_FailProbation </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Marks the system "bad" and triggers a roll-back to a "good" system.</p>
<dl class="section note"><dt>Note</dt><dd>Ignored if the probation period has already ended. Also, the roll-back may be delayed if someone is deferring updates using <a class="el" href="le__updateCtrl__interface_8h.html#acdbc9dcc05455f0dd1020b875909c3ed">le_updateCtrl_Defer()</a>. </dd></dl>
</div>
</div>
<a id="ab68e770c5caa42a6cd463a2827fe371e"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ab68e770c5caa42a6cd463a2827fe371e">◆ </a></span>le_updateCtrl_GetSystemState()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="le__updateCtrl__interface_8h.html#a0e65bfd2d86ab1ad2ee2e5fafae461ee">le_updateCtrl_SystemState_t</a> le_updateCtrl_GetSystemState </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Get the current system state.</p>
<dl class="section note"><dt>Note</dt><dd>Can only be called if updates have been deferred or if a probation lock is held. Otherwise the system state could change between the time this function is called and when the return value is checked. </dd></dl>
</div>
</div>
<a id="a88e55c6e0ee5c2cf52e6fcb75a9db87e"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a88e55c6e0ee5c2cf52e6fcb75a9db87e">◆ </a></span>le_updateCtrl_LockProbation()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool le_updateCtrl_LockProbation </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Prevent the probation period from ending.</p>
<dl class="section return"><dt>Returns</dt><dd>false if lock failed (for example if not in a probation period). </dd></dl>
</div>
</div>
<a id="a8eaa5f533d5d677397642c7b44ce7bb3"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a8eaa5f533d5d677397642c7b44ce7bb3">◆ </a></span>le_updateCtrl_MarkGood()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> le_updateCtrl_MarkGood </td>
<td>(</td>
<td class="paramtype">bool </td>
<td class="paramname"><em>force</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Marks the system "good", ending the probation period.</p>
<dl class="section return"><dt>Returns</dt><dd><ul>
<li>LE_OK The system was marked Good</li>
<li>LE_BUSY Someone holds a probation lock</li>
<li>LE_DUPLICATE Probation has expired - the system has already been marked </li>
</ul>
</dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramdir">[in]</td><td class="paramname">force</td><td>True to set system Good even if someone holds a probation lock </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a id="a7433ec6d73597f5783f8ab5c22a8a853"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a7433ec6d73597f5783f8ab5c22a8a853">◆ </a></span>le_updateCtrl_SetServerDisconnectHandler()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_SetServerDisconnectHandler </td>
<td>(</td>
<td class="paramtype"><a class="el" href="le__updateCtrl__interface_8h.html#a3bca9a80fd9e0d9e877a9cd8c2e0d650">le_updateCtrl_DisconnectHandler_t</a> </td>
<td class="paramname"><em>disconnectHandler</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void * </td>
<td class="paramname"><em>contextPtr</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Set handler called when server disconnection is detected.</p>
<p>When a server connection is lost, call this handler then exit with LE_FATAL. If a program wants to continue without exiting, it should call longjmp() from inside the handler. </p>
</div>
</div>
<a id="a02f087a33d15d3ed9dc5f67f64bfd104"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a02f087a33d15d3ed9dc5f67f64bfd104">◆ </a></span>le_updateCtrl_TryConnectService()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> le_updateCtrl_TryConnectService </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Try to connect the current client thread to the service providing this API. Return with an error if the service is not available.</p>
<p>For each thread that wants to use this API, either ConnectService or TryConnectService must be called before any other functions in this API. Normally, ConnectService is automatically called for the main thread, but not for any other thread. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p>
<p>This function is created automatically.</p>
<dl class="section return"><dt>Returns</dt><dd><ul>
<li>LE_OK if the client connected successfully to the service.</li>
<li>LE_UNAVAILABLE if the server is not currently offering the service to which the client is bound.</li>
<li>LE_NOT_PERMITTED if the client interface is not bound to any service (doesn't have a binding).</li>
<li>LE_COMM_ERROR if the Service Directory cannot be reached. </li>
</ul>
</dd></dl>
</div>
</div>
<a id="a4ba5ace59bfe352c518c3f1eae6d0448"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a4ba5ace59bfe352c518c3f1eae6d0448">◆ </a></span>le_updateCtrl_UnlockProbation()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void le_updateCtrl_UnlockProbation </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Cancels a call to LockProbation(), allow the probation period to end.</p>
<dl class="section note"><dt>Note</dt><dd>Must match previous successful call to LockProbation(). </dd></dl>
</div>
</div>
</div>
<br clear="left"/>
</div>
</div>
<link href="resources/css/jqtree.css" rel="stylesheet" type="text/css"/>
<script src="resources/js/tree.jquery.js" type="text/javascript"></script>
<script src="resources/js/jquery.cookie.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="resources/css/perfect-scrollbar.min.css" rel="stylesheet"/>
<script src="resources/js/perfect-scrollbar.jquery.min.js"></script>
</body>
</html>
|
legatoproject/legato-docs
|
19_02/le__updateCtrl__interface_8h.html
|
HTML
|
mpl-2.0
| 22,099
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XK_kana_HA` constant in crate `x11_dl`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XK_kana_HA">
<title>x11_dl::keysym::XK_kana_HA - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a></p><script>window.sidebarCurrent = {name: 'XK_kana_HA', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a>::<wbr><a class='constant' href=''>XK_kana_HA</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-3995' class='srclink' href='../../src/x11_dl/keysym.rs.html#530' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XK_kana_HA: <a class='type' href='../../libc/types/os/arch/c95/type.c_uint.html' title='libc::types::os::arch::c95::c_uint'>c_uint</a><code> = </code><code>0x4ca</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div>
<div class="shortcuts">
<h1>Keyboard Shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search Tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "x11_dl";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
susaing/doc.servo.org
|
x11_dl/keysym/constant.XK_kana_HA.html
|
HTML
|
mpl-2.0
| 3,990
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XICCEncodingStyle` type in crate `x11`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XICCEncodingStyle">
<title>x11::xlib::XICCEncodingStyle - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a></p><script>window.sidebarCurrent = {name: 'XICCEncodingStyle', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content type">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a>::<wbr><a class='type' href=''>XICCEncodingStyle</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-7956' class='srclink' href='../../src/x11/xlib.rs.html#953' title='goto source code'>[src]</a></span></h1>
<pre class='rust typedef'>type XICCEncodingStyle = <a class='type' href='../../std/os/raw/type.c_int.html' title='std::os::raw::c_int'>c_int</a>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "x11";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
x11/xlib/type.XICCEncodingStyle.html
|
HTML
|
mpl-2.0
| 4,180
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `PTRACE_POKEDATA` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, PTRACE_POKEDATA">
<title>libc::notbsd::linux::PTRACE_POKEDATA - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>notbsd</a>::<wbr><a href='index.html'>linux</a></p><script>window.sidebarCurrent = {name: 'PTRACE_POKEDATA', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>notbsd</a>::<wbr><a href='index.html'>linux</a>::<wbr><a class='constant' href=''>PTRACE_POKEDATA</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-3043' class='srclink' href='../../../src/libc/unix/notbsd/linux/other/mod.rs.html#396' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const PTRACE_POKEDATA: <a class='type' href='../../../libc/type.c_uint.html' title='libc::c_uint'>c_uint</a><code> = </code><code>5</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "libc";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
libc/notbsd/linux/constant.PTRACE_POKEDATA.html
|
HTML
|
mpl-2.0
| 4,561
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `new_window_proxy_handler` fn in crate `script`.">
<meta name="keywords" content="rust, rustlang, rust-lang, new_window_proxy_handler">
<title>script::dom::browsingcontext::new_window_proxy_handler - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../index.html'>script</a>::<wbr><a href='../index.html'>dom</a>::<wbr><a href='index.html'>browsingcontext</a></p><script>window.sidebarCurrent = {name: 'new_window_proxy_handler', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>script</a>::<wbr><a href='../index.html'>dom</a>::<wbr><a href='index.html'>browsingcontext</a>::<wbr><a class='fn' href=''>new_window_proxy_handler</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-101164' class='srclink' href='../../../src/script/dom/browsingcontext.rs.html#407-411' title='goto source code'>[src]</a></span></h1>
<pre class='rust fn'>pub fn new_window_proxy_handler() -> <a class='struct' href='../../../script/dom/bindings/utils/struct.WindowProxyHandler.html' title='script::dom::bindings::utils::WindowProxyHandler'>WindowProxyHandler</a></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../";
window.currentCrate = "script";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script defer src="../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
script/dom/browsingcontext/fn.new_window_proxy_handler.html
|
HTML
|
mpl-2.0
| 4,482
|
@echo off
set ANT_OPTS=-Xmx256m
ant -f mirth-build.xml
pause
|
encapturemd/MirthConnect
|
server/build.bat
|
Batchfile
|
mpl-2.0
| 63
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Utility functions for doubly-linked lists.
use std::collections::LinkedList;
use std::mem;
/// Splits the head off a list in O(1) time, and returns the head.
pub fn split_off_head<T>(list: &mut LinkedList<T>) -> LinkedList<T> {
// FIXME: Work around https://github.com/rust-lang/rust/issues/22244
if list.len() == 1 {
return mem::replace(list, LinkedList::new());
}
let tail = list.split_off(1);
mem::replace(list, tail)
}
/// Prepends the items in the other list to this one, leaving the other list empty.
#[inline]
pub fn prepend_from<T>(this: &mut LinkedList<T>, other: &mut LinkedList<T>) {
other.append(this);
mem::swap(this, other);
}
|
Adenilson/prototype-viewing-distance
|
components/util/dlist.rs
|
Rust
|
mpl-2.0
| 890
|
package services.ntr.pms.model.history;
import java.sql.Timestamp;
import services.ntr.pms.service.information.Nameable;
public class TransactionHistory implements Nameable{
private int transactionId;
private int amount;
private String type;
private long payoutTime;
private long payerAccountId;
private String payerNickname; //This does not come from the SQL
public int getTransactionId() {
return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getPayoutTime() {
return payoutTime;
}
public void setPayoutTime(long payoutTime) {
this.payoutTime = payoutTime;
}
public long getPayerAccountId() {
return payerAccountId;
}
public void setPayerAccountId(long payerAccountId) {
this.payerAccountId = payerAccountId;
}
public String getPayerNickname() {
return payerNickname;
}
public void setPayerNickname(String payerNickname) {
this.payerNickname = payerNickname;
}
/* Helper Methods------------------------------------------------- */
public void setPayoutTimeUsingTimestamp(Timestamp timestamp) {
long time = timestamp.getTime();
long payoutTime = time;
this.payoutTime = payoutTime;
}
//Used for Namable interface
@Override
public void setNickname(String nickname) {
this.payerNickname = nickname;
}
@Override
public String getNickname() {
return this.payerNickname;
}
@Override
public long getAccountId() {
return this.payerAccountId;
}
@Override
public String toString() {
return "TransactionHistory [transactionId=" + transactionId + ", amount=" + amount + ", type=" + type
+ ", payoutTime=" + payoutTime + ", payerAccountId=" + payerAccountId + "]";
}
}
|
NYPD/pms
|
src/services/ntr/pms/model/history/TransactionHistory.java
|
Java
|
mpl-2.0
| 1,929
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `GLXPbufferSGIX` type in crate `glutin`.">
<meta name="keywords" content="rust, rustlang, rust-lang, GLXPbufferSGIX">
<title>glutin::api::x11::ffi::glx_extra::types::GLXPbufferSGIX - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../../../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../../../../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../../../../../index.html'>glutin</a>::<wbr><a href='../../../../index.html'>api</a>::<wbr><a href='../../../index.html'>x11</a>::<wbr><a href='../../index.html'>ffi</a>::<wbr><a href='../index.html'>glx_extra</a>::<wbr><a href='index.html'>types</a></p><script>window.sidebarCurrent = {name: 'GLXPbufferSGIX', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content type">
<h1 class='fqn'><span class='in-band'><a href='../../../../../index.html'>glutin</a>::<wbr><a href='../../../../index.html'>api</a>::<wbr><a href='../../../index.html'>x11</a>::<wbr><a href='../../index.html'>ffi</a>::<wbr><a href='../index.html'>glx_extra</a>::<wbr><a href='index.html'>types</a>::<wbr><a class='type' href=''>GLXPbufferSGIX</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-2876' class='srclink' href='../../../../../../src/glutin/home/servo/buildbot/slave/doc/build/target/debug/build/servo-glutin-0450dfa97fa62eff/out/glx_extra_bindings.rs.html#119' title='goto source code'>[src]</a></span></h1>
<pre class='rust typedef'>type GLXPbufferSGIX = <a class='type' href='../../../../../../glutin/api/x11/ffi/glx_extra/types/type.XID.html' title='glutin::api::x11::ffi::glx_extra::types::XID'>XID</a>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../../../../../";
window.currentCrate = "glutin";
window.playgroundUrl = "";
</script>
<script src="../../../../../../jquery.js"></script>
<script src="../../../../../../main.js"></script>
<script defer src="../../../../../../search-index.js"></script>
</body>
</html>
|
servo/doc.servo.org
|
glutin/api/x11/ffi/glx_extra/types/type.GLXPbufferSGIX.html
|
HTML
|
mpl-2.0
| 4,829
|
class A(object):
def something(self):
return 3
|
caterinaurban/Typpete
|
typpete/unittests/inference/explicit_object_superclass.py
|
Python
|
mpl-2.0
| 58
|
package aws
import (
"errors"
"fmt"
"log"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func init() {
resource.AddTestSweepers("aws_autoscaling_group", &resource.Sweeper{
Name: "aws_autoscaling_group",
F: testSweepAutoscalingGroups,
})
}
func testSweepAutoscalingGroups(region string) error {
client, err := sharedClientForRegion(region)
if err != nil {
return fmt.Errorf("error getting client: %s", err)
}
conn := client.(*AWSClient).autoscalingconn
resp, err := conn.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{})
if err != nil {
if testSweepSkipSweepError(err) {
log.Printf("[WARN] Skipping AutoScaling Group sweep for %s: %s", region, err)
return nil
}
return fmt.Errorf("Error retrieving AutoScaling Groups in Sweeper: %s", err)
}
if len(resp.AutoScalingGroups) == 0 {
log.Print("[DEBUG] No aws autoscaling groups to sweep")
return nil
}
for _, asg := range resp.AutoScalingGroups {
var testOptGroup bool
for _, testName := range []string{"foobar", "terraform-", "tf-test", "tf-asg-"} {
if strings.HasPrefix(*asg.AutoScalingGroupName, testName) {
testOptGroup = true
break
}
}
if !testOptGroup {
continue
}
deleteopts := autoscaling.DeleteAutoScalingGroupInput{
AutoScalingGroupName: asg.AutoScalingGroupName,
ForceDelete: aws.Bool(true),
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil {
if awserr, ok := err.(awserr.Error); ok {
switch awserr.Code() {
case "InvalidGroup.NotFound":
return nil
case "ResourceInUse", "ScalingActivityInProgress":
return resource.RetryableError(awserr)
}
}
// Didn't recognize the error, so shouldn't retry.
return resource.NonRetryableError(err)
}
// Successful delete
return nil
})
if err != nil {
return err
}
}
return nil
}
func TestAccAWSAutoScalingGroup_basic(t *testing.T) {
var group autoscaling.Group
var lc autoscaling.LaunchConfiguration
randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_autoscaling_group.bar",
IDRefreshIgnore: []string{"force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
testAccCheckAWSAutoScalingGroupAttributes(&group, randName),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "name", randName),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "max_size", "5"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "min_size", "2"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "health_check_grace_period", "300"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "health_check_type", "ELB"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "desired_capacity", "4"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "force_delete", "true"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.1", "ClosestToNextInstanceHour"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "protect_from_scale_in", "false"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "enabled_metrics.#", "0"),
),
},
{
Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.new", &lc),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "desired_capacity", "5"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.0", "ClosestToNextInstanceHour"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "protect_from_scale_in", "true"),
testLaunchConfigurationName("aws_autoscaling_group.bar", &lc),
testAccCheckAutoscalingTags(&group.Tags, "FromTags1Changed", map[string]interface{}{
"value": "value1changed",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
"value": "value2changed",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
"value": "value3",
"propagate_at_launch": true,
}),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_namePrefix(t *testing.T) {
nameRegexp := regexp.MustCompile("^tf-test-")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_namePrefix,
Check: resource.ComposeTestCheckFunc(
resource.TestMatchResourceAttr(
"aws_autoscaling_group.test", "name", nameRegexp),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.test", "arn"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_autoGeneratedName(t *testing.T) {
asgNameRegexp := regexp.MustCompile("^tf-asg-")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_autoGeneratedName,
Check: resource.ComposeTestCheckFunc(
resource.TestMatchResourceAttr(
"aws_autoscaling_group.bar", "name", asgNameRegexp),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "arn"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_terminationPolicies(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.#", "0"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.#", "1"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.#", "1"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.0", "Default"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "termination_policies.#", "0"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_tags(t *testing.T) {
var group autoscaling.Group
randName := fmt.Sprintf("tf-test-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAutoscalingTags(&group.Tags, "FromTags1", map[string]interface{}{
"value": "value1",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
"value": "value2",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
"value": "value3",
"propagate_at_launch": true,
}),
),
},
{
Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAutoscalingTagNotExists(&group.Tags, "Foo"),
testAccCheckAutoscalingTags(&group.Tags, "FromTags1Changed", map[string]interface{}{
"value": "value1changed",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
"value": "value2changed",
"propagate_at_launch": true,
}),
testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
"value": "value3",
"propagate_at_launch": true,
}),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_VpcUpdates(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfigWithAZ,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "availability_zones.#", "1"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "0"),
),
},
{
Config: testAccAWSAutoScalingGroupConfigWithVPCIdent,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(&group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "availability_zones.#", "1"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfigWithLoadBalancer,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_withPlacementGroup(t *testing.T) {
var group autoscaling.Group
randName := fmt.Sprintf("tf-test-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_withPlacementGroup(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "placement_group", randName),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_enablingMetrics(t *testing.T) {
var group autoscaling.Group
randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckNoResourceAttr(
"aws_autoscaling_group.bar", "enabled_metrics"),
),
},
{
Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_suspendingProcesses(t *testing.T) {
var group autoscaling.Group
randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "suspended_processes.#", "0"),
),
},
{
Config: testAccAWSAutoScalingGroupConfigWithSuspendedProcesses(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "suspended_processes.#", "2"),
),
},
{
Config: testAccAWSAutoScalingGroupConfigWithSuspendedProcessesUpdated(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "suspended_processes.#", "2"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_withMetrics(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "enabled_metrics.#", "7"),
),
},
{
Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_serviceLinkedRoleARN(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_withServiceLinkedRoleARN,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "service_linked_role_arn"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_ALB_TargetGroups(t *testing.T) {
var group autoscaling.Group
var tg elbv2.TargetGroup
var tg2 elbv2.TargetGroup
testCheck := func(targets []*elbv2.TargetGroup) resource.TestCheckFunc {
return func(*terraform.State) error {
var ts []string
var gs []string
for _, t := range targets {
ts = append(ts, *t.TargetGroupArn)
}
for _, s := range group.TargetGroupARNs {
gs = append(gs, *s)
}
sort.Strings(ts)
sort.Strings(gs)
if !reflect.DeepEqual(ts, gs) {
return fmt.Errorf("Error: target group match not found!\nASG Target groups: %#v\nTarget Group: %#v", ts, gs)
}
return nil
}
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre,
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSLBTargetGroupExists("aws_lb_target_group.test", &tg),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "target_group_arns.#", "0"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo,
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSLBTargetGroupExists("aws_lb_target_group.test", &tg),
testAccCheckAWSLBTargetGroupExists("aws_lb_target_group.test_more", &tg2),
testCheck([]*elbv2.TargetGroup{&tg, &tg2}),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "target_group_arns.#", "2"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post,
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSLBTargetGroupExists("aws_lb_target_group.test", &tg),
testCheck([]*elbv2.TargetGroup{&tg}),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "target_group_arns.#", "1"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_initialLifecycleHook(t *testing.T) {
var group autoscaling.Group
randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_autoscaling_group.bar",
IDRefreshIgnore: []string{"force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupWithHookConfig(randName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "initial_lifecycle_hook.#", "1"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.default_result", "CONTINUE"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name", "launching"),
testAccCheckAWSAutoScalingGroupInitialLifecycleHookExists(
"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_ALB_TargetGroups_ELBCapacity(t *testing.T) {
var group autoscaling.Group
var tg elbv2.TargetGroup
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity(rInt),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
testAccCheckAWSLBTargetGroupExists("aws_lb_target_group.test", &tg),
testAccCheckAWSALBTargetGroupHealthy(&tg),
),
},
},
})
}
func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_autoscaling_group" {
continue
}
// Try to find the Group
describeGroups, err := conn.DescribeAutoScalingGroups(
&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
})
if err == nil {
if len(describeGroups.AutoScalingGroups) != 0 &&
*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {
return fmt.Errorf("AutoScaling Group still exists")
}
}
// Verify the error
ec2err, ok := err.(awserr.Error)
if !ok {
return err
}
if ec2err.Code() != "InvalidGroup.NotFound" {
return err
}
}
return nil
}
func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group, name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
if *group.AvailabilityZones[0] != "us-west-2a" {
return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0])
}
if *group.AutoScalingGroupName != name {
return fmt.Errorf("Bad Autoscaling Group name, expected (%s), got (%s)", name, *group.AutoScalingGroupName)
}
if *group.MaxSize != 5 {
return fmt.Errorf("Bad max_size: %d", *group.MaxSize)
}
if *group.MinSize != 2 {
return fmt.Errorf("Bad max_size: %d", *group.MinSize)
}
if *group.HealthCheckType != "ELB" {
return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType)
}
if *group.HealthCheckGracePeriod != 300 {
return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod)
}
if *group.DesiredCapacity != 4 {
return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity)
}
if *group.LaunchConfigurationName == "" {
return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName)
}
t := &autoscaling.TagDescription{
Key: aws.String("FromTags1"),
Value: aws.String("value1"),
PropagateAtLaunch: aws.Bool(true),
ResourceType: aws.String("auto-scaling-group"),
ResourceId: group.AutoScalingGroupName,
}
if !reflect.DeepEqual(group.Tags[0], t) {
return fmt.Errorf(
"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
group.Tags[0],
t)
}
return nil
}
}
func testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc {
return func(s *terraform.State) error {
if len(group.LoadBalancerNames) != 1 {
return fmt.Errorf("Bad load_balancers: %v", group.LoadBalancerNames)
}
return nil
}
}
func testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No AutoScaling Group ID is set")
}
conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
describeGroups, err := conn.DescribeAutoScalingGroups(
&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
})
if err != nil {
return err
}
if len(describeGroups.AutoScalingGroups) != 1 ||
*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {
return fmt.Errorf("AutoScaling Group not found")
}
*group = *describeGroups.AutoScalingGroups[0]
return nil
}
}
func testAccCheckAWSAutoScalingGroupInitialLifecycleHookExists(asg, hookAttr string) resource.TestCheckFunc {
return func(s *terraform.State) error {
asgResource, ok := s.RootModule().Resources[asg]
if !ok {
return fmt.Errorf("Not found: %s", asg)
}
if asgResource.Primary.ID == "" {
return fmt.Errorf("No AutoScaling Group ID is set")
}
hookName := asgResource.Primary.Attributes[hookAttr]
if hookName == "" {
return fmt.Errorf("ASG %s has no hook name %s", asg, hookAttr)
}
return checkLifecycleHookExistsByName(asgResource.Primary.ID, hookName)
}
}
func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] {
return fmt.Errorf("Launch configuration names do not match")
}
return nil
}
}
func testAccCheckAWSAutoScalingGroupHealthyCapacity(
g *autoscaling.Group, exp int) resource.TestCheckFunc {
return func(s *terraform.State) error {
healthy := 0
for _, i := range g.Instances {
if i.HealthStatus == nil {
continue
}
if strings.EqualFold(*i.HealthStatus, "Healthy") {
healthy++
}
}
if healthy < exp {
return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy)
}
return nil
}
}
func testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(group *autoscaling.Group) resource.TestCheckFunc {
return func(s *terraform.State) error {
// Grab Subnet Ids
var subnets []string
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_subnet" {
continue
}
subnets = append(subnets, rs.Primary.Attributes["id"])
}
if group.VPCZoneIdentifier == nil {
return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets)
}
zones := strings.Split(*group.VPCZoneIdentifier, ",")
remaining := len(zones)
for _, z := range zones {
for _, s := range subnets {
if z == s {
remaining--
}
}
}
if remaining != 0 {
return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets)
}
return nil
}
}
// testAccCheckAWSALBTargetGroupHealthy checks an *elbv2.TargetGroup to make
// sure that all instances in it are healthy.
func testAccCheckAWSALBTargetGroupHealthy(res *elbv2.TargetGroup) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).elbv2conn
resp, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
TargetGroupArn: res.TargetGroupArn,
})
if err != nil {
return err
}
for _, target := range resp.TargetHealthDescriptions {
if target.TargetHealth == nil || target.TargetHealth.State == nil || *target.TargetHealth.State != "healthy" {
return errors.New("Not all instances in target group are healthy yet, but should be")
}
}
return nil
}
}
func TestAccAWSAutoScalingGroup_classicVpcZoneIdentifier(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_autoscaling_group.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.test", &group),
resource.TestCheckResourceAttr("aws_autoscaling_group.test", "vpc_zone_identifier.#", "0"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_emptyAvailabilityZones(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_autoscaling_group.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_emptyAvailabilityZones,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.test", &group),
resource.TestCheckResourceAttr("aws_autoscaling_group.test", "availability_zones.#", "1"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_launchTemplate(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "launch_template.0.id"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) {
var group autoscaling.Group
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "launch_template.0.name"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "launch_configuration"),
resource.TestCheckNoResourceAttr(
"aws_autoscaling_group.bar", "launch_template"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "launch_configuration", ""),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "launch_template.0.name", "foobar2"),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "launch_template.0.id"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "launch_template.0.version", "$Latest"),
),
},
{
Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
resource.TestCheckResourceAttrSet(
"aws_autoscaling_group.bar", "launch_template.0.name"),
resource.TestCheckResourceAttr(
"aws_autoscaling_group.bar", "launch_template.0.version", "1"),
),
},
},
})
}
func TestAccAWSAutoScalingGroup_LaunchTemplate_IAMInstanceProfile(t *testing.T) {
var group autoscaling.Group
resourceName := "aws_autoscaling_group.test"
rName := acctest.RandomWithPrefix("tf-acc-test")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSAutoScalingGroupConfig_LaunchTemplate_IAMInstanceProfile(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAutoScalingGroupExists(resourceName, &group),
),
},
},
})
}
const testAccAWSAutoScalingGroupConfig_autoGeneratedName = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
const testAccAWSAutoScalingGroupConfig_namePrefix = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "test" {
availability_zones = ["us-west-2a"]
desired_capacity = 0
max_size = 0
min_size = 0
name_prefix = "tf-test-"
launch_configuration = "${aws_launch_configuration.test.name}"
}
`
const testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
max_size = 0
min_size = 0
desired_capacity = 0
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
const testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
max_size = 0
min_size = 0
desired_capacity = 0
termination_policies = ["Default"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
const testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
max_size = 0
min_size = 0
desired_capacity = 0
termination_policies = ["OldestInstance"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
func testAccAWSAutoScalingGroupConfig(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_placement_group" "test" {
name = "asg_pg_%s"
strategy = "cluster"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_type = "ELB"
desired_capacity = 4
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
tags = [
{
key = "FromTags1"
value = "value1"
propagate_at_launch = true
},
{
key = "FromTags2"
value = "value2"
propagate_at_launch = true
},
{
key = "FromTags3"
value = "value3"
propagate_at_launch = true
},
]
}
`, name, name)
}
func testAccAWSAutoScalingGroupConfigUpdate(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_configuration" "new" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 5
force_delete = true
termination_policies = ["ClosestToNextInstanceHour"]
protect_from_scale_in = true
launch_configuration = "${aws_launch_configuration.new.name}"
tags = [
{
key = "FromTags1Changed"
value = "value1changed"
propagate_at_launch = true
},
{
key = "FromTags2"
value = "value2changed"
propagate_at_launch = true
},
{
key = "FromTags3"
value = "value3"
propagate_at_launch = true
},
]
}
`, name)
}
func testAccAWSAutoScalingGroupImport(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_placement_group" "test" {
name = "asg_pg_%s"
strategy = "cluster"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_type = "ELB"
desired_capacity = 4
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
tag {
key = "FromTags1"
value = "value1"
propagate_at_launch = true
}
tag {
key = "FromTags2"
value = "value2"
propagate_at_launch = true
}
tag {
key = "FromTags3"
value = "value3"
propagate_at_launch = true
}
}
`, name, name)
}
const testAccAWSAutoScalingGroupConfigWithLoadBalancer = `
resource "aws_vpc" "foo" {
cidr_block = "10.1.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-with-lb"
}
}
resource "aws_internet_gateway" "gw" {
vpc_id = "${aws_vpc.foo.id}"
}
resource "aws_subnet" "foo" {
cidr_block = "10.1.1.0/24"
vpc_id = "${aws_vpc.foo.id}"
tags {
Name = "tf-acc-autoscaling-group-with-load-balancer"
}
}
resource "aws_security_group" "foo" {
vpc_id="${aws_vpc.foo.id}"
ingress {
protocol = "-1"
from_port = 0
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}
egress {
protocol = "-1"
from_port = 0
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_elb" "bar" {
subnets = ["${aws_subnet.foo.id}"]
security_groups = ["${aws_security_group.foo.id}"]
listener {
instance_port = 80
instance_protocol = "http"
lb_port = 80
lb_protocol = "http"
}
health_check {
healthy_threshold = 2
unhealthy_threshold = 2
target = "HTTP:80/"
interval = 5
timeout = 2
}
depends_on = ["aws_internet_gateway.gw"]
}
// need an AMI that listens on :80 at boot, this is:
data "aws_ami" "test_ami" {
most_recent = true
owners = ["979382823631"]
filter {
name = "name"
values = ["bitnami-nginxstack-*-linux-debian-9-x86_64-hvm-ebs"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
security_groups = ["${aws_security_group.foo.id}"]
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["${aws_subnet.foo.availability_zone}"]
vpc_zone_identifier = ["${aws_subnet.foo.id}"]
max_size = 2
min_size = 2
health_check_grace_period = 300
health_check_type = "ELB"
wait_for_elb_capacity = 2
force_delete = true
launch_configuration = "${aws_launch_configuration.foobar.name}"
load_balancers = ["${aws_elb.bar.name}"]
}
`
const testAccAWSAutoScalingGroupConfigWithAZ = `
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-with-az"
}
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-with-az"
}
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = [
"us-west-2a"
]
desired_capacity = 0
max_size = 0
min_size = 0
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
const testAccAWSAutoScalingGroupConfigWithVPCIdent = `
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-with-vpc-id"
}
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-with-vpc-id"
}
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
vpc_zone_identifier = [
"${aws_subnet.main.id}",
]
desired_capacity = 0
max_size = 0
min_size = 0
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
`
func testAccAWSAutoScalingGroupConfig_withPlacementGroup(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "c3.large"
}
resource "aws_placement_group" "test" {
name = "%s"
strategy = "cluster"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 1
min_size = 1
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 1
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
placement_group = "${aws_placement_group.test.name}"
launch_configuration = "${aws_launch_configuration.foobar.name}"
tag {
key = "Foo"
value = "foo-bar"
propagate_at_launch = true
}
}
`, name, name)
}
const testAccAWSAutoScalingGroupConfig_withServiceLinkedRoleARN = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
data "aws_iam_role" "autoscaling_service_linked_role" {
name = "AWSServiceRoleForAutoScaling"
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_configuration = "${aws_launch_configuration.foobar.name}"
service_linked_role_arn = "${data.aws_iam_role.autoscaling_service_linked_role.arn}"
}
`
const testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
max_size = 1
min_size = 0
health_check_grace_period = 300
health_check_type = "EC2"
desired_capacity = 0
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
enabled_metrics = ["GroupTotalInstances",
"GroupPendingInstances",
"GroupTerminatingInstances",
"GroupDesiredCapacity",
"GroupInServiceInstances",
"GroupMinSize",
"GroupMaxSize"
]
metrics_granularity = "1Minute"
}
`
const testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
max_size = 1
min_size = 0
health_check_grace_period = 300
health_check_type = "EC2"
desired_capacity = 0
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
enabled_metrics = ["GroupTotalInstances",
"GroupPendingInstances",
"GroupTerminatingInstances",
"GroupDesiredCapacity",
"GroupMaxSize"
]
metrics_granularity = "1Minute"
}
`
const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre = `
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-alb-target-group"
}
}
resource "aws_lb_target_group" "test" {
name = "tf-example-alb-tg"
port = 80
protocol = "HTTP"
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-main"
}
}
resource "aws_subnet" "alt" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.2.0/24"
availability_zone = "us-west-2b"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-alt"
}
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
enable_monitoring = false
}
resource "aws_autoscaling_group" "bar" {
vpc_zone_identifier = [
"${aws_subnet.main.id}",
"${aws_subnet.alt.id}",
]
max_size = 2
min_size = 0
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 0
force_delete = true
termination_policies = ["OldestInstance"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
resource "aws_security_group" "tf_test_self" {
name = "tf_test_alb_asg"
description = "tf_test_alb_asg"
vpc_id = "${aws_vpc.default.id}"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags {
Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
}
}
`
const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post = `
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-alb-target-group"
}
}
resource "aws_lb_target_group" "test" {
name = "tf-example-alb-tg"
port = 80
protocol = "HTTP"
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-main"
}
}
resource "aws_subnet" "alt" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.2.0/24"
availability_zone = "us-west-2b"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-alt"
}
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
enable_monitoring = false
}
resource "aws_autoscaling_group" "bar" {
vpc_zone_identifier = [
"${aws_subnet.main.id}",
"${aws_subnet.alt.id}",
]
target_group_arns = ["${aws_lb_target_group.test.arn}"]
max_size = 2
min_size = 0
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 0
force_delete = true
termination_policies = ["OldestInstance"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
resource "aws_security_group" "tf_test_self" {
name = "tf_test_alb_asg"
description = "tf_test_alb_asg"
vpc_id = "${aws_vpc.default.id}"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags {
Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
}
}
`
const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo = `
provider "aws" {
region = "us-west-2"
}
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-alb-target-group"
}
}
resource "aws_lb_target_group" "test" {
name = "tf-example-alb-tg"
port = 80
protocol = "HTTP"
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_lb_target_group" "test_more" {
name = "tf-example-alb-tg-more"
port = 80
protocol = "HTTP"
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-main"
}
}
resource "aws_subnet" "alt" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.2.0/24"
availability_zone = "us-west-2b"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-alt"
}
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
enable_monitoring = false
}
resource "aws_autoscaling_group" "bar" {
vpc_zone_identifier = [
"${aws_subnet.main.id}",
"${aws_subnet.alt.id}",
]
target_group_arns = [
"${aws_lb_target_group.test.arn}",
"${aws_lb_target_group.test_more.arn}",
]
max_size = 2
min_size = 0
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 0
force_delete = true
termination_policies = ["OldestInstance"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}
resource "aws_security_group" "tf_test_self" {
name = "tf_test_alb_asg"
description = "tf_test_alb_asg"
vpc_id = "${aws_vpc.default.id}"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags {
Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
}
}
`
func testAccAWSAutoScalingGroupWithHookConfig(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_type = "ELB"
desired_capacity = 4
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
initial_lifecycle_hook {
name = "launching"
default_result = "CONTINUE"
heartbeat_timeout = 30 # minimum value
lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING"
}
}
`, name)
}
func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity(rInt int) string {
return fmt.Sprintf(`
provider "aws" {
region = "us-west-2"
}
resource "aws_vpc" "default" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = "true"
enable_dns_support = "true"
tags {
Name = "terraform-testacc-autoscaling-group-alb-target-group-elb-capacity"
}
}
resource "aws_lb" "test_lb" {
subnets = ["${aws_subnet.main.id}", "${aws_subnet.alt.id}"]
tags {
Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
}
}
resource "aws_lb_listener" "test_listener" {
load_balancer_arn = "${aws_lb.test_lb.arn}"
port = "80"
default_action {
target_group_arn = "${aws_lb_target_group.test.arn}"
type = "forward"
}
}
resource "aws_lb_target_group" "test" {
name = "tf-alb-test-%d"
port = 80
protocol = "HTTP"
vpc_id = "${aws_vpc.default.id}"
health_check {
path = "/"
healthy_threshold = "2"
timeout = "2"
interval = "5"
matcher = "200"
}
tags {
Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
}
}
resource "aws_subnet" "main" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-main"
}
}
resource "aws_subnet" "alt" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "10.0.2.0/24"
availability_zone = "us-west-2b"
tags {
Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-alt"
}
}
resource "aws_internet_gateway" "internet_gateway" {
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_route_table" "route_table" {
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_route_table_association" "route_table_association_main" {
subnet_id = "${aws_subnet.main.id}"
route_table_id = "${aws_route_table.route_table.id}"
}
resource "aws_route_table_association" "route_table_association_alt" {
subnet_id = "${aws_subnet.alt.id}"
route_table_id = "${aws_route_table.route_table.id}"
}
resource "aws_route" "public_default_route" {
route_table_id = "${aws_route_table.route_table.id}"
destination_cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.internet_gateway.id}"
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
associate_public_ip_address = "true"
user_data = <<EOS
#!/bin/bash
yum -y install httpd
echo "hello world" > /var/www/html/index.html
chkconfig httpd on
service httpd start
EOS
}
resource "aws_autoscaling_group" "bar" {
vpc_zone_identifier = [
"${aws_subnet.main.id}",
"${aws_subnet.alt.id}",
]
target_group_arns = ["${aws_lb_target_group.test.arn}"]
max_size = 2
min_size = 2
health_check_grace_period = 300
health_check_type = "ELB"
desired_capacity = 2
wait_for_elb_capacity = 2
force_delete = true
termination_policies = ["OldestInstance"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
}`, rInt)
}
func testAccAWSAutoScalingGroupConfigWithSuspendedProcesses(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_placement_group" "test" {
name = "asg_pg_%s"
strategy = "cluster"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_type = "ELB"
desired_capacity = 4
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
suspended_processes = ["AlarmNotification","ScheduledActions"]
tag {
key = "Foo"
value = "foo-bar"
propagate_at_launch = true
}
}
`, name, name)
}
func testAccAWSAutoScalingGroupConfigWithSuspendedProcessesUpdated(name string) string {
return fmt.Sprintf(`
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "foobar" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_placement_group" "test" {
name = "asg_pg_%s"
strategy = "cluster"
}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["us-west-2a"]
name = "%s"
max_size = 5
min_size = 2
health_check_type = "ELB"
desired_capacity = 4
force_delete = true
termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
launch_configuration = "${aws_launch_configuration.foobar.name}"
suspended_processes = ["AZRebalance","ScheduledActions"]
tag {
key = "Foo"
value = "foo-bar"
propagate_at_launch = true
}
}
`, name, name)
}
const testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier = `
resource "aws_autoscaling_group" "test" {
min_size = 0
max_size = 0
availability_zones = ["us-west-2a"]
launch_configuration = "${aws_launch_configuration.test.name}"
vpc_zone_identifier = []
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t1.micro"
}
`
const testAccAWSAutoScalingGroupConfig_emptyAvailabilityZones = `
resource "aws_vpc" "test" {
cidr_block = "10.0.0.0/16"
tags {
Name = "terraform-testacc-autoscaling-group-empty-azs"
}
}
resource "aws_subnet" "test" {
vpc_id = "${aws_vpc.test.id}"
cidr_block = "10.0.0.0/16"
tags {
Name = "tf-acc-autoscaling-group-empty-availability-zones"
}
}
resource "aws_autoscaling_group" "test" {
min_size = 0
max_size = 0
availability_zones = []
launch_configuration = "${aws_launch_configuration.test.name}"
vpc_zone_identifier = ["${aws_subnet.test.id}"]
}
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
`
const testAccAWSAutoScalingGroupConfig_withLaunchTemplate = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_template" "foobar" {
name_prefix = "foobar"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
data "aws_availability_zones" "available" {}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["${data.aws_availability_zones.available.names[0]}"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_template = {
id = "${aws_launch_template.foobar.id}"
version = "${aws_launch_template.foobar.default_version}"
}
}
`
const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_template" "foobar" {
name_prefix = "foobar"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
data "aws_availability_zones" "available" {}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["${data.aws_availability_zones.available.names[0]}"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_configuration = "${aws_launch_configuration.test.name}"
}
`
const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_template" "foobar" {
name_prefix = "foobar"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_template" "foobar2" {
name = "foobar2"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
data "aws_availability_zones" "available" {}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["${data.aws_availability_zones.available.names[0]}"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_template = {
name = "foobar2"
}
}
`
const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion = `
data "aws_ami" "test_ami" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_launch_template" "foobar" {
name_prefix = "foobar"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_configuration" "test" {
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
resource "aws_launch_template" "foobar2" {
name = "foobar2"
image_id = "${data.aws_ami.test_ami.id}"
instance_type = "t2.micro"
}
data "aws_availability_zones" "available" {}
resource "aws_autoscaling_group" "bar" {
availability_zones = ["${data.aws_availability_zones.available.names[0]}"]
desired_capacity = 0
max_size = 0
min_size = 0
launch_template = {
id = "${aws_launch_template.foobar.id}"
version = "$$Latest"
}
}
`
func testAccAWSAutoScalingGroupConfig_LaunchTemplate_IAMInstanceProfile(rName string) string {
return fmt.Sprintf(`
data "aws_ami" "test" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn-ami-hvm-*-x86_64-gp2"]
}
}
data "aws_availability_zones" "available" {}
resource "aws_iam_role" "test" {
assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}"
name = %q
}
resource "aws_iam_instance_profile" "test" {
name = %q
roles = ["${aws_iam_role.test.name}"]
}
resource "aws_launch_template" "test" {
image_id = "${data.aws_ami.test.id}"
instance_type = "t2.micro"
name = %q
iam_instance_profile {
name = "${aws_iam_instance_profile.test.id}"
}
}
resource "aws_autoscaling_group" "test" {
availability_zones = ["${data.aws_availability_zones.available.names[0]}"]
desired_capacity = 0
max_size = 0
min_size = 0
name = %q
launch_template {
id = "${aws_launch_template.test.id}"
}
}
`, rName, rName, rName, rName)
}
|
nbaztec/terraform-provider-aws
|
aws/resource_aws_autoscaling_group_test.go
|
GO
|
mpl-2.0
| 65,747
|
/**
* Input Field for JSON-schema type:object.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code includes react-jsonschema-form
* released under the Apache License 2.0.
* https://github.com/mozilla-services/react-jsonschema-form
* Date on whitch referred: Thu, Mar 08, 2018 1:08:52 PM
*/
'use strict';
const SchemaUtils = require('./schema-utils');
const SchemaField = require('./schema-field');
const Utils = require('../utils');
class ObjectField {
constructor(schema,
formData,
idSchema,
name,
definitions,
onChange,
required = false,
disabled = false,
readOnly = false) {
this.retrievedSchema = SchemaUtils.retrieveSchema(schema,
definitions,
formData);
this.schema = schema;
this.formData = formData;
this.idSchema = idSchema;
this.name = name;
this.definitions = definitions;
this.onChange = onChange;
this.required = required;
this.disabled = disabled;
this.readOnly = readOnly;
}
isRequired(name) {
return (
Array.isArray(this.retrievedSchema.required) &&
this.retrievedSchema.required.includes(name)
);
}
sortObject(obj) {
const keys = Object.keys(obj).sort();
const map = {};
keys.forEach((key) => {
let val = obj[key];
if (typeof val === 'object') {
val = this.sortObject(val);
}
map[key] = val;
});
return map;
}
isSameSchema(schema1, schema2) {
const json1 = JSON.stringify(this.sortObject(schema1));
const json2 = JSON.stringify(this.sortObject(schema2));
return json1 === json2;
}
onPropertyChange(name, field) {
return (value) => {
const schema = this.schema;
const newFormData = {};
newFormData[name] = value;
this.formData = Object.assign(this.formData, newFormData);
// modify part of form based on form data.
if (schema.hasOwnProperty('dependencies')) {
const newRetrievedSchema = SchemaUtils.retrieveSchema(schema,
this.definitions,
this.formData);
if (!this.isSameSchema(this.retrievedSchema, newRetrievedSchema)) {
this.retrievedSchema = newRetrievedSchema;
this.formData = SchemaUtils.getDefaultFormState(newRetrievedSchema,
this.formData,
this.definitions);
this.renderField(field);
}
}
if (this.onChange) {
this.onChange(this.formData);
}
};
}
renderField(field) {
const id = Utils.escapeHtmlForIdClass(this.idSchema.$id);
const description = this.retrievedSchema.description;
let title = this.retrievedSchema.title ?
this.retrievedSchema.title :
this.name;
if (typeof title !== 'undefined' && title !== null) {
title = Utils.escapeHtml(title);
title = this.required ? title + SchemaUtils.REQUIRED_FIELD_SYMBOL : title;
}
field.innerHTML =
(title ? `<legend id="${`${id}__title`}">${title}</legend>` : '') +
(description ?
`<p id="${id}__description" class="field-description">
${Utils.escapeHtml(description)}</p>` :
'');
// TODO support to specific properties order
const orderedProperties = Object.keys(this.retrievedSchema.properties);
orderedProperties.forEach((name) => {
const childSchema = this.retrievedSchema.properties[name];
const childIdPrefix = `${this.idSchema.$id}_${name}`;
const childData = this.formData[name];
const childIdSchema = SchemaUtils.toIdSchema(
childSchema,
childIdPrefix,
this.definitions,
childData
);
const child = new SchemaField(
childSchema,
childData,
childIdSchema,
name,
this.definitions,
this.onPropertyChange(name, field),
this.isRequired(name),
childSchema.disabled,
childSchema.readOnly).render();
field.appendChild(child);
});
}
render() {
const field = document.createElement('fieldset');
this.renderField(field);
return field;
}
}
module.exports = ObjectField;
|
mozilla-iot/gateway
|
static/js/schema-form/object-field.js
|
JavaScript
|
mpl-2.0
| 4,632
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.Types
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
module Network.AWS.EC2.Types
(
-- * Service
EC2
-- ** Error
, EC2Error
-- ** XML
, ns
-- * ImageAttributeName
, ImageAttributeName (..)
-- * PermissionGroup
, PermissionGroup (..)
-- * NetworkAclEntry
, NetworkAclEntry
, networkAclEntry
, naeCidrBlock
, naeEgress
, naeIcmpTypeCode
, naePortRange
, naeProtocol
, naeRuleAction
, naeRuleNumber
-- * BlobAttributeValue
, BlobAttributeValue
, blobAttributeValue
, bavValue
-- * ImportInstanceLaunchSpecification
, ImportInstanceLaunchSpecification
, importInstanceLaunchSpecification
, iilsAdditionalInfo
, iilsArchitecture
, iilsGroupIds
, iilsGroupNames
, iilsInstanceInitiatedShutdownBehavior
, iilsInstanceType
, iilsMonitoring
, iilsPlacement
, iilsPrivateIpAddress
, iilsSubnetId
, iilsUserData
-- * Snapshot
, Snapshot
, snapshot
, sDescription
, sEncrypted
, sKmsKeyId
, sOwnerAlias
, sOwnerId
, sProgress
, sSnapshotId
, sStartTime
, sState
, sTags
, sVolumeId
, sVolumeSize
-- * SpotInstanceStateFault
, SpotInstanceStateFault
, spotInstanceStateFault
, sisfCode
, sisfMessage
-- * TagDescription
, TagDescription
, tagDescription
, tdKey
, tdResourceId
, tdResourceType
, tdValue
-- * GroupIdentifier
, GroupIdentifier
, groupIdentifier
, giGroupId
, giGroupName
-- * VpnStaticRouteSource
, VpnStaticRouteSource (..)
-- * ReservedInstancesListing
, ReservedInstancesListing
, reservedInstancesListing
, rilClientToken
, rilCreateDate
, rilInstanceCounts
, rilPriceSchedules
, rilReservedInstancesId
, rilReservedInstancesListingId
, rilStatus
, rilStatusMessage
, rilTags
, rilUpdateDate
-- * InstanceLifecycleType
, InstanceLifecycleType (..)
-- * VirtualizationType
, VirtualizationType (..)
-- * NetworkInterfaceStatus
, NetworkInterfaceStatus (..)
-- * PlatformValues
, PlatformValues (..)
-- * CreateVolumePermission
, CreateVolumePermission
, createVolumePermission
, cvpGroup
, cvpUserId
-- * NetworkInterfaceAttachmentChanges
, NetworkInterfaceAttachmentChanges
, networkInterfaceAttachmentChanges
, niacAttachmentId
, niacDeleteOnTermination
-- * RecurringChargeFrequency
, RecurringChargeFrequency (..)
-- * DhcpOptions
, DhcpOptions
, dhcpOptions
, doDhcpConfigurations
, doDhcpOptionsId
, doTags
-- * InstanceNetworkInterfaceSpecification
, InstanceNetworkInterfaceSpecification
, instanceNetworkInterfaceSpecification
, inisAssociatePublicIpAddress
, inisDeleteOnTermination
, inisDescription
, inisDeviceIndex
, inisGroups
, inisNetworkInterfaceId
, inisPrivateIpAddress
, inisPrivateIpAddresses
, inisSecondaryPrivateIpAddressCount
, inisSubnetId
-- * VolumeState
, VolumeState (..)
-- * AttributeValue
, AttributeValue
, attributeValue
, avValue
-- * PrivateIpAddressSpecification
, PrivateIpAddressSpecification
, privateIpAddressSpecification
, piasPrimary
, piasPrivateIpAddress
-- * Image
, Image
, image
, iArchitecture
, iBlockDeviceMappings
, iCreationDate
, iDescription
, iHypervisor
, iImageId
, iImageLocation
, iImageOwnerAlias
, iImageType
, iKernelId
, iName
, iOwnerId
, iPlatform
, iProductCodes
, iPublic
, iRamdiskId
, iRootDeviceName
, iRootDeviceType
, iSriovNetSupport
, iState
, iStateReason
, iTags
, iVirtualizationType
-- * DhcpConfiguration
, DhcpConfiguration
, dhcpConfiguration
, dcKey
, dcValues
-- * Tag
, Tag
, tag
, tagKey
, tagValue
-- * AccountAttributeName
, AccountAttributeName (..)
-- * NetworkInterfaceAttachment
, NetworkInterfaceAttachment
, networkInterfaceAttachment
, niaAttachTime
, niaAttachmentId
, niaDeleteOnTermination
, niaDeviceIndex
, niaInstanceId
, niaInstanceOwnerId
, niaStatus
-- * RunInstancesMonitoringEnabled
, RunInstancesMonitoringEnabled
, runInstancesMonitoringEnabled
, rimeEnabled
-- * VolumeStatusInfo
, VolumeStatusInfo
, volumeStatusInfo
, vsiDetails
, vsiStatus
-- * NetworkInterfaceAssociation
, NetworkInterfaceAssociation
, networkInterfaceAssociation
, niaAllocationId
, niaAssociationId
, niaIpOwnerId
, niaPublicDnsName
, niaPublicIp
-- * CreateVolumePermissionModifications
, CreateVolumePermissionModifications
, createVolumePermissionModifications
, cvpmAdd
, cvpmRemove
-- * VpcState
, VpcState (..)
-- * ResourceType
, ResourceType (..)
-- * ReportStatusType
, ReportStatusType (..)
-- * CurrencyCodeValues
, CurrencyCodeValues (..)
-- * IcmpTypeCode
, IcmpTypeCode
, icmpTypeCode
, itcCode
, itcType
-- * InstanceCount
, InstanceCount
, instanceCount
, icInstanceCount
, icState
-- * ExportToS3Task
, ExportToS3Task
, exportToS3Task
, etstContainerFormat
, etstDiskImageFormat
, etstS3Bucket
, etstS3Key
-- * BlockDeviceMapping
, BlockDeviceMapping
, blockDeviceMapping
, bdmDeviceName
, bdmEbs
, bdmNoDevice
, bdmVirtualName
-- * ConversionTask
, ConversionTask
, conversionTask
, ctConversionTaskId
, ctExpirationTime
, ctImportInstance
, ctImportVolume
, ctState
, ctStatusMessage
, ctTags
-- * AttachmentStatus
, AttachmentStatus (..)
-- * ClassicLinkInstance
, ClassicLinkInstance
, classicLinkInstance
, cliGroups
, cliInstanceId
, cliTags
, cliVpcId
-- * RouteOrigin
, RouteOrigin (..)
-- * ListingState
, ListingState (..)
-- * SpotPrice
, SpotPrice
, spotPrice
, spAvailabilityZone
, spInstanceType
, spProductDescription
, spSpotPrice
, spTimestamp
-- * InstanceMonitoring
, InstanceMonitoring
, instanceMonitoring
, imInstanceId
, imMonitoring
-- * PriceScheduleSpecification
, PriceScheduleSpecification
, priceScheduleSpecification
, pssCurrencyCode
, pssPrice
, pssTerm
-- * SpotInstanceStatus
, SpotInstanceStatus
, spotInstanceStatus
, sisCode
, sisMessage
, sisUpdateTime
-- * AvailabilityZoneState
, AvailabilityZoneState (..)
-- * SpotInstanceRequest
, SpotInstanceRequest
, spotInstanceRequest
, siAvailabilityZoneGroup
, siCreateTime
, siFault
, siInstanceId
, siLaunchGroup
, siLaunchSpecification
, siLaunchedAvailabilityZone
, siProductDescription
, siSpotInstanceRequestId
, siSpotPrice
, siState
, siStatus
, siTags
, siType
, siValidFrom
, siValidUntil
-- * LaunchSpecification
, LaunchSpecification
, launchSpecification
, lsAddressingType
, lsBlockDeviceMappings
, lsEbsOptimized
, lsIamInstanceProfile
, lsImageId
, lsInstanceType
, lsKernelId
, lsKeyName
, lsMonitoring
, lsNetworkInterfaces
, lsPlacement
, lsRamdiskId
, lsSecurityGroups
, lsSubnetId
, lsUserData
-- * VolumeStatusEvent
, VolumeStatusEvent
, volumeStatusEvent
, vseDescription
, vseEventId
, vseEventType
, vseNotAfter
, vseNotBefore
-- * Volume
, Volume
, volume
, vAttachments
, vAvailabilityZone
, vCreateTime
, vEncrypted
, vIops
, vKmsKeyId
, vSize
, vSnapshotId
, vState
, vTags
, vVolumeId
, vVolumeType
-- * Reservation
, Reservation
, reservation
, rGroups
, rInstances
, rOwnerId
, rRequesterId
, rReservationId
-- * ImportInstanceVolumeDetailItem
, ImportInstanceVolumeDetailItem
, importInstanceVolumeDetailItem
, iivdiAvailabilityZone
, iivdiBytesConverted
, iivdiDescription
, iivdiImage
, iivdiStatus
, iivdiStatusMessage
, iivdiVolume
-- * SummaryStatus
, SummaryStatus (..)
-- * ReservedInstancesModification
, ReservedInstancesModification
, reservedInstancesModification
, rimClientToken
, rimCreateDate
, rimEffectiveDate
, rimModificationResults
, rimReservedInstancesIds
, rimReservedInstancesModificationId
, rimStatus
, rimStatusMessage
, rimUpdateDate
-- * RuleAction
, RuleAction (..)
-- * NetworkInterface
, NetworkInterface
, networkInterface
, niAssociation
, niAttachment
, niAvailabilityZone
, niDescription
, niGroups
, niMacAddress
, niNetworkInterfaceId
, niOwnerId
, niPrivateDnsName
, niPrivateIpAddress
, niPrivateIpAddresses
, niRequesterId
, niRequesterManaged
, niSourceDestCheck
, niStatus
, niSubnetId
, niTagSet
, niVpcId
-- * TelemetryStatus
, TelemetryStatus (..)
-- * Subnet
, Subnet
, subnet
, s1AvailabilityZone
, s1AvailableIpAddressCount
, s1CidrBlock
, s1DefaultForAz
, s1MapPublicIpOnLaunch
, s1State
, s1SubnetId
, s1Tags
, s1VpcId
-- * KeyPairInfo
, KeyPairInfo
, keyPairInfo
, kpiKeyFingerprint
, kpiKeyName
-- * LaunchPermissionModifications
, LaunchPermissionModifications
, launchPermissionModifications
, lpmAdd
, lpmRemove
-- * SnapshotState
, SnapshotState (..)
-- * InstanceNetworkInterfaceAssociation
, InstanceNetworkInterfaceAssociation
, instanceNetworkInterfaceAssociation
, iniaIpOwnerId
, iniaPublicDnsName
, iniaPublicIp
-- * DiskImageDetail
, DiskImageDetail
, diskImageDetail
, didBytes
, didFormat
, didImportManifestUrl
-- * InstancePrivateIpAddress
, InstancePrivateIpAddress
, instancePrivateIpAddress
, ipiaAssociation
, ipiaPrimary
, ipiaPrivateDnsName
, ipiaPrivateIpAddress
-- * CancelledSpotInstanceRequest
, CancelledSpotInstanceRequest
, cancelledSpotInstanceRequest
, csiSpotInstanceRequestId
, csiState
-- * VpnConnectionOptionsSpecification
, VpnConnectionOptionsSpecification
, vpnConnectionOptionsSpecification
, vcosStaticRoutesOnly
-- * Address
, Address
, address
, aAllocationId
, aAssociationId
, aDomain
, aInstanceId
, aNetworkInterfaceId
, aNetworkInterfaceOwnerId
, aPrivateIpAddress
, aPublicIp
-- * VolumeAttachmentState
, VolumeAttachmentState (..)
-- * LaunchPermission
, LaunchPermission
, launchPermission
, lpGroup
, lpUserId
-- * RouteState
, RouteState (..)
-- * RouteTableAssociation
, RouteTableAssociation
, routeTableAssociation
, rtaMain
, rtaRouteTableAssociationId
, rtaRouteTableId
, rtaSubnetId
-- * BundleTaskState
, BundleTaskState (..)
-- * PortRange
, PortRange
, portRange
, prFrom
, prTo
-- * VpcAttributeName
, VpcAttributeName (..)
-- * ReservedInstancesConfiguration
, ReservedInstancesConfiguration
, reservedInstancesConfiguration
, ricAvailabilityZone
, ricInstanceCount
, ricInstanceType
, ricPlatform
-- * VolumeStatusDetails
, VolumeStatusDetails
, volumeStatusDetails
, vsdName
, vsdStatus
-- * SpotInstanceState
, SpotInstanceState (..)
-- * VpnConnectionOptions
, VpnConnectionOptions
, vpnConnectionOptions
, vcoStaticRoutesOnly
-- * UserIdGroupPair
, UserIdGroupPair
, userIdGroupPair
, uigpGroupId
, uigpGroupName
, uigpUserId
-- * InstanceStatusSummary
, InstanceStatusSummary
, instanceStatusSummary
, issDetails
, issStatus
-- * SpotPlacement
, SpotPlacement
, spotPlacement
, sp1AvailabilityZone
, sp1GroupName
-- * EbsInstanceBlockDeviceSpecification
, EbsInstanceBlockDeviceSpecification
, ebsInstanceBlockDeviceSpecification
, eibdsDeleteOnTermination
, eibdsVolumeId
-- * NetworkAclAssociation
, NetworkAclAssociation
, networkAclAssociation
, naaNetworkAclAssociationId
, naaNetworkAclId
, naaSubnetId
-- * BundleTask
, BundleTask
, bundleTask
, btBundleId
, btBundleTaskError
, btInstanceId
, btProgress
, btStartTime
, btState
, btStorage
, btUpdateTime
-- * InstanceStatusEvent
, InstanceStatusEvent
, instanceStatusEvent
, iseCode
, iseDescription
, iseNotAfter
, iseNotBefore
-- * InstanceType
, InstanceType (..)
-- * Route
, Route
, route
, rDestinationCidrBlock
, rGatewayId
, rInstanceId
, rInstanceOwnerId
, rNetworkInterfaceId
, rOrigin
, rState
, rVpcPeeringConnectionId
-- * SpotDatafeedSubscription
, SpotDatafeedSubscription
, spotDatafeedSubscription
, sdsBucket
, sdsFault
, sdsOwnerId
, sdsPrefix
, sdsState
-- * Storage
, Storage
, storage
, sS3
-- * SecurityGroup
, SecurityGroup
, securityGroup
, sgDescription
, sgGroupId
, sgGroupName
, sgIpPermissions
, sgIpPermissionsEgress
, sgOwnerId
, sgTags
, sgVpcId
-- * CancelSpotInstanceRequestState
, CancelSpotInstanceRequestState (..)
-- * PlacementGroupState
, PlacementGroupState (..)
-- * ReservedInstancesModificationResult
, ReservedInstancesModificationResult
, reservedInstancesModificationResult
, rimrReservedInstancesId
, rimrTargetConfiguration
-- * InstanceBlockDeviceMappingSpecification
, InstanceBlockDeviceMappingSpecification
, instanceBlockDeviceMappingSpecification
, ibdmsDeviceName
, ibdmsEbs
, ibdmsNoDevice
, ibdmsVirtualName
-- * ExportEnvironment
, ExportEnvironment (..)
-- * UserData
, UserData
, userData
, udData
-- * VolumeAttachment
, VolumeAttachment
, volumeAttachment
, vaAttachTime
, vaDeleteOnTermination
, vaDevice
, vaInstanceId
, vaState
, vaVolumeId
-- * CustomerGateway
, CustomerGateway
, customerGateway
, cgBgpAsn
, cgCustomerGatewayId
, cgIpAddress
, cgState
, cgTags
, cgType
-- * EbsInstanceBlockDevice
, EbsInstanceBlockDevice
, ebsInstanceBlockDevice
, eibdAttachTime
, eibdDeleteOnTermination
, eibdStatus
, eibdVolumeId
-- * ShutdownBehavior
, ShutdownBehavior (..)
-- * DiskImageDescription
, DiskImageDescription
, diskImageDescription
, did1Checksum
, did1Format
, did1ImportManifestUrl
, did1Size
-- * DiskImageVolumeDescription
, DiskImageVolumeDescription
, diskImageVolumeDescription
, divdId
, divdSize
-- * Monitoring
, Monitoring
, monitoring
, mState
-- * SubnetState
, SubnetState (..)
-- * ContainerFormat
, ContainerFormat (..)
-- * AvailabilityZoneMessage
, AvailabilityZoneMessage
, availabilityZoneMessage
, azmMessage
-- * VpcAttachment
, VpcAttachment
, vpcAttachment
, va1State
, va1VpcId
-- * InstanceBlockDeviceMapping
, InstanceBlockDeviceMapping
, instanceBlockDeviceMapping
, ibdmDeviceName
, ibdmEbs
-- * StatusType
, StatusType (..)
-- * ExportToS3TaskSpecification
, ExportToS3TaskSpecification
, exportToS3TaskSpecification
, etstsContainerFormat
, etstsDiskImageFormat
, etstsS3Bucket
, etstsS3Prefix
-- * NetworkInterfaceAttribute
, NetworkInterfaceAttribute (..)
-- * ImageTypeValues
, ImageTypeValues (..)
-- * InstanceExportDetails
, InstanceExportDetails
, instanceExportDetails
, iedInstanceId
, iedTargetEnvironment
-- * SnapshotAttributeName
, SnapshotAttributeName (..)
-- * AvailabilityZone
, AvailabilityZone
, availabilityZone
, azMessages
, azRegionName
, azState
, azZoneName
-- * VpnState
, VpnState (..)
-- * RouteTable
, RouteTable
, routeTable
, rtAssociations
, rtPropagatingVgws
, rtRouteTableId
, rtRoutes
, rtTags
, rtVpcId
-- * HypervisorType
, HypervisorType (..)
-- * InstanceStatusDetails
, InstanceStatusDetails
, instanceStatusDetails
, isdImpairedSince
, isdName
, isdStatus
-- * IamInstanceProfile
, IamInstanceProfile
, iamInstanceProfile
, iipArn
, iipId
-- * InternetGatewayAttachment
, InternetGatewayAttachment
, internetGatewayAttachment
, igaState
, igaVpcId
-- * ReservedInstanceState
, ReservedInstanceState (..)
-- * InstanceAttributeName
, InstanceAttributeName (..)
-- * IpPermission
, IpPermission
, ipPermission
, ipFromPort
, ipIpProtocol
, ipIpRanges
, ipToPort
, ipUserIdGroupPairs
-- * ConversionTaskState
, ConversionTaskState (..)
-- * DiskImage
, DiskImage
, diskImage
, diDescription
, diImage
, diVolume
-- * Tenancy
, Tenancy (..)
-- * VpcPeeringConnectionStateReason
, VpcPeeringConnectionStateReason
, vpcPeeringConnectionStateReason
, vpcsrCode
, vpcsrMessage
-- * IamInstanceProfileSpecification
, IamInstanceProfileSpecification
, iamInstanceProfileSpecification
, iipsArn
, iipsName
-- * ImportVolumeTaskDetails
, ImportVolumeTaskDetails
, importVolumeTaskDetails
, ivtdAvailabilityZone
, ivtdBytesConverted
, ivtdDescription
, ivtdImage
, ivtdVolume
-- * PlacementStrategy
, PlacementStrategy (..)
-- * InstanceNetworkInterface
, InstanceNetworkInterface
, instanceNetworkInterface
, iniAssociation
, iniAttachment
, iniDescription
, iniGroups
, iniMacAddress
, iniNetworkInterfaceId
, iniOwnerId
, iniPrivateDnsName
, iniPrivateIpAddress
, iniPrivateIpAddresses
, iniSourceDestCheck
, iniStatus
, iniSubnetId
, iniVpcId
-- * VolumeStatusAction
, VolumeStatusAction
, volumeStatusAction
, vsaCode
, vsaDescription
, vsaEventId
, vsaEventType
-- * VpcPeeringConnectionVpcInfo
, VpcPeeringConnectionVpcInfo
, vpcPeeringConnectionVpcInfo
, vpcviCidrBlock
, vpcviOwnerId
, vpcviVpcId
-- * ReservedInstanceLimitPrice
, ReservedInstanceLimitPrice
, reservedInstanceLimitPrice
, rilpAmount
, rilpCurrencyCode
-- * Vpc
, Vpc
, vpc
, vpcCidrBlock
, vpcDhcpOptionsId
, vpcInstanceTenancy
, vpcIsDefault
, vpcState
, vpcTags
, vpcVpcId
-- * InstanceStatus
, InstanceStatus
, instanceStatus
, isAvailabilityZone
, isEvents
, isInstanceId
, isInstanceState
, isInstanceStatus
, isSystemStatus
-- * ArchitectureValues
, ArchitectureValues (..)
-- * ReportInstanceReasonCodes
, ReportInstanceReasonCodes (..)
-- * EbsBlockDevice
, EbsBlockDevice
, ebsBlockDevice
, ebdDeleteOnTermination
, ebdEncrypted
, ebdIops
, ebdSnapshotId
, ebdVolumeSize
, ebdVolumeType
-- * AccountAttribute
, AccountAttribute
, accountAttribute
, aaAttributeName
, aaAttributeValues
-- * PriceSchedule
, PriceSchedule
, priceSchedule
, psActive
, psCurrencyCode
, psPrice
, psTerm
-- * DeviceType
, DeviceType (..)
-- * DomainType
, DomainType (..)
-- * Region
, Region
, region
, rEndpoint
, rRegionName
-- * PropagatingVgw
, PropagatingVgw
, propagatingVgw
, pvGatewayId
-- * OfferingTypeValues
, OfferingTypeValues (..)
-- * VpnGateway
, VpnGateway
, vpnGateway
, vgAvailabilityZone
, vgState
, vgTags
, vgType
, vgVpcAttachments
, vgVpnGatewayId
-- * Filter
, Filter
, filter'
, fName
, fValues
-- * VolumeType
, VolumeType (..)
-- * InstanceStateChange
, InstanceStateChange
, instanceStateChange
, iscCurrentState
, iscInstanceId
, iscPreviousState
-- * NetworkAcl
, NetworkAcl
, networkAcl
, naAssociations
, naEntries
, naIsDefault
, naNetworkAclId
, naTags
, naVpcId
-- * ImageState
, ImageState (..)
-- * GatewayType
, GatewayType (..)
-- * InstanceNetworkInterfaceAttachment
, InstanceNetworkInterfaceAttachment
, instanceNetworkInterfaceAttachment
, iniaAttachTime
, iniaAttachmentId
, iniaDeleteOnTermination
, iniaDeviceIndex
, iniaStatus
-- * AttributeBooleanValue
, AttributeBooleanValue
, attributeBooleanValue
, abvValue
-- * RecurringCharge
, RecurringCharge
, recurringCharge
, rcAmount
, rcFrequency
-- * NewDhcpConfiguration
, NewDhcpConfiguration
, newDhcpConfiguration
, ndcKey
, ndcValues
-- * StateReason
, StateReason
, stateReason
, srCode
, srMessage
-- * MonitoringState
, MonitoringState (..)
-- * ReservedInstancesId
, ReservedInstancesId
, reservedInstancesId
, riiReservedInstancesId
-- * StatusName
, StatusName (..)
-- * InternetGateway
, InternetGateway
, internetGateway
, igAttachments
, igInternetGatewayId
, igTags
-- * VolumeStatusName
, VolumeStatusName (..)
-- * VolumeAttributeName
, VolumeAttributeName (..)
-- * ImportInstanceTaskDetails
, ImportInstanceTaskDetails
, importInstanceTaskDetails
, iitdDescription
, iitdInstanceId
, iitdPlatform
, iitdVolumes
-- * PlacementGroup
, PlacementGroup
, placementGroup
, pgGroupName
, pgState
, pgStrategy
-- * ProductCode
, ProductCode
, productCode
, pcProductCodeId
, pcProductCodeType
-- * ListingStatus
, ListingStatus (..)
-- * IpRange
, IpRange
, ipRange
, irCidrIp
-- * VolumeStatusInfoStatus
, VolumeStatusInfoStatus (..)
-- * AccountAttributeValue
, AccountAttributeValue
, accountAttributeValue
, aavAttributeValue
-- * RIProductDescription
, RIProductDescription (..)
-- * ReservedInstancesOffering
, ReservedInstancesOffering
, reservedInstancesOffering
, rioAvailabilityZone
, rioCurrencyCode
, rioDuration
, rioFixedPrice
, rioInstanceTenancy
, rioInstanceType
, rioMarketplace
, rioOfferingType
, rioPricingDetails
, rioProductDescription
, rioRecurringCharges
, rioReservedInstancesOfferingId
, rioUsagePrice
-- * ReservedInstances
, ReservedInstances
, reservedInstances
, ri1AvailabilityZone
, ri1CurrencyCode
, ri1Duration
, ri1End
, ri1FixedPrice
, ri1InstanceCount
, ri1InstanceTenancy
, ri1InstanceType
, ri1OfferingType
, ri1ProductDescription
, ri1RecurringCharges
, ri1ReservedInstancesId
, ri1Start
, ri1State
, ri1Tags
, ri1UsagePrice
-- * DatafeedSubscriptionState
, DatafeedSubscriptionState (..)
-- * ExportTaskState
, ExportTaskState (..)
-- * ProductCodeValues
, ProductCodeValues (..)
-- * VpnConnection
, VpnConnection
, vpnConnection
, vcCustomerGatewayConfiguration
, vcCustomerGatewayId
, vcOptions
, vcRoutes
, vcState
, vcTags
, vcType
, vcVgwTelemetry
, vcVpnConnectionId
, vcVpnGatewayId
-- * InstanceState
, InstanceState
, instanceState
, isCode
, isName
-- * Placement
, Placement
, placement
, pAvailabilityZone
, pGroupName
, pTenancy
-- * EventCode
, EventCode (..)
-- * SpotInstanceType
, SpotInstanceType (..)
-- * VpcPeeringConnection
, VpcPeeringConnection
, vpcPeeringConnection
, vpc1AccepterVpcInfo
, vpc1ExpirationTime
, vpc1RequesterVpcInfo
, vpc1Status
, vpc1Tags
, vpc1VpcPeeringConnectionId
-- * S3Storage
, S3Storage
, s3Storage
, ssAWSAccessKeyId
, ssBucket
, ssPrefix
, ssUploadPolicy
, ssUploadPolicySignature
-- * VgwTelemetry
, VgwTelemetry
, vgwTelemetry
, vtAcceptedRouteCount
, vtLastStatusChange
, vtOutsideIpAddress
, vtStatus
, vtStatusMessage
-- * VpnStaticRoute
, VpnStaticRoute
, vpnStaticRoute
, vsrDestinationCidrBlock
, vsrSource
, vsrState
-- * InstanceStateName
, InstanceStateName (..)
-- * Instance
, Instance
, instance'
, i1AmiLaunchIndex
, i1Architecture
, i1BlockDeviceMappings
, i1ClientToken
, i1EbsOptimized
, i1Hypervisor
, i1IamInstanceProfile
, i1ImageId
, i1InstanceId
, i1InstanceLifecycle
, i1InstanceType
, i1KernelId
, i1KeyName
, i1LaunchTime
, i1Monitoring
, i1NetworkInterfaces
, i1Placement
, i1Platform
, i1PrivateDnsName
, i1PrivateIpAddress
, i1ProductCodes
, i1PublicDnsName
, i1PublicIpAddress
, i1RamdiskId
, i1RootDeviceName
, i1RootDeviceType
, i1SecurityGroups
, i1SourceDestCheck
, i1SpotInstanceRequestId
, i1SriovNetSupport
, i1State
, i1StateReason
, i1StateTransitionReason
, i1SubnetId
, i1Tags
, i1VirtualizationType
, i1VpcId
-- * ExportTask
, ExportTask
, exportTask
, etDescription
, etExportTaskId
, etExportToS3Task
, etInstanceExportDetails
, etState
, etStatusMessage
-- * ResetImageAttributeName
, ResetImageAttributeName (..)
-- * RequestSpotLaunchSpecification
, RequestSpotLaunchSpecification
, requestSpotLaunchSpecification
, rslsAddressingType
, rslsBlockDeviceMappings
, rslsEbsOptimized
, rslsIamInstanceProfile
, rslsImageId
, rslsInstanceType
, rslsKernelId
, rslsKeyName
, rslsMonitoring
, rslsNetworkInterfaces
, rslsPlacement
, rslsRamdiskId
, rslsSecurityGroupIds
, rslsSecurityGroups
, rslsSubnetId
, rslsUserData
-- * VolumeDetail
, VolumeDetail
, volumeDetail
, vdSize
-- * PricingDetail
, PricingDetail
, pricingDetail
, pdCount
, pdPrice
-- * NetworkInterfacePrivateIpAddress
, NetworkInterfacePrivateIpAddress
, networkInterfacePrivateIpAddress
, nipiaAssociation
, nipiaPrimary
, nipiaPrivateDnsName
, nipiaPrivateIpAddress
-- * DiskImageFormat
, DiskImageFormat (..)
-- * BundleTaskError
, BundleTaskError
, bundleTaskError
, bteCode
, bteMessage
-- * VpcClassicLink
, VpcClassicLink
, vpcClassicLink
, vclClassicLinkEnabled
, vclTags
, vclVpcId
-- * VolumeStatusItem
, VolumeStatusItem
, volumeStatusItem
, vsiActions
, vsiAvailabilityZone
, vsiEvents
, vsiVolumeId
, vsiVolumeStatus
-- * Common
, module Network.AWS.EC2.Internal
) where
import Network.AWS.Prelude
import Network.AWS.Signing
import Network.AWS.EC2.Internal
import qualified GHC.Exts
-- | Version @2014-10-01@ of the Amazon Elastic Compute Cloud service.
data EC2
instance AWSService EC2 where
type Sg EC2 = V4
type Er EC2 = EC2Error
service = service'
where
service' :: Service EC2
service' = Service
{ _svcAbbrev = "EC2"
, _svcPrefix = "ec2"
, _svcVersion = "2014-10-01"
, _svcTargetPrefix = Nothing
, _svcJSONVersion = Nothing
, _svcHandle = handle
, _svcRetry = retry
}
handle :: Status
-> Maybe (LazyByteString -> ServiceError EC2Error)
handle = restError statusSuccess service'
retry :: Retry EC2
retry = Exponential
{ _retryBase = 0.05
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check :: Status
-> EC2Error
-> Bool
check (statusCode -> s) (awsErrorCode -> e)
| s == 503 && "RequestLimitExceeded" == e = True -- Request Limit Exceeded
| s == 500 = True -- General Server Error
| s == 509 = True -- Limit Exceeded
| s == 503 = True -- Service Unavailable
| otherwise = False
ns :: Text
ns = "http://ec2.amazonaws.com/doc/2014-10-01"
{-# INLINE ns #-}
data ImageAttributeName
= ImageBlockDeviceMapping -- ^ blockDeviceMapping
| ImageDescription -- ^ description
| ImageKernel -- ^ kernel
| ImageLaunchPermission -- ^ launchPermission
| ImageProductCodes -- ^ productCodes
| ImageRamdisk -- ^ ramdisk
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ImageAttributeName
instance FromText ImageAttributeName where
parser = takeLowerText >>= \case
"blockdevicemapping" -> pure ImageBlockDeviceMapping
"description" -> pure ImageDescription
"kernel" -> pure ImageKernel
"launchpermission" -> pure ImageLaunchPermission
"productcodes" -> pure ImageProductCodes
"ramdisk" -> pure ImageRamdisk
e -> fail $
"Failure parsing ImageAttributeName from " ++ show e
instance ToText ImageAttributeName where
toText = \case
ImageBlockDeviceMapping -> "blockDeviceMapping"
ImageDescription -> "description"
ImageKernel -> "kernel"
ImageLaunchPermission -> "launchPermission"
ImageProductCodes -> "productCodes"
ImageRamdisk -> "ramdisk"
instance ToByteString ImageAttributeName
instance ToHeader ImageAttributeName
instance ToQuery ImageAttributeName
instance FromXML ImageAttributeName where
parseXML = parseXMLText "ImageAttributeName"
data PermissionGroup
= All -- ^ all
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable PermissionGroup
instance FromText PermissionGroup where
parser = takeLowerText >>= \case
"all" -> pure All
e -> fail $
"Failure parsing PermissionGroup from " ++ show e
instance ToText PermissionGroup where
toText All = "all"
instance ToByteString PermissionGroup
instance ToHeader PermissionGroup
instance ToQuery PermissionGroup
instance FromXML PermissionGroup where
parseXML = parseXMLText "PermissionGroup"
data NetworkAclEntry = NetworkAclEntry
{ _naeCidrBlock :: Maybe Text
, _naeEgress :: Maybe Bool
, _naeIcmpTypeCode :: Maybe IcmpTypeCode
, _naePortRange :: Maybe PortRange
, _naeProtocol :: Maybe Text
, _naeRuleAction :: Maybe RuleAction
, _naeRuleNumber :: Maybe Int
} deriving (Eq, Read, Show)
-- | 'NetworkAclEntry' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'naeCidrBlock' @::@ 'Maybe' 'Text'
--
-- * 'naeEgress' @::@ 'Maybe' 'Bool'
--
-- * 'naeIcmpTypeCode' @::@ 'Maybe' 'IcmpTypeCode'
--
-- * 'naePortRange' @::@ 'Maybe' 'PortRange'
--
-- * 'naeProtocol' @::@ 'Maybe' 'Text'
--
-- * 'naeRuleAction' @::@ 'Maybe' 'RuleAction'
--
-- * 'naeRuleNumber' @::@ 'Maybe' 'Int'
--
networkAclEntry :: NetworkAclEntry
networkAclEntry = NetworkAclEntry
{ _naeRuleNumber = Nothing
, _naeProtocol = Nothing
, _naeRuleAction = Nothing
, _naeEgress = Nothing
, _naeCidrBlock = Nothing
, _naeIcmpTypeCode = Nothing
, _naePortRange = Nothing
}
-- | The network range to allow or deny, in CIDR notation.
naeCidrBlock :: Lens' NetworkAclEntry (Maybe Text)
naeCidrBlock = lens _naeCidrBlock (\s a -> s { _naeCidrBlock = a })
-- | Indicates whether the rule is an egress rule (applied to traffic leaving the
-- subnet).
naeEgress :: Lens' NetworkAclEntry (Maybe Bool)
naeEgress = lens _naeEgress (\s a -> s { _naeEgress = a })
-- | ICMP protocol: The ICMP type and code.
naeIcmpTypeCode :: Lens' NetworkAclEntry (Maybe IcmpTypeCode)
naeIcmpTypeCode = lens _naeIcmpTypeCode (\s a -> s { _naeIcmpTypeCode = a })
-- | TCP or UDP protocols: The range of ports the rule applies to.
naePortRange :: Lens' NetworkAclEntry (Maybe PortRange)
naePortRange = lens _naePortRange (\s a -> s { _naePortRange = a })
-- | The protocol. A value of '-1' means all protocols.
naeProtocol :: Lens' NetworkAclEntry (Maybe Text)
naeProtocol = lens _naeProtocol (\s a -> s { _naeProtocol = a })
-- | Indicates whether to allow or deny the traffic that matches the rule.
naeRuleAction :: Lens' NetworkAclEntry (Maybe RuleAction)
naeRuleAction = lens _naeRuleAction (\s a -> s { _naeRuleAction = a })
-- | The rule number for the entry. ACL entries are processed in ascending order
-- by rule number.
naeRuleNumber :: Lens' NetworkAclEntry (Maybe Int)
naeRuleNumber = lens _naeRuleNumber (\s a -> s { _naeRuleNumber = a })
instance FromXML NetworkAclEntry where
parseXML x = NetworkAclEntry
<$> x .@? "cidrBlock"
<*> x .@? "egress"
<*> x .@? "icmpTypeCode"
<*> x .@? "portRange"
<*> x .@? "protocol"
<*> x .@? "ruleAction"
<*> x .@? "ruleNumber"
instance ToQuery NetworkAclEntry where
toQuery NetworkAclEntry{..} = mconcat
[ "CidrBlock" =? _naeCidrBlock
, "Egress" =? _naeEgress
, "IcmpTypeCode" =? _naeIcmpTypeCode
, "PortRange" =? _naePortRange
, "Protocol" =? _naeProtocol
, "RuleAction" =? _naeRuleAction
, "RuleNumber" =? _naeRuleNumber
]
newtype BlobAttributeValue = BlobAttributeValue
{ _bavValue :: Maybe Base64
} deriving (Eq, Read, Show)
-- | 'BlobAttributeValue' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'bavValue' @::@ 'Maybe' 'Base64'
--
blobAttributeValue :: BlobAttributeValue
blobAttributeValue = BlobAttributeValue
{ _bavValue = Nothing
}
bavValue :: Lens' BlobAttributeValue (Maybe Base64)
bavValue = lens _bavValue (\s a -> s { _bavValue = a })
instance FromXML BlobAttributeValue where
parseXML x = BlobAttributeValue
<$> x .@? "value"
instance ToQuery BlobAttributeValue where
toQuery BlobAttributeValue{..} = mconcat
[ "Value" =? _bavValue
]
data ImportInstanceLaunchSpecification = ImportInstanceLaunchSpecification
{ _iilsAdditionalInfo :: Maybe Text
, _iilsArchitecture :: Maybe ArchitectureValues
, _iilsGroupIds :: List "SecurityGroupId" Text
, _iilsGroupNames :: List "SecurityGroup" Text
, _iilsInstanceInitiatedShutdownBehavior :: Maybe ShutdownBehavior
, _iilsInstanceType :: Maybe InstanceType
, _iilsMonitoring :: Maybe Bool
, _iilsPlacement :: Maybe Placement
, _iilsPrivateIpAddress :: Maybe Text
, _iilsSubnetId :: Maybe Text
, _iilsUserData :: Maybe UserData
} deriving (Eq, Read, Show)
-- | 'ImportInstanceLaunchSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iilsAdditionalInfo' @::@ 'Maybe' 'Text'
--
-- * 'iilsArchitecture' @::@ 'Maybe' 'ArchitectureValues'
--
-- * 'iilsGroupIds' @::@ ['Text']
--
-- * 'iilsGroupNames' @::@ ['Text']
--
-- * 'iilsInstanceInitiatedShutdownBehavior' @::@ 'Maybe' 'ShutdownBehavior'
--
-- * 'iilsInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'iilsMonitoring' @::@ 'Maybe' 'Bool'
--
-- * 'iilsPlacement' @::@ 'Maybe' 'Placement'
--
-- * 'iilsPrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'iilsSubnetId' @::@ 'Maybe' 'Text'
--
-- * 'iilsUserData' @::@ 'Maybe' 'UserData'
--
importInstanceLaunchSpecification :: ImportInstanceLaunchSpecification
importInstanceLaunchSpecification = ImportInstanceLaunchSpecification
{ _iilsArchitecture = Nothing
, _iilsGroupNames = mempty
, _iilsGroupIds = mempty
, _iilsAdditionalInfo = Nothing
, _iilsUserData = Nothing
, _iilsInstanceType = Nothing
, _iilsPlacement = Nothing
, _iilsMonitoring = Nothing
, _iilsSubnetId = Nothing
, _iilsInstanceInitiatedShutdownBehavior = Nothing
, _iilsPrivateIpAddress = Nothing
}
iilsAdditionalInfo :: Lens' ImportInstanceLaunchSpecification (Maybe Text)
iilsAdditionalInfo =
lens _iilsAdditionalInfo (\s a -> s { _iilsAdditionalInfo = a })
-- | The architecture of the instance.
iilsArchitecture :: Lens' ImportInstanceLaunchSpecification (Maybe ArchitectureValues)
iilsArchitecture = lens _iilsArchitecture (\s a -> s { _iilsArchitecture = a })
-- | One or more security group IDs.
iilsGroupIds :: Lens' ImportInstanceLaunchSpecification [Text]
iilsGroupIds = lens _iilsGroupIds (\s a -> s { _iilsGroupIds = a }) . _List
-- | One or more security group names.
iilsGroupNames :: Lens' ImportInstanceLaunchSpecification [Text]
iilsGroupNames = lens _iilsGroupNames (\s a -> s { _iilsGroupNames = a }) . _List
-- | Indicates whether an instance stops or terminates when you initiate shutdown
-- from the instance (using the operating system command for system shutdown).
iilsInstanceInitiatedShutdownBehavior :: Lens' ImportInstanceLaunchSpecification (Maybe ShutdownBehavior)
iilsInstanceInitiatedShutdownBehavior =
lens _iilsInstanceInitiatedShutdownBehavior
(\s a -> s { _iilsInstanceInitiatedShutdownBehavior = a })
-- | The instance type. This is not supported for VMs imported into a VPC, which
-- are assigned the default security group. After a VM is imported into a VPC,
-- you can specify another security group using the AWS Management Console. For
-- more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html Instance Types> in the /Amazon Elastic Compute Cloud UserGuide for Linux/. For more information about the Linux instance types you can
-- import, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/VMImportPrerequisites.html Before You Get Started> in the Amazon Elastic Compute Cloud User
-- Guide for Linux.
iilsInstanceType :: Lens' ImportInstanceLaunchSpecification (Maybe InstanceType)
iilsInstanceType = lens _iilsInstanceType (\s a -> s { _iilsInstanceType = a })
iilsMonitoring :: Lens' ImportInstanceLaunchSpecification (Maybe Bool)
iilsMonitoring = lens _iilsMonitoring (\s a -> s { _iilsMonitoring = a })
iilsPlacement :: Lens' ImportInstanceLaunchSpecification (Maybe Placement)
iilsPlacement = lens _iilsPlacement (\s a -> s { _iilsPlacement = a })
-- | [EC2-VPC] Optionally, you can use this parameter to assign the instance a
-- specific available IP address from the IP address range of the subnet.
iilsPrivateIpAddress :: Lens' ImportInstanceLaunchSpecification (Maybe Text)
iilsPrivateIpAddress =
lens _iilsPrivateIpAddress (\s a -> s { _iilsPrivateIpAddress = a })
-- | [EC2-VPC] The ID of the subnet to launch the instance into.
iilsSubnetId :: Lens' ImportInstanceLaunchSpecification (Maybe Text)
iilsSubnetId = lens _iilsSubnetId (\s a -> s { _iilsSubnetId = a })
-- | User data to be made available to the instance.
iilsUserData :: Lens' ImportInstanceLaunchSpecification (Maybe UserData)
iilsUserData = lens _iilsUserData (\s a -> s { _iilsUserData = a })
instance FromXML ImportInstanceLaunchSpecification where
parseXML x = ImportInstanceLaunchSpecification
<$> x .@? "additionalInfo"
<*> x .@? "architecture"
<*> x .@? "GroupId" .!@ mempty
<*> x .@? "GroupName" .!@ mempty
<*> x .@? "instanceInitiatedShutdownBehavior"
<*> x .@? "instanceType"
<*> x .@? "monitoring"
<*> x .@? "placement"
<*> x .@? "privateIpAddress"
<*> x .@? "subnetId"
<*> x .@? "userData"
instance ToQuery ImportInstanceLaunchSpecification where
toQuery ImportInstanceLaunchSpecification{..} = mconcat
[ "AdditionalInfo" =? _iilsAdditionalInfo
, "Architecture" =? _iilsArchitecture
, "GroupId" `toQueryList` _iilsGroupIds
, "GroupName" `toQueryList` _iilsGroupNames
, "InstanceInitiatedShutdownBehavior" =? _iilsInstanceInitiatedShutdownBehavior
, "InstanceType" =? _iilsInstanceType
, "Monitoring" =? _iilsMonitoring
, "Placement" =? _iilsPlacement
, "PrivateIpAddress" =? _iilsPrivateIpAddress
, "SubnetId" =? _iilsSubnetId
, "UserData" =? _iilsUserData
]
data Snapshot = Snapshot
{ _sDescription :: Text
, _sEncrypted :: Bool
, _sKmsKeyId :: Maybe Text
, _sOwnerAlias :: Maybe Text
, _sOwnerId :: Text
, _sProgress :: Text
, _sSnapshotId :: Text
, _sStartTime :: ISO8601
, _sState :: SnapshotState
, _sTags :: List "item" Tag
, _sVolumeId :: Text
, _sVolumeSize :: Int
} deriving (Eq, Read, Show)
-- | 'Snapshot' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sDescription' @::@ 'Text'
--
-- * 'sEncrypted' @::@ 'Bool'
--
-- * 'sKmsKeyId' @::@ 'Maybe' 'Text'
--
-- * 'sOwnerAlias' @::@ 'Maybe' 'Text'
--
-- * 'sOwnerId' @::@ 'Text'
--
-- * 'sProgress' @::@ 'Text'
--
-- * 'sSnapshotId' @::@ 'Text'
--
-- * 'sStartTime' @::@ 'UTCTime'
--
-- * 'sState' @::@ 'SnapshotState'
--
-- * 'sTags' @::@ ['Tag']
--
-- * 'sVolumeId' @::@ 'Text'
--
-- * 'sVolumeSize' @::@ 'Int'
--
snapshot :: Text -- ^ 'sSnapshotId'
-> Text -- ^ 'sVolumeId'
-> SnapshotState -- ^ 'sState'
-> UTCTime -- ^ 'sStartTime'
-> Text -- ^ 'sProgress'
-> Text -- ^ 'sOwnerId'
-> Text -- ^ 'sDescription'
-> Int -- ^ 'sVolumeSize'
-> Bool -- ^ 'sEncrypted'
-> Snapshot
snapshot p1 p2 p3 p4 p5 p6 p7 p8 p9 = Snapshot
{ _sSnapshotId = p1
, _sVolumeId = p2
, _sState = p3
, _sStartTime = withIso _Time (const id) p4
, _sProgress = p5
, _sOwnerId = p6
, _sDescription = p7
, _sVolumeSize = p8
, _sEncrypted = p9
, _sOwnerAlias = Nothing
, _sTags = mempty
, _sKmsKeyId = Nothing
}
-- | The description for the snapshot.
sDescription :: Lens' Snapshot Text
sDescription = lens _sDescription (\s a -> s { _sDescription = a })
-- | Indicates whether the snapshot is encrypted.
sEncrypted :: Lens' Snapshot Bool
sEncrypted = lens _sEncrypted (\s a -> s { _sEncrypted = a })
-- | The full ARN of the AWS Key Management Service (KMS) master key that was used
-- to protect the volume encryption key for the parent volume.
sKmsKeyId :: Lens' Snapshot (Maybe Text)
sKmsKeyId = lens _sKmsKeyId (\s a -> s { _sKmsKeyId = a })
-- | The AWS account alias (for example, 'amazon', 'self') or AWS account ID that owns
-- the snapshot.
sOwnerAlias :: Lens' Snapshot (Maybe Text)
sOwnerAlias = lens _sOwnerAlias (\s a -> s { _sOwnerAlias = a })
-- | The AWS account ID of the Amazon EBS snapshot owner.
sOwnerId :: Lens' Snapshot Text
sOwnerId = lens _sOwnerId (\s a -> s { _sOwnerId = a })
-- | The progress of the snapshot, as a percentage.
sProgress :: Lens' Snapshot Text
sProgress = lens _sProgress (\s a -> s { _sProgress = a })
-- | The ID of the snapshot.
sSnapshotId :: Lens' Snapshot Text
sSnapshotId = lens _sSnapshotId (\s a -> s { _sSnapshotId = a })
-- | The time stamp when the snapshot was initiated.
sStartTime :: Lens' Snapshot UTCTime
sStartTime = lens _sStartTime (\s a -> s { _sStartTime = a }) . _Time
-- | The snapshot state.
sState :: Lens' Snapshot SnapshotState
sState = lens _sState (\s a -> s { _sState = a })
-- | Any tags assigned to the snapshot.
sTags :: Lens' Snapshot [Tag]
sTags = lens _sTags (\s a -> s { _sTags = a }) . _List
-- | The ID of the volume.
sVolumeId :: Lens' Snapshot Text
sVolumeId = lens _sVolumeId (\s a -> s { _sVolumeId = a })
-- | The size of the volume, in GiB.
sVolumeSize :: Lens' Snapshot Int
sVolumeSize = lens _sVolumeSize (\s a -> s { _sVolumeSize = a })
instance FromXML Snapshot where
parseXML x = Snapshot
<$> x .@ "description"
<*> x .@ "encrypted"
<*> x .@? "kmsKeyId"
<*> x .@? "ownerAlias"
<*> x .@ "ownerId"
<*> x .@ "progress"
<*> x .@ "snapshotId"
<*> x .@ "startTime"
<*> x .@ "status"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "volumeId"
<*> x .@ "volumeSize"
instance ToQuery Snapshot where
toQuery Snapshot{..} = mconcat
[ "Description" =? _sDescription
, "Encrypted" =? _sEncrypted
, "KmsKeyId" =? _sKmsKeyId
, "OwnerAlias" =? _sOwnerAlias
, "OwnerId" =? _sOwnerId
, "Progress" =? _sProgress
, "SnapshotId" =? _sSnapshotId
, "StartTime" =? _sStartTime
, "Status" =? _sState
, "TagSet" `toQueryList` _sTags
, "VolumeId" =? _sVolumeId
, "VolumeSize" =? _sVolumeSize
]
data SpotInstanceStateFault = SpotInstanceStateFault
{ _sisfCode :: Maybe Text
, _sisfMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'SpotInstanceStateFault' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sisfCode' @::@ 'Maybe' 'Text'
--
-- * 'sisfMessage' @::@ 'Maybe' 'Text'
--
spotInstanceStateFault :: SpotInstanceStateFault
spotInstanceStateFault = SpotInstanceStateFault
{ _sisfCode = Nothing
, _sisfMessage = Nothing
}
-- | The reason code for the Spot Instance state change.
sisfCode :: Lens' SpotInstanceStateFault (Maybe Text)
sisfCode = lens _sisfCode (\s a -> s { _sisfCode = a })
-- | The message for the Spot Instance state change.
sisfMessage :: Lens' SpotInstanceStateFault (Maybe Text)
sisfMessage = lens _sisfMessage (\s a -> s { _sisfMessage = a })
instance FromXML SpotInstanceStateFault where
parseXML x = SpotInstanceStateFault
<$> x .@? "code"
<*> x .@? "message"
instance ToQuery SpotInstanceStateFault where
toQuery SpotInstanceStateFault{..} = mconcat
[ "Code" =? _sisfCode
, "Message" =? _sisfMessage
]
data TagDescription = TagDescription
{ _tdKey :: Text
, _tdResourceId :: Text
, _tdResourceType :: ResourceType
, _tdValue :: Text
} deriving (Eq, Read, Show)
-- | 'TagDescription' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'tdKey' @::@ 'Text'
--
-- * 'tdResourceId' @::@ 'Text'
--
-- * 'tdResourceType' @::@ 'ResourceType'
--
-- * 'tdValue' @::@ 'Text'
--
tagDescription :: Text -- ^ 'tdResourceId'
-> ResourceType -- ^ 'tdResourceType'
-> Text -- ^ 'tdKey'
-> Text -- ^ 'tdValue'
-> TagDescription
tagDescription p1 p2 p3 p4 = TagDescription
{ _tdResourceId = p1
, _tdResourceType = p2
, _tdKey = p3
, _tdValue = p4
}
-- | The tag key.
tdKey :: Lens' TagDescription Text
tdKey = lens _tdKey (\s a -> s { _tdKey = a })
-- | The ID of the resource. For example, 'ami-1a2b3c4d'.
tdResourceId :: Lens' TagDescription Text
tdResourceId = lens _tdResourceId (\s a -> s { _tdResourceId = a })
-- | The resource type.
tdResourceType :: Lens' TagDescription ResourceType
tdResourceType = lens _tdResourceType (\s a -> s { _tdResourceType = a })
-- | The tag value.
tdValue :: Lens' TagDescription Text
tdValue = lens _tdValue (\s a -> s { _tdValue = a })
instance FromXML TagDescription where
parseXML x = TagDescription
<$> x .@ "key"
<*> x .@ "resourceId"
<*> x .@ "resourceType"
<*> x .@ "value"
instance ToQuery TagDescription where
toQuery TagDescription{..} = mconcat
[ "Key" =? _tdKey
, "ResourceId" =? _tdResourceId
, "ResourceType" =? _tdResourceType
, "Value" =? _tdValue
]
data GroupIdentifier = GroupIdentifier
{ _giGroupId :: Maybe Text
, _giGroupName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'GroupIdentifier' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'giGroupId' @::@ 'Maybe' 'Text'
--
-- * 'giGroupName' @::@ 'Maybe' 'Text'
--
groupIdentifier :: GroupIdentifier
groupIdentifier = GroupIdentifier
{ _giGroupName = Nothing
, _giGroupId = Nothing
}
-- | The ID of the security group.
giGroupId :: Lens' GroupIdentifier (Maybe Text)
giGroupId = lens _giGroupId (\s a -> s { _giGroupId = a })
-- | The name of the security group.
giGroupName :: Lens' GroupIdentifier (Maybe Text)
giGroupName = lens _giGroupName (\s a -> s { _giGroupName = a })
instance FromXML GroupIdentifier where
parseXML x = GroupIdentifier
<$> x .@? "groupId"
<*> x .@? "groupName"
instance ToQuery GroupIdentifier where
toQuery GroupIdentifier{..} = mconcat
[ "GroupId" =? _giGroupId
, "GroupName" =? _giGroupName
]
data VpnStaticRouteSource
= Static -- ^ Static
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VpnStaticRouteSource
instance FromText VpnStaticRouteSource where
parser = takeLowerText >>= \case
"static" -> pure Static
e -> fail $
"Failure parsing VpnStaticRouteSource from " ++ show e
instance ToText VpnStaticRouteSource where
toText Static = "Static"
instance ToByteString VpnStaticRouteSource
instance ToHeader VpnStaticRouteSource
instance ToQuery VpnStaticRouteSource
instance FromXML VpnStaticRouteSource where
parseXML = parseXMLText "VpnStaticRouteSource"
data ReservedInstancesListing = ReservedInstancesListing
{ _rilClientToken :: Maybe Text
, _rilCreateDate :: Maybe ISO8601
, _rilInstanceCounts :: List "item" InstanceCount
, _rilPriceSchedules :: List "item" PriceSchedule
, _rilReservedInstancesId :: Maybe Text
, _rilReservedInstancesListingId :: Maybe Text
, _rilStatus :: Maybe ListingStatus
, _rilStatusMessage :: Maybe Text
, _rilTags :: List "item" Tag
, _rilUpdateDate :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'ReservedInstancesListing' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rilClientToken' @::@ 'Maybe' 'Text'
--
-- * 'rilCreateDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'rilInstanceCounts' @::@ ['InstanceCount']
--
-- * 'rilPriceSchedules' @::@ ['PriceSchedule']
--
-- * 'rilReservedInstancesId' @::@ 'Maybe' 'Text'
--
-- * 'rilReservedInstancesListingId' @::@ 'Maybe' 'Text'
--
-- * 'rilStatus' @::@ 'Maybe' 'ListingStatus'
--
-- * 'rilStatusMessage' @::@ 'Maybe' 'Text'
--
-- * 'rilTags' @::@ ['Tag']
--
-- * 'rilUpdateDate' @::@ 'Maybe' 'UTCTime'
--
reservedInstancesListing :: ReservedInstancesListing
reservedInstancesListing = ReservedInstancesListing
{ _rilReservedInstancesListingId = Nothing
, _rilReservedInstancesId = Nothing
, _rilCreateDate = Nothing
, _rilUpdateDate = Nothing
, _rilStatus = Nothing
, _rilStatusMessage = Nothing
, _rilInstanceCounts = mempty
, _rilPriceSchedules = mempty
, _rilTags = mempty
, _rilClientToken = Nothing
}
-- | A unique, case-sensitive key supplied by the client to ensure that the
-- request is idempotent. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html Ensuring Idempotency>.
rilClientToken :: Lens' ReservedInstancesListing (Maybe Text)
rilClientToken = lens _rilClientToken (\s a -> s { _rilClientToken = a })
-- | The time the listing was created.
rilCreateDate :: Lens' ReservedInstancesListing (Maybe UTCTime)
rilCreateDate = lens _rilCreateDate (\s a -> s { _rilCreateDate = a }) . mapping _Time
-- | The number of instances in this state.
rilInstanceCounts :: Lens' ReservedInstancesListing [InstanceCount]
rilInstanceCounts =
lens _rilInstanceCounts (\s a -> s { _rilInstanceCounts = a })
. _List
-- | The price of the Reserved Instance listing.
rilPriceSchedules :: Lens' ReservedInstancesListing [PriceSchedule]
rilPriceSchedules =
lens _rilPriceSchedules (\s a -> s { _rilPriceSchedules = a })
. _List
-- | The ID of the Reserved Instance.
rilReservedInstancesId :: Lens' ReservedInstancesListing (Maybe Text)
rilReservedInstancesId =
lens _rilReservedInstancesId (\s a -> s { _rilReservedInstancesId = a })
-- | The ID of the Reserved Instance listing.
rilReservedInstancesListingId :: Lens' ReservedInstancesListing (Maybe Text)
rilReservedInstancesListingId =
lens _rilReservedInstancesListingId
(\s a -> s { _rilReservedInstancesListingId = a })
-- | The status of the Reserved Instance listing.
rilStatus :: Lens' ReservedInstancesListing (Maybe ListingStatus)
rilStatus = lens _rilStatus (\s a -> s { _rilStatus = a })
-- | The reason for the current status of the Reserved Instance listing. The
-- response can be blank.
rilStatusMessage :: Lens' ReservedInstancesListing (Maybe Text)
rilStatusMessage = lens _rilStatusMessage (\s a -> s { _rilStatusMessage = a })
-- | Any tags assigned to the resource.
rilTags :: Lens' ReservedInstancesListing [Tag]
rilTags = lens _rilTags (\s a -> s { _rilTags = a }) . _List
-- | The last modified timestamp of the listing.
rilUpdateDate :: Lens' ReservedInstancesListing (Maybe UTCTime)
rilUpdateDate = lens _rilUpdateDate (\s a -> s { _rilUpdateDate = a }) . mapping _Time
instance FromXML ReservedInstancesListing where
parseXML x = ReservedInstancesListing
<$> x .@? "clientToken"
<*> x .@? "createDate"
<*> x .@? "instanceCounts" .!@ mempty
<*> x .@? "priceSchedules" .!@ mempty
<*> x .@? "reservedInstancesId"
<*> x .@? "reservedInstancesListingId"
<*> x .@? "status"
<*> x .@? "statusMessage"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "updateDate"
instance ToQuery ReservedInstancesListing where
toQuery ReservedInstancesListing{..} = mconcat
[ "ClientToken" =? _rilClientToken
, "CreateDate" =? _rilCreateDate
, "InstanceCounts" `toQueryList` _rilInstanceCounts
, "PriceSchedules" `toQueryList` _rilPriceSchedules
, "ReservedInstancesId" =? _rilReservedInstancesId
, "ReservedInstancesListingId" =? _rilReservedInstancesListingId
, "Status" =? _rilStatus
, "StatusMessage" =? _rilStatusMessage
, "TagSet" `toQueryList` _rilTags
, "UpdateDate" =? _rilUpdateDate
]
data InstanceLifecycleType
= Spot -- ^ spot
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable InstanceLifecycleType
instance FromText InstanceLifecycleType where
parser = takeLowerText >>= \case
"spot" -> pure Spot
e -> fail $
"Failure parsing InstanceLifecycleType from " ++ show e
instance ToText InstanceLifecycleType where
toText Spot = "spot"
instance ToByteString InstanceLifecycleType
instance ToHeader InstanceLifecycleType
instance ToQuery InstanceLifecycleType
instance FromXML InstanceLifecycleType where
parseXML = parseXMLText "InstanceLifecycleType"
data VirtualizationType
= Hvm -- ^ hvm
| Paravirtual -- ^ paravirtual
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VirtualizationType
instance FromText VirtualizationType where
parser = takeLowerText >>= \case
"hvm" -> pure Hvm
"paravirtual" -> pure Paravirtual
e -> fail $
"Failure parsing VirtualizationType from " ++ show e
instance ToText VirtualizationType where
toText = \case
Hvm -> "hvm"
Paravirtual -> "paravirtual"
instance ToByteString VirtualizationType
instance ToHeader VirtualizationType
instance ToQuery VirtualizationType
instance FromXML VirtualizationType where
parseXML = parseXMLText "VirtualizationType"
data NetworkInterfaceStatus
= Attaching -- ^ attaching
| Available -- ^ available
| Detaching -- ^ detaching
| InUse -- ^ in-use
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable NetworkInterfaceStatus
instance FromText NetworkInterfaceStatus where
parser = takeLowerText >>= \case
"attaching" -> pure Attaching
"available" -> pure Available
"detaching" -> pure Detaching
"in-use" -> pure InUse
e -> fail $
"Failure parsing NetworkInterfaceStatus from " ++ show e
instance ToText NetworkInterfaceStatus where
toText = \case
Attaching -> "attaching"
Available -> "available"
Detaching -> "detaching"
InUse -> "in-use"
instance ToByteString NetworkInterfaceStatus
instance ToHeader NetworkInterfaceStatus
instance ToQuery NetworkInterfaceStatus
instance FromXML NetworkInterfaceStatus where
parseXML = parseXMLText "NetworkInterfaceStatus"
data PlatformValues
= Windows -- ^ Windows
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable PlatformValues
instance FromText PlatformValues where
parser = takeLowerText >>= \case
"windows" -> pure Windows
e -> fail $
"Failure parsing PlatformValues from " ++ show e
instance ToText PlatformValues where
toText Windows = "Windows"
instance ToByteString PlatformValues
instance ToHeader PlatformValues
instance ToQuery PlatformValues
instance FromXML PlatformValues where
parseXML = parseXMLText "PlatformValues"
data CreateVolumePermission = CreateVolumePermission
{ _cvpGroup :: Maybe PermissionGroup
, _cvpUserId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'CreateVolumePermission' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cvpGroup' @::@ 'Maybe' 'PermissionGroup'
--
-- * 'cvpUserId' @::@ 'Maybe' 'Text'
--
createVolumePermission :: CreateVolumePermission
createVolumePermission = CreateVolumePermission
{ _cvpUserId = Nothing
, _cvpGroup = Nothing
}
-- | The specific group that is to be added or removed from a volume's list of
-- create volume permissions.
cvpGroup :: Lens' CreateVolumePermission (Maybe PermissionGroup)
cvpGroup = lens _cvpGroup (\s a -> s { _cvpGroup = a })
-- | The specific AWS account ID that is to be added or removed from a volume's
-- list of create volume permissions.
cvpUserId :: Lens' CreateVolumePermission (Maybe Text)
cvpUserId = lens _cvpUserId (\s a -> s { _cvpUserId = a })
instance FromXML CreateVolumePermission where
parseXML x = CreateVolumePermission
<$> x .@? "group"
<*> x .@? "userId"
instance ToQuery CreateVolumePermission where
toQuery CreateVolumePermission{..} = mconcat
[ "Group" =? _cvpGroup
, "UserId" =? _cvpUserId
]
data NetworkInterfaceAttachmentChanges = NetworkInterfaceAttachmentChanges
{ _niacAttachmentId :: Maybe Text
, _niacDeleteOnTermination :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'NetworkInterfaceAttachmentChanges' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'niacAttachmentId' @::@ 'Maybe' 'Text'
--
-- * 'niacDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
networkInterfaceAttachmentChanges :: NetworkInterfaceAttachmentChanges
networkInterfaceAttachmentChanges = NetworkInterfaceAttachmentChanges
{ _niacAttachmentId = Nothing
, _niacDeleteOnTermination = Nothing
}
-- | The ID of the network interface attachment.
niacAttachmentId :: Lens' NetworkInterfaceAttachmentChanges (Maybe Text)
niacAttachmentId = lens _niacAttachmentId (\s a -> s { _niacAttachmentId = a })
-- | Indicates whether the network interface is deleted when the instance is
-- terminated.
niacDeleteOnTermination :: Lens' NetworkInterfaceAttachmentChanges (Maybe Bool)
niacDeleteOnTermination =
lens _niacDeleteOnTermination (\s a -> s { _niacDeleteOnTermination = a })
instance FromXML NetworkInterfaceAttachmentChanges where
parseXML x = NetworkInterfaceAttachmentChanges
<$> x .@? "attachmentId"
<*> x .@? "deleteOnTermination"
instance ToQuery NetworkInterfaceAttachmentChanges where
toQuery NetworkInterfaceAttachmentChanges{..} = mconcat
[ "AttachmentId" =? _niacAttachmentId
, "DeleteOnTermination" =? _niacDeleteOnTermination
]
data RecurringChargeFrequency
= Hourly -- ^ Hourly
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable RecurringChargeFrequency
instance FromText RecurringChargeFrequency where
parser = takeLowerText >>= \case
"hourly" -> pure Hourly
e -> fail $
"Failure parsing RecurringChargeFrequency from " ++ show e
instance ToText RecurringChargeFrequency where
toText Hourly = "Hourly"
instance ToByteString RecurringChargeFrequency
instance ToHeader RecurringChargeFrequency
instance ToQuery RecurringChargeFrequency
instance FromXML RecurringChargeFrequency where
parseXML = parseXMLText "RecurringChargeFrequency"
data DhcpOptions = DhcpOptions
{ _doDhcpConfigurations :: List "item" DhcpConfiguration
, _doDhcpOptionsId :: Maybe Text
, _doTags :: List "item" Tag
} deriving (Eq, Read, Show)
-- | 'DhcpOptions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'doDhcpConfigurations' @::@ ['DhcpConfiguration']
--
-- * 'doDhcpOptionsId' @::@ 'Maybe' 'Text'
--
-- * 'doTags' @::@ ['Tag']
--
dhcpOptions :: DhcpOptions
dhcpOptions = DhcpOptions
{ _doDhcpOptionsId = Nothing
, _doDhcpConfigurations = mempty
, _doTags = mempty
}
-- | One or more DHCP options in the set.
doDhcpConfigurations :: Lens' DhcpOptions [DhcpConfiguration]
doDhcpConfigurations =
lens _doDhcpConfigurations (\s a -> s { _doDhcpConfigurations = a })
. _List
-- | The ID of the set of DHCP options.
doDhcpOptionsId :: Lens' DhcpOptions (Maybe Text)
doDhcpOptionsId = lens _doDhcpOptionsId (\s a -> s { _doDhcpOptionsId = a })
-- | Any tags assigned to the DHCP options set.
doTags :: Lens' DhcpOptions [Tag]
doTags = lens _doTags (\s a -> s { _doTags = a }) . _List
instance FromXML DhcpOptions where
parseXML x = DhcpOptions
<$> x .@? "dhcpConfigurationSet" .!@ mempty
<*> x .@? "dhcpOptionsId"
<*> x .@? "tagSet" .!@ mempty
instance ToQuery DhcpOptions where
toQuery DhcpOptions{..} = mconcat
[ "DhcpConfigurationSet" `toQueryList` _doDhcpConfigurations
, "DhcpOptionsId" =? _doDhcpOptionsId
, "TagSet" `toQueryList` _doTags
]
data InstanceNetworkInterfaceSpecification = InstanceNetworkInterfaceSpecification
{ _inisAssociatePublicIpAddress :: Maybe Bool
, _inisDeleteOnTermination :: Maybe Bool
, _inisDescription :: Maybe Text
, _inisDeviceIndex :: Maybe Int
, _inisGroups :: List "SecurityGroupId" Text
, _inisNetworkInterfaceId :: Maybe Text
, _inisPrivateIpAddress :: Maybe Text
, _inisPrivateIpAddresses :: List "item" PrivateIpAddressSpecification
, _inisSecondaryPrivateIpAddressCount :: Maybe Int
, _inisSubnetId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'InstanceNetworkInterfaceSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'inisAssociatePublicIpAddress' @::@ 'Maybe' 'Bool'
--
-- * 'inisDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'inisDescription' @::@ 'Maybe' 'Text'
--
-- * 'inisDeviceIndex' @::@ 'Maybe' 'Int'
--
-- * 'inisGroups' @::@ ['Text']
--
-- * 'inisNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'inisPrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'inisPrivateIpAddresses' @::@ ['PrivateIpAddressSpecification']
--
-- * 'inisSecondaryPrivateIpAddressCount' @::@ 'Maybe' 'Int'
--
-- * 'inisSubnetId' @::@ 'Maybe' 'Text'
--
instanceNetworkInterfaceSpecification :: InstanceNetworkInterfaceSpecification
instanceNetworkInterfaceSpecification = InstanceNetworkInterfaceSpecification
{ _inisNetworkInterfaceId = Nothing
, _inisDeviceIndex = Nothing
, _inisSubnetId = Nothing
, _inisDescription = Nothing
, _inisPrivateIpAddress = Nothing
, _inisGroups = mempty
, _inisDeleteOnTermination = Nothing
, _inisPrivateIpAddresses = mempty
, _inisSecondaryPrivateIpAddressCount = Nothing
, _inisAssociatePublicIpAddress = Nothing
}
-- | Indicates whether to assign a public IP address to an instance you launch in
-- a VPC. The public IP address can only be assigned to a network interface for
-- eth0, and can only be assigned to a new network interface, not an existing
-- one. You cannot specify more than one network interface in the request. If
-- launching into a default subnet, the default value is 'true'.
inisAssociatePublicIpAddress :: Lens' InstanceNetworkInterfaceSpecification (Maybe Bool)
inisAssociatePublicIpAddress =
lens _inisAssociatePublicIpAddress
(\s a -> s { _inisAssociatePublicIpAddress = a })
-- | If set to 'true', the interface is deleted when the instance is terminated. You
-- can specify 'true' only if creating a new network interface when launching an
-- instance.
inisDeleteOnTermination :: Lens' InstanceNetworkInterfaceSpecification (Maybe Bool)
inisDeleteOnTermination =
lens _inisDeleteOnTermination (\s a -> s { _inisDeleteOnTermination = a })
-- | The description of the network interface. Applies only if creating a network
-- interface when launching an instance.
inisDescription :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text)
inisDescription = lens _inisDescription (\s a -> s { _inisDescription = a })
-- | The index of the device on the instance for the network interface attachment.
-- If you are specifying a network interface in a 'RunInstances' request, you must
-- provide the device index.
inisDeviceIndex :: Lens' InstanceNetworkInterfaceSpecification (Maybe Int)
inisDeviceIndex = lens _inisDeviceIndex (\s a -> s { _inisDeviceIndex = a })
-- | The IDs of the security groups for the network interface. Applies only if
-- creating a network interface when launching an instance.
inisGroups :: Lens' InstanceNetworkInterfaceSpecification [Text]
inisGroups = lens _inisGroups (\s a -> s { _inisGroups = a }) . _List
-- | The ID of the network interface.
inisNetworkInterfaceId :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text)
inisNetworkInterfaceId =
lens _inisNetworkInterfaceId (\s a -> s { _inisNetworkInterfaceId = a })
-- | The private IP address of the network interface. Applies only if creating a
-- network interface when launching an instance.
inisPrivateIpAddress :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text)
inisPrivateIpAddress =
lens _inisPrivateIpAddress (\s a -> s { _inisPrivateIpAddress = a })
-- | One or more private IP addresses to assign to the network interface. Only one
-- private IP address can be designated as primary.
inisPrivateIpAddresses :: Lens' InstanceNetworkInterfaceSpecification [PrivateIpAddressSpecification]
inisPrivateIpAddresses =
lens _inisPrivateIpAddresses (\s a -> s { _inisPrivateIpAddresses = a })
. _List
-- | The number of secondary private IP addresses. You can't specify this option
-- and specify more than one private IP address using the private IP addresses
-- option.
inisSecondaryPrivateIpAddressCount :: Lens' InstanceNetworkInterfaceSpecification (Maybe Int)
inisSecondaryPrivateIpAddressCount =
lens _inisSecondaryPrivateIpAddressCount
(\s a -> s { _inisSecondaryPrivateIpAddressCount = a })
-- | The ID of the subnet associated with the network string. Applies only if
-- creating a network interface when launching an instance.
inisSubnetId :: Lens' InstanceNetworkInterfaceSpecification (Maybe Text)
inisSubnetId = lens _inisSubnetId (\s a -> s { _inisSubnetId = a })
instance FromXML InstanceNetworkInterfaceSpecification where
parseXML x = InstanceNetworkInterfaceSpecification
<$> x .@? "associatePublicIpAddress"
<*> x .@? "deleteOnTermination"
<*> x .@? "description"
<*> x .@? "deviceIndex"
<*> x .@? "SecurityGroupId" .!@ mempty
<*> x .@? "networkInterfaceId"
<*> x .@? "privateIpAddress"
<*> x .@? "privateIpAddressesSet" .!@ mempty
<*> x .@? "secondaryPrivateIpAddressCount"
<*> x .@? "subnetId"
instance ToQuery InstanceNetworkInterfaceSpecification where
toQuery InstanceNetworkInterfaceSpecification{..} = mconcat
[ "AssociatePublicIpAddress" =? _inisAssociatePublicIpAddress
, "DeleteOnTermination" =? _inisDeleteOnTermination
, "Description" =? _inisDescription
, "DeviceIndex" =? _inisDeviceIndex
, "SecurityGroupId" `toQueryList` _inisGroups
, "NetworkInterfaceId" =? _inisNetworkInterfaceId
, "PrivateIpAddress" =? _inisPrivateIpAddress
, "PrivateIpAddressesSet" `toQueryList` _inisPrivateIpAddresses
, "SecondaryPrivateIpAddressCount" =? _inisSecondaryPrivateIpAddressCount
, "SubnetId" =? _inisSubnetId
]
data VolumeState
= VSAvailable -- ^ available
| VSCreating -- ^ creating
| VSDeleted -- ^ deleted
| VSDeleting -- ^ deleting
| VSError -- ^ error
| VSInUse -- ^ in-use
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeState
instance FromText VolumeState where
parser = takeLowerText >>= \case
"available" -> pure VSAvailable
"creating" -> pure VSCreating
"deleted" -> pure VSDeleted
"deleting" -> pure VSDeleting
"error" -> pure VSError
"in-use" -> pure VSInUse
e -> fail $
"Failure parsing VolumeState from " ++ show e
instance ToText VolumeState where
toText = \case
VSAvailable -> "available"
VSCreating -> "creating"
VSDeleted -> "deleted"
VSDeleting -> "deleting"
VSError -> "error"
VSInUse -> "in-use"
instance ToByteString VolumeState
instance ToHeader VolumeState
instance ToQuery VolumeState
instance FromXML VolumeState where
parseXML = parseXMLText "VolumeState"
newtype AttributeValue = AttributeValue
{ _avValue :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'AttributeValue' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'avValue' @::@ 'Maybe' 'Text'
--
attributeValue :: AttributeValue
attributeValue = AttributeValue
{ _avValue = Nothing
}
-- | Valid values are case-sensitive and vary by action.
avValue :: Lens' AttributeValue (Maybe Text)
avValue = lens _avValue (\s a -> s { _avValue = a })
instance FromXML AttributeValue where
parseXML x = AttributeValue
<$> x .@? "value"
instance ToQuery AttributeValue where
toQuery AttributeValue{..} = mconcat
[ "Value" =? _avValue
]
data PrivateIpAddressSpecification = PrivateIpAddressSpecification
{ _piasPrimary :: Maybe Bool
, _piasPrivateIpAddress :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'PrivateIpAddressSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'piasPrimary' @::@ 'Maybe' 'Bool'
--
-- * 'piasPrivateIpAddress' @::@ 'Text'
--
privateIpAddressSpecification :: Text -- ^ 'piasPrivateIpAddress'
-> PrivateIpAddressSpecification
privateIpAddressSpecification p1 = PrivateIpAddressSpecification
{ _piasPrivateIpAddress = p1
, _piasPrimary = Nothing
}
-- | Indicates whether the private IP address is the primary private IP address.
-- Only one IP address can be designated as primary.
piasPrimary :: Lens' PrivateIpAddressSpecification (Maybe Bool)
piasPrimary = lens _piasPrimary (\s a -> s { _piasPrimary = a })
-- | The private IP addresses.
piasPrivateIpAddress :: Lens' PrivateIpAddressSpecification Text
piasPrivateIpAddress =
lens _piasPrivateIpAddress (\s a -> s { _piasPrivateIpAddress = a })
instance FromXML PrivateIpAddressSpecification where
parseXML x = PrivateIpAddressSpecification
<$> x .@? "primary"
<*> x .@ "privateIpAddress"
instance ToQuery PrivateIpAddressSpecification where
toQuery PrivateIpAddressSpecification{..} = mconcat
[ "Primary" =? _piasPrimary
, "PrivateIpAddress" =? _piasPrivateIpAddress
]
data Image = Image
{ _iArchitecture :: ArchitectureValues
, _iBlockDeviceMappings :: List "item" BlockDeviceMapping
, _iCreationDate :: Maybe Text
, _iDescription :: Maybe Text
, _iHypervisor :: HypervisorType
, _iImageId :: Text
, _iImageLocation :: Text
, _iImageOwnerAlias :: Maybe Text
, _iImageType :: ImageTypeValues
, _iKernelId :: Maybe Text
, _iName :: Maybe Text
, _iOwnerId :: Text
, _iPlatform :: Maybe PlatformValues
, _iProductCodes :: List "item" ProductCode
, _iPublic :: Bool
, _iRamdiskId :: Maybe Text
, _iRootDeviceName :: Maybe Text
, _iRootDeviceType :: DeviceType
, _iSriovNetSupport :: Maybe Text
, _iState :: ImageState
, _iStateReason :: Maybe StateReason
, _iTags :: List "item" Tag
, _iVirtualizationType :: VirtualizationType
} deriving (Eq, Read, Show)
-- | 'Image' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iArchitecture' @::@ 'ArchitectureValues'
--
-- * 'iBlockDeviceMappings' @::@ ['BlockDeviceMapping']
--
-- * 'iCreationDate' @::@ 'Maybe' 'Text'
--
-- * 'iDescription' @::@ 'Maybe' 'Text'
--
-- * 'iHypervisor' @::@ 'HypervisorType'
--
-- * 'iImageId' @::@ 'Text'
--
-- * 'iImageLocation' @::@ 'Text'
--
-- * 'iImageOwnerAlias' @::@ 'Maybe' 'Text'
--
-- * 'iImageType' @::@ 'ImageTypeValues'
--
-- * 'iKernelId' @::@ 'Maybe' 'Text'
--
-- * 'iName' @::@ 'Maybe' 'Text'
--
-- * 'iOwnerId' @::@ 'Text'
--
-- * 'iPlatform' @::@ 'Maybe' 'PlatformValues'
--
-- * 'iProductCodes' @::@ ['ProductCode']
--
-- * 'iPublic' @::@ 'Bool'
--
-- * 'iRamdiskId' @::@ 'Maybe' 'Text'
--
-- * 'iRootDeviceName' @::@ 'Maybe' 'Text'
--
-- * 'iRootDeviceType' @::@ 'DeviceType'
--
-- * 'iSriovNetSupport' @::@ 'Maybe' 'Text'
--
-- * 'iState' @::@ 'ImageState'
--
-- * 'iStateReason' @::@ 'Maybe' 'StateReason'
--
-- * 'iTags' @::@ ['Tag']
--
-- * 'iVirtualizationType' @::@ 'VirtualizationType'
--
image :: Text -- ^ 'iImageId'
-> Text -- ^ 'iImageLocation'
-> ImageState -- ^ 'iState'
-> Text -- ^ 'iOwnerId'
-> Bool -- ^ 'iPublic'
-> ArchitectureValues -- ^ 'iArchitecture'
-> ImageTypeValues -- ^ 'iImageType'
-> DeviceType -- ^ 'iRootDeviceType'
-> VirtualizationType -- ^ 'iVirtualizationType'
-> HypervisorType -- ^ 'iHypervisor'
-> Image
image p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 = Image
{ _iImageId = p1
, _iImageLocation = p2
, _iState = p3
, _iOwnerId = p4
, _iPublic = p5
, _iArchitecture = p6
, _iImageType = p7
, _iRootDeviceType = p8
, _iVirtualizationType = p9
, _iHypervisor = p10
, _iCreationDate = Nothing
, _iProductCodes = mempty
, _iKernelId = Nothing
, _iRamdiskId = Nothing
, _iPlatform = Nothing
, _iSriovNetSupport = Nothing
, _iStateReason = Nothing
, _iImageOwnerAlias = Nothing
, _iName = Nothing
, _iDescription = Nothing
, _iRootDeviceName = Nothing
, _iBlockDeviceMappings = mempty
, _iTags = mempty
}
-- | The architecture of the image.
iArchitecture :: Lens' Image ArchitectureValues
iArchitecture = lens _iArchitecture (\s a -> s { _iArchitecture = a })
-- | Any block device mapping entries.
iBlockDeviceMappings :: Lens' Image [BlockDeviceMapping]
iBlockDeviceMappings =
lens _iBlockDeviceMappings (\s a -> s { _iBlockDeviceMappings = a })
. _List
-- | The date and time the image was created.
iCreationDate :: Lens' Image (Maybe Text)
iCreationDate = lens _iCreationDate (\s a -> s { _iCreationDate = a })
-- | The description of the AMI that was provided during image creation.
iDescription :: Lens' Image (Maybe Text)
iDescription = lens _iDescription (\s a -> s { _iDescription = a })
-- | The hypervisor type of the image.
iHypervisor :: Lens' Image HypervisorType
iHypervisor = lens _iHypervisor (\s a -> s { _iHypervisor = a })
-- | The ID of the AMI.
iImageId :: Lens' Image Text
iImageId = lens _iImageId (\s a -> s { _iImageId = a })
-- | The location of the AMI.
iImageLocation :: Lens' Image Text
iImageLocation = lens _iImageLocation (\s a -> s { _iImageLocation = a })
-- | The AWS account alias (for example, 'amazon', 'self') or the AWS account ID of
-- the AMI owner.
iImageOwnerAlias :: Lens' Image (Maybe Text)
iImageOwnerAlias = lens _iImageOwnerAlias (\s a -> s { _iImageOwnerAlias = a })
-- | The type of image.
iImageType :: Lens' Image ImageTypeValues
iImageType = lens _iImageType (\s a -> s { _iImageType = a })
-- | The kernel associated with the image, if any. Only applicable for machine
-- images.
iKernelId :: Lens' Image (Maybe Text)
iKernelId = lens _iKernelId (\s a -> s { _iKernelId = a })
-- | The name of the AMI that was provided during image creation.
iName :: Lens' Image (Maybe Text)
iName = lens _iName (\s a -> s { _iName = a })
-- | The AWS account ID of the image owner.
iOwnerId :: Lens' Image Text
iOwnerId = lens _iOwnerId (\s a -> s { _iOwnerId = a })
-- | The value is 'Windows' for Windows AMIs; otherwise blank.
iPlatform :: Lens' Image (Maybe PlatformValues)
iPlatform = lens _iPlatform (\s a -> s { _iPlatform = a })
-- | Any product codes associated with the AMI.
iProductCodes :: Lens' Image [ProductCode]
iProductCodes = lens _iProductCodes (\s a -> s { _iProductCodes = a }) . _List
-- | Indicates whether the image has public launch permissions. The value is 'true'
-- if this image has public launch permissions or 'false' if it has only implicit
-- and explicit launch permissions.
iPublic :: Lens' Image Bool
iPublic = lens _iPublic (\s a -> s { _iPublic = a })
-- | The RAM disk associated with the image, if any. Only applicable for machine
-- images.
iRamdiskId :: Lens' Image (Maybe Text)
iRamdiskId = lens _iRamdiskId (\s a -> s { _iRamdiskId = a })
-- | The device name of the root device (for example, '/dev/sda1' or '/dev/xvda').
iRootDeviceName :: Lens' Image (Maybe Text)
iRootDeviceName = lens _iRootDeviceName (\s a -> s { _iRootDeviceName = a })
-- | The type of root device used by the AMI. The AMI can use an Amazon EBS volume
-- or an instance store volume.
iRootDeviceType :: Lens' Image DeviceType
iRootDeviceType = lens _iRootDeviceType (\s a -> s { _iRootDeviceType = a })
-- | Specifies whether enhanced networking is enabled.
iSriovNetSupport :: Lens' Image (Maybe Text)
iSriovNetSupport = lens _iSriovNetSupport (\s a -> s { _iSriovNetSupport = a })
-- | The current state of the AMI. If the state is 'available', the image is
-- successfully registered and can be used to launch an instance.
iState :: Lens' Image ImageState
iState = lens _iState (\s a -> s { _iState = a })
-- | The reason for the state change.
iStateReason :: Lens' Image (Maybe StateReason)
iStateReason = lens _iStateReason (\s a -> s { _iStateReason = a })
-- | Any tags assigned to the image.
iTags :: Lens' Image [Tag]
iTags = lens _iTags (\s a -> s { _iTags = a }) . _List
-- | The type of virtualization of the AMI.
iVirtualizationType :: Lens' Image VirtualizationType
iVirtualizationType =
lens _iVirtualizationType (\s a -> s { _iVirtualizationType = a })
instance FromXML Image where
parseXML x = Image
<$> x .@ "architecture"
<*> x .@? "blockDeviceMapping" .!@ mempty
<*> x .@? "creationDate"
<*> x .@? "description"
<*> x .@ "hypervisor"
<*> x .@ "imageId"
<*> x .@ "imageLocation"
<*> x .@? "imageOwnerAlias"
<*> x .@ "imageType"
<*> x .@? "kernelId"
<*> x .@? "name"
<*> x .@ "imageOwnerId"
<*> x .@? "platform"
<*> x .@? "productCodes" .!@ mempty
<*> x .@ "isPublic"
<*> x .@? "ramdiskId"
<*> x .@? "rootDeviceName"
<*> x .@ "rootDeviceType"
<*> x .@? "sriovNetSupport"
<*> x .@ "imageState"
<*> x .@? "stateReason"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "virtualizationType"
instance ToQuery Image where
toQuery Image{..} = mconcat
[ "Architecture" =? _iArchitecture
, "BlockDeviceMapping" `toQueryList` _iBlockDeviceMappings
, "CreationDate" =? _iCreationDate
, "Description" =? _iDescription
, "Hypervisor" =? _iHypervisor
, "ImageId" =? _iImageId
, "ImageLocation" =? _iImageLocation
, "ImageOwnerAlias" =? _iImageOwnerAlias
, "ImageType" =? _iImageType
, "KernelId" =? _iKernelId
, "Name" =? _iName
, "ImageOwnerId" =? _iOwnerId
, "Platform" =? _iPlatform
, "ProductCodes" `toQueryList` _iProductCodes
, "IsPublic" =? _iPublic
, "RamdiskId" =? _iRamdiskId
, "RootDeviceName" =? _iRootDeviceName
, "RootDeviceType" =? _iRootDeviceType
, "SriovNetSupport" =? _iSriovNetSupport
, "ImageState" =? _iState
, "StateReason" =? _iStateReason
, "TagSet" `toQueryList` _iTags
, "VirtualizationType" =? _iVirtualizationType
]
data DhcpConfiguration = DhcpConfiguration
{ _dcKey :: Maybe Text
, _dcValues :: List "item" AttributeValue
} deriving (Eq, Read, Show)
-- | 'DhcpConfiguration' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcKey' @::@ 'Maybe' 'Text'
--
-- * 'dcValues' @::@ ['AttributeValue']
--
dhcpConfiguration :: DhcpConfiguration
dhcpConfiguration = DhcpConfiguration
{ _dcKey = Nothing
, _dcValues = mempty
}
-- | The name of a DHCP option.
dcKey :: Lens' DhcpConfiguration (Maybe Text)
dcKey = lens _dcKey (\s a -> s { _dcKey = a })
-- | One or more values for the DHCP option.
dcValues :: Lens' DhcpConfiguration [AttributeValue]
dcValues = lens _dcValues (\s a -> s { _dcValues = a }) . _List
instance FromXML DhcpConfiguration where
parseXML x = DhcpConfiguration
<$> x .@? "key"
<*> x .@? "valueSet" .!@ mempty
instance ToQuery DhcpConfiguration where
toQuery DhcpConfiguration{..} = mconcat
[ "Key" =? _dcKey
, "ValueSet" `toQueryList` _dcValues
]
data Tag = Tag
{ _tagKey :: Text
, _tagValue :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'Tag' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'tagKey' @::@ 'Text'
--
-- * 'tagValue' @::@ 'Text'
--
tag :: Text -- ^ 'tagKey'
-> Text -- ^ 'tagValue'
-> Tag
tag p1 p2 = Tag
{ _tagKey = p1
, _tagValue = p2
}
-- | The key of the tag.
--
-- Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode
-- characters. May not begin with 'aws:'
tagKey :: Lens' Tag Text
tagKey = lens _tagKey (\s a -> s { _tagKey = a })
-- | The value of the tag.
--
-- Constraints: Tag values are case-sensitive and accept a maximum of 255
-- Unicode characters.
tagValue :: Lens' Tag Text
tagValue = lens _tagValue (\s a -> s { _tagValue = a })
instance FromXML Tag where
parseXML x = Tag
<$> x .@ "key"
<*> x .@ "value"
instance ToQuery Tag where
toQuery Tag{..} = mconcat
[ "Key" =? _tagKey
, "Value" =? _tagValue
]
data AccountAttributeName
= DefaultVpc -- ^ default-vpc
| SupportedPlatforms -- ^ supported-platforms
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable AccountAttributeName
instance FromText AccountAttributeName where
parser = takeLowerText >>= \case
"default-vpc" -> pure DefaultVpc
"supported-platforms" -> pure SupportedPlatforms
e -> fail $
"Failure parsing AccountAttributeName from " ++ show e
instance ToText AccountAttributeName where
toText = \case
DefaultVpc -> "default-vpc"
SupportedPlatforms -> "supported-platforms"
instance ToByteString AccountAttributeName
instance ToHeader AccountAttributeName
instance ToQuery AccountAttributeName
instance FromXML AccountAttributeName where
parseXML = parseXMLText "AccountAttributeName"
data NetworkInterfaceAttachment = NetworkInterfaceAttachment
{ _niaAttachTime :: Maybe ISO8601
, _niaAttachmentId :: Maybe Text
, _niaDeleteOnTermination :: Maybe Bool
, _niaDeviceIndex :: Maybe Int
, _niaInstanceId :: Maybe Text
, _niaInstanceOwnerId :: Maybe Text
, _niaStatus :: Maybe AttachmentStatus
} deriving (Eq, Read, Show)
-- | 'NetworkInterfaceAttachment' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'niaAttachTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'niaAttachmentId' @::@ 'Maybe' 'Text'
--
-- * 'niaDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'niaDeviceIndex' @::@ 'Maybe' 'Int'
--
-- * 'niaInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'niaInstanceOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'niaStatus' @::@ 'Maybe' 'AttachmentStatus'
--
networkInterfaceAttachment :: NetworkInterfaceAttachment
networkInterfaceAttachment = NetworkInterfaceAttachment
{ _niaAttachmentId = Nothing
, _niaInstanceId = Nothing
, _niaInstanceOwnerId = Nothing
, _niaDeviceIndex = Nothing
, _niaStatus = Nothing
, _niaAttachTime = Nothing
, _niaDeleteOnTermination = Nothing
}
-- | The timestamp indicating when the attachment initiated.
niaAttachTime :: Lens' NetworkInterfaceAttachment (Maybe UTCTime)
niaAttachTime = lens _niaAttachTime (\s a -> s { _niaAttachTime = a }) . mapping _Time
-- | The ID of the network interface attachment.
niaAttachmentId :: Lens' NetworkInterfaceAttachment (Maybe Text)
niaAttachmentId = lens _niaAttachmentId (\s a -> s { _niaAttachmentId = a })
-- | Indicates whether the network interface is deleted when the instance is
-- terminated.
niaDeleteOnTermination :: Lens' NetworkInterfaceAttachment (Maybe Bool)
niaDeleteOnTermination =
lens _niaDeleteOnTermination (\s a -> s { _niaDeleteOnTermination = a })
-- | The device index of the network interface attachment on the instance.
niaDeviceIndex :: Lens' NetworkInterfaceAttachment (Maybe Int)
niaDeviceIndex = lens _niaDeviceIndex (\s a -> s { _niaDeviceIndex = a })
-- | The ID of the instance.
niaInstanceId :: Lens' NetworkInterfaceAttachment (Maybe Text)
niaInstanceId = lens _niaInstanceId (\s a -> s { _niaInstanceId = a })
-- | The AWS account ID of the owner of the instance.
niaInstanceOwnerId :: Lens' NetworkInterfaceAttachment (Maybe Text)
niaInstanceOwnerId =
lens _niaInstanceOwnerId (\s a -> s { _niaInstanceOwnerId = a })
-- | The attachment state.
niaStatus :: Lens' NetworkInterfaceAttachment (Maybe AttachmentStatus)
niaStatus = lens _niaStatus (\s a -> s { _niaStatus = a })
instance FromXML NetworkInterfaceAttachment where
parseXML x = NetworkInterfaceAttachment
<$> x .@? "attachTime"
<*> x .@? "attachmentId"
<*> x .@? "deleteOnTermination"
<*> x .@? "deviceIndex"
<*> x .@? "instanceId"
<*> x .@? "instanceOwnerId"
<*> x .@? "status"
instance ToQuery NetworkInterfaceAttachment where
toQuery NetworkInterfaceAttachment{..} = mconcat
[ "AttachTime" =? _niaAttachTime
, "AttachmentId" =? _niaAttachmentId
, "DeleteOnTermination" =? _niaDeleteOnTermination
, "DeviceIndex" =? _niaDeviceIndex
, "InstanceId" =? _niaInstanceId
, "InstanceOwnerId" =? _niaInstanceOwnerId
, "Status" =? _niaStatus
]
newtype RunInstancesMonitoringEnabled = RunInstancesMonitoringEnabled
{ _rimeEnabled :: Bool
} deriving (Eq, Ord, Read, Show, Enum)
-- | 'RunInstancesMonitoringEnabled' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rimeEnabled' @::@ 'Bool'
--
runInstancesMonitoringEnabled :: Bool -- ^ 'rimeEnabled'
-> RunInstancesMonitoringEnabled
runInstancesMonitoringEnabled p1 = RunInstancesMonitoringEnabled
{ _rimeEnabled = p1
}
-- | Indicates whether monitoring is enabled for the instance.
rimeEnabled :: Lens' RunInstancesMonitoringEnabled Bool
rimeEnabled = lens _rimeEnabled (\s a -> s { _rimeEnabled = a })
instance FromXML RunInstancesMonitoringEnabled where
parseXML x = RunInstancesMonitoringEnabled
<$> x .@ "enabled"
instance ToQuery RunInstancesMonitoringEnabled where
toQuery RunInstancesMonitoringEnabled{..} = mconcat
[ "Enabled" =? _rimeEnabled
]
data VolumeStatusInfo = VolumeStatusInfo
{ _vsiDetails :: List "item" VolumeStatusDetails
, _vsiStatus :: Maybe VolumeStatusInfoStatus
} deriving (Eq, Read, Show)
-- | 'VolumeStatusInfo' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vsiDetails' @::@ ['VolumeStatusDetails']
--
-- * 'vsiStatus' @::@ 'Maybe' 'VolumeStatusInfoStatus'
--
volumeStatusInfo :: VolumeStatusInfo
volumeStatusInfo = VolumeStatusInfo
{ _vsiStatus = Nothing
, _vsiDetails = mempty
}
-- | The details of the volume status.
vsiDetails :: Lens' VolumeStatusInfo [VolumeStatusDetails]
vsiDetails = lens _vsiDetails (\s a -> s { _vsiDetails = a }) . _List
-- | The status of the volume.
vsiStatus :: Lens' VolumeStatusInfo (Maybe VolumeStatusInfoStatus)
vsiStatus = lens _vsiStatus (\s a -> s { _vsiStatus = a })
instance FromXML VolumeStatusInfo where
parseXML x = VolumeStatusInfo
<$> x .@? "details" .!@ mempty
<*> x .@? "status"
instance ToQuery VolumeStatusInfo where
toQuery VolumeStatusInfo{..} = mconcat
[ "Details" `toQueryList` _vsiDetails
, "Status" =? _vsiStatus
]
data NetworkInterfaceAssociation = NetworkInterfaceAssociation
{ _niaAllocationId :: Maybe Text
, _niaAssociationId :: Maybe Text
, _niaIpOwnerId :: Maybe Text
, _niaPublicDnsName :: Maybe Text
, _niaPublicIp :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'NetworkInterfaceAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'niaAllocationId' @::@ 'Maybe' 'Text'
--
-- * 'niaAssociationId' @::@ 'Maybe' 'Text'
--
-- * 'niaIpOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'niaPublicDnsName' @::@ 'Maybe' 'Text'
--
-- * 'niaPublicIp' @::@ 'Maybe' 'Text'
--
networkInterfaceAssociation :: NetworkInterfaceAssociation
networkInterfaceAssociation = NetworkInterfaceAssociation
{ _niaPublicIp = Nothing
, _niaPublicDnsName = Nothing
, _niaIpOwnerId = Nothing
, _niaAllocationId = Nothing
, _niaAssociationId = Nothing
}
-- | The allocation ID.
niaAllocationId :: Lens' NetworkInterfaceAssociation (Maybe Text)
niaAllocationId = lens _niaAllocationId (\s a -> s { _niaAllocationId = a })
-- | The association ID.
niaAssociationId :: Lens' NetworkInterfaceAssociation (Maybe Text)
niaAssociationId = lens _niaAssociationId (\s a -> s { _niaAssociationId = a })
-- | The ID of the Elastic IP address owner.
niaIpOwnerId :: Lens' NetworkInterfaceAssociation (Maybe Text)
niaIpOwnerId = lens _niaIpOwnerId (\s a -> s { _niaIpOwnerId = a })
-- | The public DNS name.
niaPublicDnsName :: Lens' NetworkInterfaceAssociation (Maybe Text)
niaPublicDnsName = lens _niaPublicDnsName (\s a -> s { _niaPublicDnsName = a })
-- | The address of the Elastic IP address bound to the network interface.
niaPublicIp :: Lens' NetworkInterfaceAssociation (Maybe Text)
niaPublicIp = lens _niaPublicIp (\s a -> s { _niaPublicIp = a })
instance FromXML NetworkInterfaceAssociation where
parseXML x = NetworkInterfaceAssociation
<$> x .@? "allocationId"
<*> x .@? "associationId"
<*> x .@? "ipOwnerId"
<*> x .@? "publicDnsName"
<*> x .@? "publicIp"
instance ToQuery NetworkInterfaceAssociation where
toQuery NetworkInterfaceAssociation{..} = mconcat
[ "AllocationId" =? _niaAllocationId
, "AssociationId" =? _niaAssociationId
, "IpOwnerId" =? _niaIpOwnerId
, "PublicDnsName" =? _niaPublicDnsName
, "PublicIp" =? _niaPublicIp
]
data CreateVolumePermissionModifications = CreateVolumePermissionModifications
{ _cvpmAdd :: List "item" CreateVolumePermission
, _cvpmRemove :: List "item" CreateVolumePermission
} deriving (Eq, Read, Show)
-- | 'CreateVolumePermissionModifications' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cvpmAdd' @::@ ['CreateVolumePermission']
--
-- * 'cvpmRemove' @::@ ['CreateVolumePermission']
--
createVolumePermissionModifications :: CreateVolumePermissionModifications
createVolumePermissionModifications = CreateVolumePermissionModifications
{ _cvpmAdd = mempty
, _cvpmRemove = mempty
}
-- | Adds a specific AWS account ID or group to a volume's list of create volume
-- permissions.
cvpmAdd :: Lens' CreateVolumePermissionModifications [CreateVolumePermission]
cvpmAdd = lens _cvpmAdd (\s a -> s { _cvpmAdd = a }) . _List
-- | Removes a specific AWS account ID or group from a volume's list of create
-- volume permissions.
cvpmRemove :: Lens' CreateVolumePermissionModifications [CreateVolumePermission]
cvpmRemove = lens _cvpmRemove (\s a -> s { _cvpmRemove = a }) . _List
instance FromXML CreateVolumePermissionModifications where
parseXML x = CreateVolumePermissionModifications
<$> x .@? "Add" .!@ mempty
<*> x .@? "Remove" .!@ mempty
instance ToQuery CreateVolumePermissionModifications where
toQuery CreateVolumePermissionModifications{..} = mconcat
[ "Add" `toQueryList` _cvpmAdd
, "Remove" `toQueryList` _cvpmRemove
]
data VpcState
= VpcStateAvailable -- ^ available
| VpcStatePending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VpcState
instance FromText VpcState where
parser = takeLowerText >>= \case
"available" -> pure VpcStateAvailable
"pending" -> pure VpcStatePending
e -> fail $
"Failure parsing VpcState from " ++ show e
instance ToText VpcState where
toText = \case
VpcStateAvailable -> "available"
VpcStatePending -> "pending"
instance ToByteString VpcState
instance ToHeader VpcState
instance ToQuery VpcState
instance FromXML VpcState where
parseXML = parseXMLText "VpcState"
data ResourceType
= RTCustomerGateway -- ^ customer-gateway
| RTDhcpOptions -- ^ dhcp-options
| RTImage -- ^ image
| RTInstance' -- ^ instance
| RTInternetGateway -- ^ internet-gateway
| RTNetworkAcl -- ^ network-acl
| RTNetworkInterface -- ^ network-interface
| RTReservedInstances -- ^ reserved-instances
| RTRouteTable -- ^ route-table
| RTSecurityGroup -- ^ security-group
| RTSnapshot -- ^ snapshot
| RTSpotInstancesRequest -- ^ spot-instances-request
| RTSubnet -- ^ subnet
| RTVolume -- ^ volume
| RTVpc -- ^ vpc
| RTVpnConnection -- ^ vpn-connection
| RTVpnGateway -- ^ vpn-gateway
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ResourceType
instance FromText ResourceType where
parser = takeLowerText >>= \case
"customer-gateway" -> pure RTCustomerGateway
"dhcp-options" -> pure RTDhcpOptions
"image" -> pure RTImage
"instance" -> pure RTInstance'
"internet-gateway" -> pure RTInternetGateway
"network-acl" -> pure RTNetworkAcl
"network-interface" -> pure RTNetworkInterface
"reserved-instances" -> pure RTReservedInstances
"route-table" -> pure RTRouteTable
"security-group" -> pure RTSecurityGroup
"snapshot" -> pure RTSnapshot
"spot-instances-request" -> pure RTSpotInstancesRequest
"subnet" -> pure RTSubnet
"volume" -> pure RTVolume
"vpc" -> pure RTVpc
"vpn-connection" -> pure RTVpnConnection
"vpn-gateway" -> pure RTVpnGateway
e -> fail $
"Failure parsing ResourceType from " ++ show e
instance ToText ResourceType where
toText = \case
RTCustomerGateway -> "customer-gateway"
RTDhcpOptions -> "dhcp-options"
RTImage -> "image"
RTInstance' -> "instance"
RTInternetGateway -> "internet-gateway"
RTNetworkAcl -> "network-acl"
RTNetworkInterface -> "network-interface"
RTReservedInstances -> "reserved-instances"
RTRouteTable -> "route-table"
RTSecurityGroup -> "security-group"
RTSnapshot -> "snapshot"
RTSpotInstancesRequest -> "spot-instances-request"
RTSubnet -> "subnet"
RTVolume -> "volume"
RTVpc -> "vpc"
RTVpnConnection -> "vpn-connection"
RTVpnGateway -> "vpn-gateway"
instance ToByteString ResourceType
instance ToHeader ResourceType
instance ToQuery ResourceType
instance FromXML ResourceType where
parseXML = parseXMLText "ResourceType"
data ReportStatusType
= Impaired -- ^ impaired
| Ok -- ^ ok
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ReportStatusType
instance FromText ReportStatusType where
parser = takeLowerText >>= \case
"impaired" -> pure Impaired
"ok" -> pure Ok
e -> fail $
"Failure parsing ReportStatusType from " ++ show e
instance ToText ReportStatusType where
toText = \case
Impaired -> "impaired"
Ok -> "ok"
instance ToByteString ReportStatusType
instance ToHeader ReportStatusType
instance ToQuery ReportStatusType
instance FromXML ReportStatusType where
parseXML = parseXMLText "ReportStatusType"
data CurrencyCodeValues
= Usd -- ^ USD
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable CurrencyCodeValues
instance FromText CurrencyCodeValues where
parser = takeLowerText >>= \case
"usd" -> pure Usd
e -> fail $
"Failure parsing CurrencyCodeValues from " ++ show e
instance ToText CurrencyCodeValues where
toText Usd = "USD"
instance ToByteString CurrencyCodeValues
instance ToHeader CurrencyCodeValues
instance ToQuery CurrencyCodeValues
instance FromXML CurrencyCodeValues where
parseXML = parseXMLText "CurrencyCodeValues"
data IcmpTypeCode = IcmpTypeCode
{ _itcCode :: Maybe Int
, _itcType :: Maybe Int
} deriving (Eq, Ord, Read, Show)
-- | 'IcmpTypeCode' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'itcCode' @::@ 'Maybe' 'Int'
--
-- * 'itcType' @::@ 'Maybe' 'Int'
--
icmpTypeCode :: IcmpTypeCode
icmpTypeCode = IcmpTypeCode
{ _itcType = Nothing
, _itcCode = Nothing
}
-- | The ICMP type. A value of -1 means all types.
itcCode :: Lens' IcmpTypeCode (Maybe Int)
itcCode = lens _itcCode (\s a -> s { _itcCode = a })
-- | The ICMP code. A value of -1 means all codes for the specified ICMP type.
itcType :: Lens' IcmpTypeCode (Maybe Int)
itcType = lens _itcType (\s a -> s { _itcType = a })
instance FromXML IcmpTypeCode where
parseXML x = IcmpTypeCode
<$> x .@? "code"
<*> x .@? "type"
instance ToQuery IcmpTypeCode where
toQuery IcmpTypeCode{..} = mconcat
[ "Code" =? _itcCode
, "Type" =? _itcType
]
data InstanceCount = InstanceCount
{ _icInstanceCount :: Maybe Int
, _icState :: Maybe ListingState
} deriving (Eq, Read, Show)
-- | 'InstanceCount' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'icInstanceCount' @::@ 'Maybe' 'Int'
--
-- * 'icState' @::@ 'Maybe' 'ListingState'
--
instanceCount :: InstanceCount
instanceCount = InstanceCount
{ _icState = Nothing
, _icInstanceCount = Nothing
}
-- | he number of listed Reserved Instances in the state specified by the 'state'.
icInstanceCount :: Lens' InstanceCount (Maybe Int)
icInstanceCount = lens _icInstanceCount (\s a -> s { _icInstanceCount = a })
-- | The states of the listed Reserved Instances.
icState :: Lens' InstanceCount (Maybe ListingState)
icState = lens _icState (\s a -> s { _icState = a })
instance FromXML InstanceCount where
parseXML x = InstanceCount
<$> x .@? "instanceCount"
<*> x .@? "state"
instance ToQuery InstanceCount where
toQuery InstanceCount{..} = mconcat
[ "InstanceCount" =? _icInstanceCount
, "State" =? _icState
]
data ExportToS3Task = ExportToS3Task
{ _etstContainerFormat :: Maybe ContainerFormat
, _etstDiskImageFormat :: Maybe DiskImageFormat
, _etstS3Bucket :: Maybe Text
, _etstS3Key :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ExportToS3Task' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'etstContainerFormat' @::@ 'Maybe' 'ContainerFormat'
--
-- * 'etstDiskImageFormat' @::@ 'Maybe' 'DiskImageFormat'
--
-- * 'etstS3Bucket' @::@ 'Maybe' 'Text'
--
-- * 'etstS3Key' @::@ 'Maybe' 'Text'
--
exportToS3Task :: ExportToS3Task
exportToS3Task = ExportToS3Task
{ _etstDiskImageFormat = Nothing
, _etstContainerFormat = Nothing
, _etstS3Bucket = Nothing
, _etstS3Key = Nothing
}
-- | The container format used to combine disk images with metadata (such as OVF).
-- If absent, only the disk image is exported.
etstContainerFormat :: Lens' ExportToS3Task (Maybe ContainerFormat)
etstContainerFormat =
lens _etstContainerFormat (\s a -> s { _etstContainerFormat = a })
-- | The format for the exported image.
etstDiskImageFormat :: Lens' ExportToS3Task (Maybe DiskImageFormat)
etstDiskImageFormat =
lens _etstDiskImageFormat (\s a -> s { _etstDiskImageFormat = a })
-- | The Amazon S3 bucket for the destination image. The destination bucket must
-- exist and grant WRITE and READ_ACP permissions to the AWS account 'vm-import-export@amazon.com'.
etstS3Bucket :: Lens' ExportToS3Task (Maybe Text)
etstS3Bucket = lens _etstS3Bucket (\s a -> s { _etstS3Bucket = a })
etstS3Key :: Lens' ExportToS3Task (Maybe Text)
etstS3Key = lens _etstS3Key (\s a -> s { _etstS3Key = a })
instance FromXML ExportToS3Task where
parseXML x = ExportToS3Task
<$> x .@? "containerFormat"
<*> x .@? "diskImageFormat"
<*> x .@? "s3Bucket"
<*> x .@? "s3Key"
instance ToQuery ExportToS3Task where
toQuery ExportToS3Task{..} = mconcat
[ "ContainerFormat" =? _etstContainerFormat
, "DiskImageFormat" =? _etstDiskImageFormat
, "S3Bucket" =? _etstS3Bucket
, "S3Key" =? _etstS3Key
]
data BlockDeviceMapping = BlockDeviceMapping
{ _bdmDeviceName :: Text
, _bdmEbs :: Maybe EbsBlockDevice
, _bdmNoDevice :: Maybe Text
, _bdmVirtualName :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'BlockDeviceMapping' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'bdmDeviceName' @::@ 'Text'
--
-- * 'bdmEbs' @::@ 'Maybe' 'EbsBlockDevice'
--
-- * 'bdmNoDevice' @::@ 'Maybe' 'Text'
--
-- * 'bdmVirtualName' @::@ 'Maybe' 'Text'
--
blockDeviceMapping :: Text -- ^ 'bdmDeviceName'
-> BlockDeviceMapping
blockDeviceMapping p1 = BlockDeviceMapping
{ _bdmDeviceName = p1
, _bdmVirtualName = Nothing
, _bdmEbs = Nothing
, _bdmNoDevice = Nothing
}
-- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh').
bdmDeviceName :: Lens' BlockDeviceMapping Text
bdmDeviceName = lens _bdmDeviceName (\s a -> s { _bdmDeviceName = a })
-- | Parameters used to automatically set up Amazon EBS volumes when the instance
-- is launched.
bdmEbs :: Lens' BlockDeviceMapping (Maybe EbsBlockDevice)
bdmEbs = lens _bdmEbs (\s a -> s { _bdmEbs = a })
-- | Suppresses the specified device included in the block device mapping of the
-- AMI.
bdmNoDevice :: Lens' BlockDeviceMapping (Maybe Text)
bdmNoDevice = lens _bdmNoDevice (\s a -> s { _bdmNoDevice = a })
-- | The virtual device name ('ephemeral'N). Instance store volumes are numbered
-- starting from 0. An instance type with 2 available instance store volumes can
-- specify mappings for 'ephemeral0' and 'ephemeral1'.The number of available
-- instance store volumes depends on the instance type. After you connect to the
-- instance, you must mount the volume.
--
-- Constraints: For M3 instances, you must specify instance store volumes in
-- the block device mapping for the instance. When you launch an M3 instance, we
-- ignore any instance store volumes specified in the block device mapping for
-- the AMI.
bdmVirtualName :: Lens' BlockDeviceMapping (Maybe Text)
bdmVirtualName = lens _bdmVirtualName (\s a -> s { _bdmVirtualName = a })
instance FromXML BlockDeviceMapping where
parseXML x = BlockDeviceMapping
<$> x .@ "deviceName"
<*> x .@? "ebs"
<*> x .@? "noDevice"
<*> x .@? "virtualName"
instance ToQuery BlockDeviceMapping where
toQuery BlockDeviceMapping{..} = mconcat
[ "DeviceName" =? _bdmDeviceName
, "Ebs" =? _bdmEbs
, "NoDevice" =? _bdmNoDevice
, "VirtualName" =? _bdmVirtualName
]
data ConversionTask = ConversionTask
{ _ctConversionTaskId :: Text
, _ctExpirationTime :: Maybe Text
, _ctImportInstance :: Maybe ImportInstanceTaskDetails
, _ctImportVolume :: Maybe ImportVolumeTaskDetails
, _ctState :: ConversionTaskState
, _ctStatusMessage :: Maybe Text
, _ctTags :: List "item" Tag
} deriving (Eq, Read, Show)
-- | 'ConversionTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ctConversionTaskId' @::@ 'Text'
--
-- * 'ctExpirationTime' @::@ 'Maybe' 'Text'
--
-- * 'ctImportInstance' @::@ 'Maybe' 'ImportInstanceTaskDetails'
--
-- * 'ctImportVolume' @::@ 'Maybe' 'ImportVolumeTaskDetails'
--
-- * 'ctState' @::@ 'ConversionTaskState'
--
-- * 'ctStatusMessage' @::@ 'Maybe' 'Text'
--
-- * 'ctTags' @::@ ['Tag']
--
conversionTask :: Text -- ^ 'ctConversionTaskId'
-> ConversionTaskState -- ^ 'ctState'
-> ConversionTask
conversionTask p1 p2 = ConversionTask
{ _ctConversionTaskId = p1
, _ctState = p2
, _ctExpirationTime = Nothing
, _ctImportInstance = Nothing
, _ctImportVolume = Nothing
, _ctStatusMessage = Nothing
, _ctTags = mempty
}
-- | The ID of the conversion task.
ctConversionTaskId :: Lens' ConversionTask Text
ctConversionTaskId =
lens _ctConversionTaskId (\s a -> s { _ctConversionTaskId = a })
-- | The time when the task expires. If the upload isn't complete before the
-- expiration time, we automatically cancel the task.
ctExpirationTime :: Lens' ConversionTask (Maybe Text)
ctExpirationTime = lens _ctExpirationTime (\s a -> s { _ctExpirationTime = a })
-- | If the task is for importing an instance, this contains information about the
-- import instance task.
ctImportInstance :: Lens' ConversionTask (Maybe ImportInstanceTaskDetails)
ctImportInstance = lens _ctImportInstance (\s a -> s { _ctImportInstance = a })
-- | If the task is for importing a volume, this contains information about the
-- import volume task.
ctImportVolume :: Lens' ConversionTask (Maybe ImportVolumeTaskDetails)
ctImportVolume = lens _ctImportVolume (\s a -> s { _ctImportVolume = a })
-- | The state of the conversion task.
ctState :: Lens' ConversionTask ConversionTaskState
ctState = lens _ctState (\s a -> s { _ctState = a })
-- | The status message related to the conversion task.
ctStatusMessage :: Lens' ConversionTask (Maybe Text)
ctStatusMessage = lens _ctStatusMessage (\s a -> s { _ctStatusMessage = a })
ctTags :: Lens' ConversionTask [Tag]
ctTags = lens _ctTags (\s a -> s { _ctTags = a }) . _List
instance FromXML ConversionTask where
parseXML x = ConversionTask
<$> x .@ "conversionTaskId"
<*> x .@? "expirationTime"
<*> x .@? "importInstance"
<*> x .@? "importVolume"
<*> x .@ "state"
<*> x .@? "statusMessage"
<*> x .@? "tagSet" .!@ mempty
instance ToQuery ConversionTask where
toQuery ConversionTask{..} = mconcat
[ "ConversionTaskId" =? _ctConversionTaskId
, "ExpirationTime" =? _ctExpirationTime
, "ImportInstance" =? _ctImportInstance
, "ImportVolume" =? _ctImportVolume
, "State" =? _ctState
, "StatusMessage" =? _ctStatusMessage
, "TagSet" `toQueryList` _ctTags
]
data AttachmentStatus
= ASAttached -- ^ attached
| ASAttaching -- ^ attaching
| ASDetached -- ^ detached
| ASDetaching -- ^ detaching
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable AttachmentStatus
instance FromText AttachmentStatus where
parser = takeLowerText >>= \case
"attached" -> pure ASAttached
"attaching" -> pure ASAttaching
"detached" -> pure ASDetached
"detaching" -> pure ASDetaching
e -> fail $
"Failure parsing AttachmentStatus from " ++ show e
instance ToText AttachmentStatus where
toText = \case
ASAttached -> "attached"
ASAttaching -> "attaching"
ASDetached -> "detached"
ASDetaching -> "detaching"
instance ToByteString AttachmentStatus
instance ToHeader AttachmentStatus
instance ToQuery AttachmentStatus
instance FromXML AttachmentStatus where
parseXML = parseXMLText "AttachmentStatus"
data ClassicLinkInstance = ClassicLinkInstance
{ _cliGroups :: List "item" GroupIdentifier
, _cliInstanceId :: Maybe Text
, _cliTags :: List "item" Tag
, _cliVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ClassicLinkInstance' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cliGroups' @::@ ['GroupIdentifier']
--
-- * 'cliInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'cliTags' @::@ ['Tag']
--
-- * 'cliVpcId' @::@ 'Maybe' 'Text'
--
classicLinkInstance :: ClassicLinkInstance
classicLinkInstance = ClassicLinkInstance
{ _cliInstanceId = Nothing
, _cliVpcId = Nothing
, _cliGroups = mempty
, _cliTags = mempty
}
-- | A list of security groups.
cliGroups :: Lens' ClassicLinkInstance [GroupIdentifier]
cliGroups = lens _cliGroups (\s a -> s { _cliGroups = a }) . _List
-- | The ID of the instance.
cliInstanceId :: Lens' ClassicLinkInstance (Maybe Text)
cliInstanceId = lens _cliInstanceId (\s a -> s { _cliInstanceId = a })
-- | Any tags assigned to the instance.
cliTags :: Lens' ClassicLinkInstance [Tag]
cliTags = lens _cliTags (\s a -> s { _cliTags = a }) . _List
-- | The ID of the VPC.
cliVpcId :: Lens' ClassicLinkInstance (Maybe Text)
cliVpcId = lens _cliVpcId (\s a -> s { _cliVpcId = a })
instance FromXML ClassicLinkInstance where
parseXML x = ClassicLinkInstance
<$> x .@? "groupSet" .!@ mempty
<*> x .@? "instanceId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery ClassicLinkInstance where
toQuery ClassicLinkInstance{..} = mconcat
[ "GroupSet" `toQueryList` _cliGroups
, "InstanceId" =? _cliInstanceId
, "TagSet" `toQueryList` _cliTags
, "VpcId" =? _cliVpcId
]
data RouteOrigin
= OriginCreateRoute -- ^ CreateRoute
| OriginCreateRouteTable -- ^ CreateRouteTable
| OriginEnableVgwRoutePropagation -- ^ EnableVgwRoutePropagation
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable RouteOrigin
instance FromText RouteOrigin where
parser = takeLowerText >>= \case
"createroute" -> pure OriginCreateRoute
"createroutetable" -> pure OriginCreateRouteTable
"enablevgwroutepropagation" -> pure OriginEnableVgwRoutePropagation
e -> fail $
"Failure parsing RouteOrigin from " ++ show e
instance ToText RouteOrigin where
toText = \case
OriginCreateRoute -> "CreateRoute"
OriginCreateRouteTable -> "CreateRouteTable"
OriginEnableVgwRoutePropagation -> "EnableVgwRoutePropagation"
instance ToByteString RouteOrigin
instance ToHeader RouteOrigin
instance ToQuery RouteOrigin
instance FromXML RouteOrigin where
parseXML = parseXMLText "RouteOrigin"
data ListingState
= LSAvailable -- ^ available
| LSCancelled -- ^ cancelled
| LSPending -- ^ pending
| LSSold -- ^ sold
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ListingState
instance FromText ListingState where
parser = takeLowerText >>= \case
"available" -> pure LSAvailable
"cancelled" -> pure LSCancelled
"pending" -> pure LSPending
"sold" -> pure LSSold
e -> fail $
"Failure parsing ListingState from " ++ show e
instance ToText ListingState where
toText = \case
LSAvailable -> "available"
LSCancelled -> "cancelled"
LSPending -> "pending"
LSSold -> "sold"
instance ToByteString ListingState
instance ToHeader ListingState
instance ToQuery ListingState
instance FromXML ListingState where
parseXML = parseXMLText "ListingState"
data SpotPrice = SpotPrice
{ _spAvailabilityZone :: Maybe Text
, _spInstanceType :: Maybe InstanceType
, _spProductDescription :: Maybe RIProductDescription
, _spSpotPrice :: Maybe Text
, _spTimestamp :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'SpotPrice' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'spAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'spInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'spProductDescription' @::@ 'Maybe' 'RIProductDescription'
--
-- * 'spSpotPrice' @::@ 'Maybe' 'Text'
--
-- * 'spTimestamp' @::@ 'Maybe' 'UTCTime'
--
spotPrice :: SpotPrice
spotPrice = SpotPrice
{ _spInstanceType = Nothing
, _spProductDescription = Nothing
, _spSpotPrice = Nothing
, _spTimestamp = Nothing
, _spAvailabilityZone = Nothing
}
-- | The Availability Zone.
spAvailabilityZone :: Lens' SpotPrice (Maybe Text)
spAvailabilityZone =
lens _spAvailabilityZone (\s a -> s { _spAvailabilityZone = a })
-- | The instance type.
spInstanceType :: Lens' SpotPrice (Maybe InstanceType)
spInstanceType = lens _spInstanceType (\s a -> s { _spInstanceType = a })
-- | A general description of the AMI.
spProductDescription :: Lens' SpotPrice (Maybe RIProductDescription)
spProductDescription =
lens _spProductDescription (\s a -> s { _spProductDescription = a })
-- | The maximum price (bid) that you are willing to pay for a Spot Instance.
spSpotPrice :: Lens' SpotPrice (Maybe Text)
spSpotPrice = lens _spSpotPrice (\s a -> s { _spSpotPrice = a })
-- | The date and time the request was created.
spTimestamp :: Lens' SpotPrice (Maybe UTCTime)
spTimestamp = lens _spTimestamp (\s a -> s { _spTimestamp = a }) . mapping _Time
instance FromXML SpotPrice where
parseXML x = SpotPrice
<$> x .@? "availabilityZone"
<*> x .@? "instanceType"
<*> x .@? "productDescription"
<*> x .@? "spotPrice"
<*> x .@? "timestamp"
instance ToQuery SpotPrice where
toQuery SpotPrice{..} = mconcat
[ "AvailabilityZone" =? _spAvailabilityZone
, "InstanceType" =? _spInstanceType
, "ProductDescription" =? _spProductDescription
, "SpotPrice" =? _spSpotPrice
, "Timestamp" =? _spTimestamp
]
data InstanceMonitoring = InstanceMonitoring
{ _imInstanceId :: Maybe Text
, _imMonitoring :: Maybe Monitoring
} deriving (Eq, Read, Show)
-- | 'InstanceMonitoring' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'imInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'imMonitoring' @::@ 'Maybe' 'Monitoring'
--
instanceMonitoring :: InstanceMonitoring
instanceMonitoring = InstanceMonitoring
{ _imInstanceId = Nothing
, _imMonitoring = Nothing
}
-- | The ID of the instance.
imInstanceId :: Lens' InstanceMonitoring (Maybe Text)
imInstanceId = lens _imInstanceId (\s a -> s { _imInstanceId = a })
-- | The monitoring information.
imMonitoring :: Lens' InstanceMonitoring (Maybe Monitoring)
imMonitoring = lens _imMonitoring (\s a -> s { _imMonitoring = a })
instance FromXML InstanceMonitoring where
parseXML x = InstanceMonitoring
<$> x .@? "instanceId"
<*> x .@? "monitoring"
instance ToQuery InstanceMonitoring where
toQuery InstanceMonitoring{..} = mconcat
[ "InstanceId" =? _imInstanceId
, "Monitoring" =? _imMonitoring
]
data PriceScheduleSpecification = PriceScheduleSpecification
{ _pssCurrencyCode :: Maybe CurrencyCodeValues
, _pssPrice :: Maybe Double
, _pssTerm :: Maybe Integer
} deriving (Eq, Read, Show)
-- | 'PriceScheduleSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pssCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues'
--
-- * 'pssPrice' @::@ 'Maybe' 'Double'
--
-- * 'pssTerm' @::@ 'Maybe' 'Integer'
--
priceScheduleSpecification :: PriceScheduleSpecification
priceScheduleSpecification = PriceScheduleSpecification
{ _pssTerm = Nothing
, _pssPrice = Nothing
, _pssCurrencyCode = Nothing
}
-- | The currency for transacting the Reserved Instance resale. At this time, the
-- only supported currency is 'USD'.
pssCurrencyCode :: Lens' PriceScheduleSpecification (Maybe CurrencyCodeValues)
pssCurrencyCode = lens _pssCurrencyCode (\s a -> s { _pssCurrencyCode = a })
-- | The fixed price for the term.
pssPrice :: Lens' PriceScheduleSpecification (Maybe Double)
pssPrice = lens _pssPrice (\s a -> s { _pssPrice = a })
-- | The number of months remaining in the reservation. For example, 2 is the
-- second to the last month before the capacity reservation expires.
pssTerm :: Lens' PriceScheduleSpecification (Maybe Integer)
pssTerm = lens _pssTerm (\s a -> s { _pssTerm = a })
instance FromXML PriceScheduleSpecification where
parseXML x = PriceScheduleSpecification
<$> x .@? "currencyCode"
<*> x .@? "price"
<*> x .@? "term"
instance ToQuery PriceScheduleSpecification where
toQuery PriceScheduleSpecification{..} = mconcat
[ "CurrencyCode" =? _pssCurrencyCode
, "Price" =? _pssPrice
, "Term" =? _pssTerm
]
data SpotInstanceStatus = SpotInstanceStatus
{ _sisCode :: Maybe Text
, _sisMessage :: Maybe Text
, _sisUpdateTime :: Maybe ISO8601
} deriving (Eq, Ord, Read, Show)
-- | 'SpotInstanceStatus' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sisCode' @::@ 'Maybe' 'Text'
--
-- * 'sisMessage' @::@ 'Maybe' 'Text'
--
-- * 'sisUpdateTime' @::@ 'Maybe' 'UTCTime'
--
spotInstanceStatus :: SpotInstanceStatus
spotInstanceStatus = SpotInstanceStatus
{ _sisCode = Nothing
, _sisUpdateTime = Nothing
, _sisMessage = Nothing
}
-- | The status code.
sisCode :: Lens' SpotInstanceStatus (Maybe Text)
sisCode = lens _sisCode (\s a -> s { _sisCode = a })
-- | The description for the status code.
sisMessage :: Lens' SpotInstanceStatus (Maybe Text)
sisMessage = lens _sisMessage (\s a -> s { _sisMessage = a })
-- | The time of the most recent status update.
sisUpdateTime :: Lens' SpotInstanceStatus (Maybe UTCTime)
sisUpdateTime = lens _sisUpdateTime (\s a -> s { _sisUpdateTime = a }) . mapping _Time
instance FromXML SpotInstanceStatus where
parseXML x = SpotInstanceStatus
<$> x .@? "code"
<*> x .@? "message"
<*> x .@? "updateTime"
instance ToQuery SpotInstanceStatus where
toQuery SpotInstanceStatus{..} = mconcat
[ "Code" =? _sisCode
, "Message" =? _sisMessage
, "UpdateTime" =? _sisUpdateTime
]
data AvailabilityZoneState
= AZSAvailable -- ^ available
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable AvailabilityZoneState
instance FromText AvailabilityZoneState where
parser = takeLowerText >>= \case
"available" -> pure AZSAvailable
e -> fail $
"Failure parsing AvailabilityZoneState from " ++ show e
instance ToText AvailabilityZoneState where
toText AZSAvailable = "available"
instance ToByteString AvailabilityZoneState
instance ToHeader AvailabilityZoneState
instance ToQuery AvailabilityZoneState
instance FromXML AvailabilityZoneState where
parseXML = parseXMLText "AvailabilityZoneState"
data SpotInstanceRequest = SpotInstanceRequest
{ _siAvailabilityZoneGroup :: Maybe Text
, _siCreateTime :: Maybe ISO8601
, _siFault :: Maybe SpotInstanceStateFault
, _siInstanceId :: Maybe Text
, _siLaunchGroup :: Maybe Text
, _siLaunchSpecification :: Maybe LaunchSpecification
, _siLaunchedAvailabilityZone :: Maybe Text
, _siProductDescription :: Maybe RIProductDescription
, _siSpotInstanceRequestId :: Maybe Text
, _siSpotPrice :: Maybe Text
, _siState :: Maybe SpotInstanceState
, _siStatus :: Maybe SpotInstanceStatus
, _siTags :: List "item" Tag
, _siType :: Maybe SpotInstanceType
, _siValidFrom :: Maybe ISO8601
, _siValidUntil :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'SpotInstanceRequest' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'siAvailabilityZoneGroup' @::@ 'Maybe' 'Text'
--
-- * 'siCreateTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'siFault' @::@ 'Maybe' 'SpotInstanceStateFault'
--
-- * 'siInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'siLaunchGroup' @::@ 'Maybe' 'Text'
--
-- * 'siLaunchSpecification' @::@ 'Maybe' 'LaunchSpecification'
--
-- * 'siLaunchedAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'siProductDescription' @::@ 'Maybe' 'RIProductDescription'
--
-- * 'siSpotInstanceRequestId' @::@ 'Maybe' 'Text'
--
-- * 'siSpotPrice' @::@ 'Maybe' 'Text'
--
-- * 'siState' @::@ 'Maybe' 'SpotInstanceState'
--
-- * 'siStatus' @::@ 'Maybe' 'SpotInstanceStatus'
--
-- * 'siTags' @::@ ['Tag']
--
-- * 'siType' @::@ 'Maybe' 'SpotInstanceType'
--
-- * 'siValidFrom' @::@ 'Maybe' 'UTCTime'
--
-- * 'siValidUntil' @::@ 'Maybe' 'UTCTime'
--
spotInstanceRequest :: SpotInstanceRequest
spotInstanceRequest = SpotInstanceRequest
{ _siSpotInstanceRequestId = Nothing
, _siSpotPrice = Nothing
, _siType = Nothing
, _siState = Nothing
, _siFault = Nothing
, _siStatus = Nothing
, _siValidFrom = Nothing
, _siValidUntil = Nothing
, _siLaunchGroup = Nothing
, _siAvailabilityZoneGroup = Nothing
, _siLaunchSpecification = Nothing
, _siInstanceId = Nothing
, _siCreateTime = Nothing
, _siProductDescription = Nothing
, _siTags = mempty
, _siLaunchedAvailabilityZone = Nothing
}
-- | The Availability Zone group. If you specify the same Availability Zone group
-- for all Spot Instance requests, all Spot Instances are launched in the same
-- Availability Zone.
siAvailabilityZoneGroup :: Lens' SpotInstanceRequest (Maybe Text)
siAvailabilityZoneGroup =
lens _siAvailabilityZoneGroup (\s a -> s { _siAvailabilityZoneGroup = a })
-- | The time stamp when the Spot Instance request was created.
siCreateTime :: Lens' SpotInstanceRequest (Maybe UTCTime)
siCreateTime = lens _siCreateTime (\s a -> s { _siCreateTime = a }) . mapping _Time
-- | The fault codes for the Spot Instance request, if any.
siFault :: Lens' SpotInstanceRequest (Maybe SpotInstanceStateFault)
siFault = lens _siFault (\s a -> s { _siFault = a })
-- | The instance ID, if an instance has been launched to fulfill the Spot
-- Instance request.
siInstanceId :: Lens' SpotInstanceRequest (Maybe Text)
siInstanceId = lens _siInstanceId (\s a -> s { _siInstanceId = a })
-- | The instance launch group. Launch groups are Spot Instances that launch
-- together and terminate together.
siLaunchGroup :: Lens' SpotInstanceRequest (Maybe Text)
siLaunchGroup = lens _siLaunchGroup (\s a -> s { _siLaunchGroup = a })
-- | Additional information for launching instances.
siLaunchSpecification :: Lens' SpotInstanceRequest (Maybe LaunchSpecification)
siLaunchSpecification =
lens _siLaunchSpecification (\s a -> s { _siLaunchSpecification = a })
-- | The Availability Zone in which the bid is launched.
siLaunchedAvailabilityZone :: Lens' SpotInstanceRequest (Maybe Text)
siLaunchedAvailabilityZone =
lens _siLaunchedAvailabilityZone
(\s a -> s { _siLaunchedAvailabilityZone = a })
-- | The product description associated with the Spot Instance.
siProductDescription :: Lens' SpotInstanceRequest (Maybe RIProductDescription)
siProductDescription =
lens _siProductDescription (\s a -> s { _siProductDescription = a })
-- | The ID of the Spot Instance request.
siSpotInstanceRequestId :: Lens' SpotInstanceRequest (Maybe Text)
siSpotInstanceRequestId =
lens _siSpotInstanceRequestId (\s a -> s { _siSpotInstanceRequestId = a })
-- | The maximum hourly price (bid) for any Spot Instance launched to fulfill the
-- request.
siSpotPrice :: Lens' SpotInstanceRequest (Maybe Text)
siSpotPrice = lens _siSpotPrice (\s a -> s { _siSpotPrice = a })
-- | The state of the Spot Instance request. Spot bid status information can help
-- you track your Spot Instance requests. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html Spot BidStatus> in the /Amazon Elastic Compute Cloud User Guide for Linux/.
siState :: Lens' SpotInstanceRequest (Maybe SpotInstanceState)
siState = lens _siState (\s a -> s { _siState = a })
-- | The status code and status message describing the Spot Instance request.
siStatus :: Lens' SpotInstanceRequest (Maybe SpotInstanceStatus)
siStatus = lens _siStatus (\s a -> s { _siStatus = a })
-- | Any tags assigned to the resource.
siTags :: Lens' SpotInstanceRequest [Tag]
siTags = lens _siTags (\s a -> s { _siTags = a }) . _List
-- | The Spot Instance request type.
siType :: Lens' SpotInstanceRequest (Maybe SpotInstanceType)
siType = lens _siType (\s a -> s { _siType = a })
-- | The start date of the request. If this is a one-time request, the request
-- becomes active at this date and time and remains active until all instances
-- launch, the request expires, or the request is canceled. If the request is
-- persistent, the request becomes active at this date and time and remains
-- active until it expires or is canceled.
siValidFrom :: Lens' SpotInstanceRequest (Maybe UTCTime)
siValidFrom = lens _siValidFrom (\s a -> s { _siValidFrom = a }) . mapping _Time
-- | The end date of the request. If this is a one-time request, the request
-- remains active until all instances launch, the request is canceled, or this
-- date is reached. If the request is persistent, it remains active until it is
-- canceled or this date is reached.
siValidUntil :: Lens' SpotInstanceRequest (Maybe UTCTime)
siValidUntil = lens _siValidUntil (\s a -> s { _siValidUntil = a }) . mapping _Time
instance FromXML SpotInstanceRequest where
parseXML x = SpotInstanceRequest
<$> x .@? "availabilityZoneGroup"
<*> x .@? "createTime"
<*> x .@? "fault"
<*> x .@? "instanceId"
<*> x .@? "launchGroup"
<*> x .@? "launchSpecification"
<*> x .@? "launchedAvailabilityZone"
<*> x .@? "productDescription"
<*> x .@? "spotInstanceRequestId"
<*> x .@? "spotPrice"
<*> x .@? "state"
<*> x .@? "status"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "type"
<*> x .@? "validFrom"
<*> x .@? "validUntil"
instance ToQuery SpotInstanceRequest where
toQuery SpotInstanceRequest{..} = mconcat
[ "AvailabilityZoneGroup" =? _siAvailabilityZoneGroup
, "CreateTime" =? _siCreateTime
, "Fault" =? _siFault
, "InstanceId" =? _siInstanceId
, "LaunchGroup" =? _siLaunchGroup
, "LaunchSpecification" =? _siLaunchSpecification
, "LaunchedAvailabilityZone" =? _siLaunchedAvailabilityZone
, "ProductDescription" =? _siProductDescription
, "SpotInstanceRequestId" =? _siSpotInstanceRequestId
, "SpotPrice" =? _siSpotPrice
, "State" =? _siState
, "Status" =? _siStatus
, "TagSet" `toQueryList` _siTags
, "Type" =? _siType
, "ValidFrom" =? _siValidFrom
, "ValidUntil" =? _siValidUntil
]
data LaunchSpecification = LaunchSpecification
{ _lsAddressingType :: Maybe Text
, _lsBlockDeviceMappings :: List "item" BlockDeviceMapping
, _lsEbsOptimized :: Maybe Bool
, _lsIamInstanceProfile :: Maybe IamInstanceProfileSpecification
, _lsImageId :: Maybe Text
, _lsInstanceType :: Maybe InstanceType
, _lsKernelId :: Maybe Text
, _lsKeyName :: Maybe Text
, _lsMonitoring :: Maybe RunInstancesMonitoringEnabled
, _lsNetworkInterfaces :: List "item" InstanceNetworkInterfaceSpecification
, _lsPlacement :: Maybe SpotPlacement
, _lsRamdiskId :: Maybe Text
, _lsSecurityGroups :: List "item" GroupIdentifier
, _lsSubnetId :: Maybe Text
, _lsUserData :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'LaunchSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsAddressingType' @::@ 'Maybe' 'Text'
--
-- * 'lsBlockDeviceMappings' @::@ ['BlockDeviceMapping']
--
-- * 'lsEbsOptimized' @::@ 'Maybe' 'Bool'
--
-- * 'lsIamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfileSpecification'
--
-- * 'lsImageId' @::@ 'Maybe' 'Text'
--
-- * 'lsInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'lsKernelId' @::@ 'Maybe' 'Text'
--
-- * 'lsKeyName' @::@ 'Maybe' 'Text'
--
-- * 'lsMonitoring' @::@ 'Maybe' 'RunInstancesMonitoringEnabled'
--
-- * 'lsNetworkInterfaces' @::@ ['InstanceNetworkInterfaceSpecification']
--
-- * 'lsPlacement' @::@ 'Maybe' 'SpotPlacement'
--
-- * 'lsRamdiskId' @::@ 'Maybe' 'Text'
--
-- * 'lsSecurityGroups' @::@ ['GroupIdentifier']
--
-- * 'lsSubnetId' @::@ 'Maybe' 'Text'
--
-- * 'lsUserData' @::@ 'Maybe' 'Text'
--
launchSpecification :: LaunchSpecification
launchSpecification = LaunchSpecification
{ _lsImageId = Nothing
, _lsKeyName = Nothing
, _lsSecurityGroups = mempty
, _lsUserData = Nothing
, _lsAddressingType = Nothing
, _lsInstanceType = Nothing
, _lsPlacement = Nothing
, _lsKernelId = Nothing
, _lsRamdiskId = Nothing
, _lsBlockDeviceMappings = mempty
, _lsSubnetId = Nothing
, _lsNetworkInterfaces = mempty
, _lsIamInstanceProfile = Nothing
, _lsEbsOptimized = Nothing
, _lsMonitoring = Nothing
}
-- | Deprecated.
lsAddressingType :: Lens' LaunchSpecification (Maybe Text)
lsAddressingType = lens _lsAddressingType (\s a -> s { _lsAddressingType = a })
-- | One or more block device mapping entries.
lsBlockDeviceMappings :: Lens' LaunchSpecification [BlockDeviceMapping]
lsBlockDeviceMappings =
lens _lsBlockDeviceMappings (\s a -> s { _lsBlockDeviceMappings = a })
. _List
-- | Indicates whether the instance is optimized for EBS I/O. This optimization
-- provides dedicated throughput to Amazon EBS and an optimized configuration
-- stack to provide optimal EBS I/O performance. This optimization isn't
-- available with all instance types. Additional usage charges apply when using
-- an EBS Optimized instance.
--
-- Default: 'false'
lsEbsOptimized :: Lens' LaunchSpecification (Maybe Bool)
lsEbsOptimized = lens _lsEbsOptimized (\s a -> s { _lsEbsOptimized = a })
-- | The IAM instance profile.
lsIamInstanceProfile :: Lens' LaunchSpecification (Maybe IamInstanceProfileSpecification)
lsIamInstanceProfile =
lens _lsIamInstanceProfile (\s a -> s { _lsIamInstanceProfile = a })
-- | The ID of the AMI.
lsImageId :: Lens' LaunchSpecification (Maybe Text)
lsImageId = lens _lsImageId (\s a -> s { _lsImageId = a })
-- | The instance type.
lsInstanceType :: Lens' LaunchSpecification (Maybe InstanceType)
lsInstanceType = lens _lsInstanceType (\s a -> s { _lsInstanceType = a })
-- | The ID of the kernel.
lsKernelId :: Lens' LaunchSpecification (Maybe Text)
lsKernelId = lens _lsKernelId (\s a -> s { _lsKernelId = a })
-- | The name of the key pair.
lsKeyName :: Lens' LaunchSpecification (Maybe Text)
lsKeyName = lens _lsKeyName (\s a -> s { _lsKeyName = a })
lsMonitoring :: Lens' LaunchSpecification (Maybe RunInstancesMonitoringEnabled)
lsMonitoring = lens _lsMonitoring (\s a -> s { _lsMonitoring = a })
-- | One or more network interfaces.
lsNetworkInterfaces :: Lens' LaunchSpecification [InstanceNetworkInterfaceSpecification]
lsNetworkInterfaces =
lens _lsNetworkInterfaces (\s a -> s { _lsNetworkInterfaces = a })
. _List
-- | The placement information for the instance.
lsPlacement :: Lens' LaunchSpecification (Maybe SpotPlacement)
lsPlacement = lens _lsPlacement (\s a -> s { _lsPlacement = a })
-- | The ID of the RAM disk.
lsRamdiskId :: Lens' LaunchSpecification (Maybe Text)
lsRamdiskId = lens _lsRamdiskId (\s a -> s { _lsRamdiskId = a })
-- | One or more security groups. To request an instance in a nondefault VPC, you
-- must specify the ID of the security group. To request an instance in
-- EC2-Classic or a default VPC, you can specify the name or the ID of the
-- security group.
lsSecurityGroups :: Lens' LaunchSpecification [GroupIdentifier]
lsSecurityGroups = lens _lsSecurityGroups (\s a -> s { _lsSecurityGroups = a }) . _List
-- | The ID of the subnet in which to launch the instance.
lsSubnetId :: Lens' LaunchSpecification (Maybe Text)
lsSubnetId = lens _lsSubnetId (\s a -> s { _lsSubnetId = a })
-- | The Base64-encoded MIME user data to make available to the instances.
lsUserData :: Lens' LaunchSpecification (Maybe Text)
lsUserData = lens _lsUserData (\s a -> s { _lsUserData = a })
instance FromXML LaunchSpecification where
parseXML x = LaunchSpecification
<$> x .@? "addressingType"
<*> x .@? "blockDeviceMapping" .!@ mempty
<*> x .@? "ebsOptimized"
<*> x .@? "iamInstanceProfile"
<*> x .@? "imageId"
<*> x .@? "instanceType"
<*> x .@? "kernelId"
<*> x .@? "keyName"
<*> x .@? "monitoring"
<*> x .@? "networkInterfaceSet" .!@ mempty
<*> x .@? "placement"
<*> x .@? "ramdiskId"
<*> x .@? "groupSet" .!@ mempty
<*> x .@? "subnetId"
<*> x .@? "userData"
instance ToQuery LaunchSpecification where
toQuery LaunchSpecification{..} = mconcat
[ "AddressingType" =? _lsAddressingType
, "BlockDeviceMapping" `toQueryList` _lsBlockDeviceMappings
, "EbsOptimized" =? _lsEbsOptimized
, "IamInstanceProfile" =? _lsIamInstanceProfile
, "ImageId" =? _lsImageId
, "InstanceType" =? _lsInstanceType
, "KernelId" =? _lsKernelId
, "KeyName" =? _lsKeyName
, "Monitoring" =? _lsMonitoring
, "NetworkInterfaceSet" `toQueryList` _lsNetworkInterfaces
, "Placement" =? _lsPlacement
, "RamdiskId" =? _lsRamdiskId
, "GroupSet" `toQueryList` _lsSecurityGroups
, "SubnetId" =? _lsSubnetId
, "UserData" =? _lsUserData
]
data VolumeStatusEvent = VolumeStatusEvent
{ _vseDescription :: Maybe Text
, _vseEventId :: Maybe Text
, _vseEventType :: Maybe Text
, _vseNotAfter :: Maybe ISO8601
, _vseNotBefore :: Maybe ISO8601
} deriving (Eq, Ord, Read, Show)
-- | 'VolumeStatusEvent' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vseDescription' @::@ 'Maybe' 'Text'
--
-- * 'vseEventId' @::@ 'Maybe' 'Text'
--
-- * 'vseEventType' @::@ 'Maybe' 'Text'
--
-- * 'vseNotAfter' @::@ 'Maybe' 'UTCTime'
--
-- * 'vseNotBefore' @::@ 'Maybe' 'UTCTime'
--
volumeStatusEvent :: VolumeStatusEvent
volumeStatusEvent = VolumeStatusEvent
{ _vseEventType = Nothing
, _vseDescription = Nothing
, _vseNotBefore = Nothing
, _vseNotAfter = Nothing
, _vseEventId = Nothing
}
-- | A description of the event.
vseDescription :: Lens' VolumeStatusEvent (Maybe Text)
vseDescription = lens _vseDescription (\s a -> s { _vseDescription = a })
-- | The ID of this event.
vseEventId :: Lens' VolumeStatusEvent (Maybe Text)
vseEventId = lens _vseEventId (\s a -> s { _vseEventId = a })
-- | The type of this event.
vseEventType :: Lens' VolumeStatusEvent (Maybe Text)
vseEventType = lens _vseEventType (\s a -> s { _vseEventType = a })
-- | The latest end time of the event.
vseNotAfter :: Lens' VolumeStatusEvent (Maybe UTCTime)
vseNotAfter = lens _vseNotAfter (\s a -> s { _vseNotAfter = a }) . mapping _Time
-- | The earliest start time of the event.
vseNotBefore :: Lens' VolumeStatusEvent (Maybe UTCTime)
vseNotBefore = lens _vseNotBefore (\s a -> s { _vseNotBefore = a }) . mapping _Time
instance FromXML VolumeStatusEvent where
parseXML x = VolumeStatusEvent
<$> x .@? "description"
<*> x .@? "eventId"
<*> x .@? "eventType"
<*> x .@? "notAfter"
<*> x .@? "notBefore"
instance ToQuery VolumeStatusEvent where
toQuery VolumeStatusEvent{..} = mconcat
[ "Description" =? _vseDescription
, "EventId" =? _vseEventId
, "EventType" =? _vseEventType
, "NotAfter" =? _vseNotAfter
, "NotBefore" =? _vseNotBefore
]
data Volume = Volume
{ _vAttachments :: List "item" VolumeAttachment
, _vAvailabilityZone :: Text
, _vCreateTime :: ISO8601
, _vEncrypted :: Bool
, _vIops :: Maybe Int
, _vKmsKeyId :: Maybe Text
, _vSize :: Int
, _vSnapshotId :: Text
, _vState :: VolumeState
, _vTags :: List "item" Tag
, _vVolumeId :: Text
, _vVolumeType :: VolumeType
} deriving (Eq, Read, Show)
-- | 'Volume' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vAttachments' @::@ ['VolumeAttachment']
--
-- * 'vAvailabilityZone' @::@ 'Text'
--
-- * 'vCreateTime' @::@ 'UTCTime'
--
-- * 'vEncrypted' @::@ 'Bool'
--
-- * 'vIops' @::@ 'Maybe' 'Int'
--
-- * 'vKmsKeyId' @::@ 'Maybe' 'Text'
--
-- * 'vSize' @::@ 'Int'
--
-- * 'vSnapshotId' @::@ 'Text'
--
-- * 'vState' @::@ 'VolumeState'
--
-- * 'vTags' @::@ ['Tag']
--
-- * 'vVolumeId' @::@ 'Text'
--
-- * 'vVolumeType' @::@ 'VolumeType'
--
volume :: Text -- ^ 'vVolumeId'
-> Int -- ^ 'vSize'
-> Text -- ^ 'vSnapshotId'
-> Text -- ^ 'vAvailabilityZone'
-> VolumeState -- ^ 'vState'
-> UTCTime -- ^ 'vCreateTime'
-> VolumeType -- ^ 'vVolumeType'
-> Bool -- ^ 'vEncrypted'
-> Volume
volume p1 p2 p3 p4 p5 p6 p7 p8 = Volume
{ _vVolumeId = p1
, _vSize = p2
, _vSnapshotId = p3
, _vAvailabilityZone = p4
, _vState = p5
, _vCreateTime = withIso _Time (const id) p6
, _vVolumeType = p7
, _vEncrypted = p8
, _vAttachments = mempty
, _vTags = mempty
, _vIops = Nothing
, _vKmsKeyId = Nothing
}
vAttachments :: Lens' Volume [VolumeAttachment]
vAttachments = lens _vAttachments (\s a -> s { _vAttachments = a }) . _List
-- | The Availability Zone for the volume.
vAvailabilityZone :: Lens' Volume Text
vAvailabilityZone =
lens _vAvailabilityZone (\s a -> s { _vAvailabilityZone = a })
-- | The time stamp when volume creation was initiated.
vCreateTime :: Lens' Volume UTCTime
vCreateTime = lens _vCreateTime (\s a -> s { _vCreateTime = a }) . _Time
-- | Indicates whether the volume will be encrypted.
vEncrypted :: Lens' Volume Bool
vEncrypted = lens _vEncrypted (\s a -> s { _vEncrypted = a })
-- | The number of I/O operations per second (IOPS) that the volume supports. For
-- Provisioned IOPS (SSD) volumes, this represents the number of IOPS that are
-- provisioned for the volume. For General Purpose (SSD) volumes, this
-- represents the baseline performance of the volume and the rate at which the
-- volume accumulates I/O credits for bursting. For more information on General
-- Purpose (SSD) baseline performance, I/O credits, and bursting, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html Amazon EBSVolume Types> in the /Amazon Elastic Compute Cloud User Guide for Linux/.
--
-- Constraint: Range is 100 to 20000 for Provisioned IOPS (SSD) volumes and 3
-- to 10000 for General Purpose (SSD) volumes.
--
-- Condition: This parameter is required for requests to create 'io1' volumes; it
-- is not used in requests to create 'standard' or 'gp2' volumes.
vIops :: Lens' Volume (Maybe Int)
vIops = lens _vIops (\s a -> s { _vIops = a })
-- | The full ARN of the AWS Key Management Service (KMS) master key that was used
-- to protect the volume encryption key for the volume.
vKmsKeyId :: Lens' Volume (Maybe Text)
vKmsKeyId = lens _vKmsKeyId (\s a -> s { _vKmsKeyId = a })
-- | The size of the volume, in GiBs.
vSize :: Lens' Volume Int
vSize = lens _vSize (\s a -> s { _vSize = a })
-- | The snapshot from which the volume was created, if applicable.
vSnapshotId :: Lens' Volume Text
vSnapshotId = lens _vSnapshotId (\s a -> s { _vSnapshotId = a })
-- | The volume state.
vState :: Lens' Volume VolumeState
vState = lens _vState (\s a -> s { _vState = a })
-- | Any tags assigned to the volume.
vTags :: Lens' Volume [Tag]
vTags = lens _vTags (\s a -> s { _vTags = a }) . _List
-- | The ID of the volume.
vVolumeId :: Lens' Volume Text
vVolumeId = lens _vVolumeId (\s a -> s { _vVolumeId = a })
-- | The volume type. This can be 'gp2' for General Purpose (SSD) volumes, 'io1' for
-- Provisioned IOPS (SSD) volumes, or 'standard' for Magnetic volumes.
vVolumeType :: Lens' Volume VolumeType
vVolumeType = lens _vVolumeType (\s a -> s { _vVolumeType = a })
instance FromXML Volume where
parseXML x = Volume
<$> x .@? "attachmentSet" .!@ mempty
<*> x .@ "availabilityZone"
<*> x .@ "createTime"
<*> x .@ "encrypted"
<*> x .@? "iops"
<*> x .@? "kmsKeyId"
<*> x .@ "size"
<*> x .@ "snapshotId"
<*> x .@ "status"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "volumeId"
<*> x .@ "volumeType"
instance ToQuery Volume where
toQuery Volume{..} = mconcat
[ "AttachmentSet" `toQueryList` _vAttachments
, "AvailabilityZone" =? _vAvailabilityZone
, "CreateTime" =? _vCreateTime
, "Encrypted" =? _vEncrypted
, "Iops" =? _vIops
, "KmsKeyId" =? _vKmsKeyId
, "Size" =? _vSize
, "SnapshotId" =? _vSnapshotId
, "Status" =? _vState
, "TagSet" `toQueryList` _vTags
, "VolumeId" =? _vVolumeId
, "VolumeType" =? _vVolumeType
]
data Reservation = Reservation
{ _rGroups :: List "item" GroupIdentifier
, _rInstances :: List "item" Instance
, _rOwnerId :: Text
, _rRequesterId :: Maybe Text
, _rReservationId :: Text
} deriving (Eq, Read, Show)
-- | 'Reservation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rGroups' @::@ ['GroupIdentifier']
--
-- * 'rInstances' @::@ ['Instance']
--
-- * 'rOwnerId' @::@ 'Text'
--
-- * 'rRequesterId' @::@ 'Maybe' 'Text'
--
-- * 'rReservationId' @::@ 'Text'
--
reservation :: Text -- ^ 'rReservationId'
-> Text -- ^ 'rOwnerId'
-> Reservation
reservation p1 p2 = Reservation
{ _rReservationId = p1
, _rOwnerId = p2
, _rRequesterId = Nothing
, _rGroups = mempty
, _rInstances = mempty
}
-- | One or more security groups.
rGroups :: Lens' Reservation [GroupIdentifier]
rGroups = lens _rGroups (\s a -> s { _rGroups = a }) . _List
-- | One or more instances.
rInstances :: Lens' Reservation [Instance]
rInstances = lens _rInstances (\s a -> s { _rInstances = a }) . _List
-- | The ID of the AWS account that owns the reservation.
rOwnerId :: Lens' Reservation Text
rOwnerId = lens _rOwnerId (\s a -> s { _rOwnerId = a })
-- | The ID of the requester that launched the instances on your behalf (for
-- example, AWS Management Console or Auto Scaling).
rRequesterId :: Lens' Reservation (Maybe Text)
rRequesterId = lens _rRequesterId (\s a -> s { _rRequesterId = a })
-- | The ID of the reservation.
rReservationId :: Lens' Reservation Text
rReservationId = lens _rReservationId (\s a -> s { _rReservationId = a })
instance FromXML Reservation where
parseXML x = Reservation
<$> x .@? "groupSet" .!@ mempty
<*> x .@? "instancesSet" .!@ mempty
<*> x .@ "ownerId"
<*> x .@? "requesterId"
<*> x .@ "reservationId"
instance ToQuery Reservation where
toQuery Reservation{..} = mconcat
[ "GroupSet" `toQueryList` _rGroups
, "InstancesSet" `toQueryList` _rInstances
, "OwnerId" =? _rOwnerId
, "RequesterId" =? _rRequesterId
, "ReservationId" =? _rReservationId
]
data ImportInstanceVolumeDetailItem = ImportInstanceVolumeDetailItem
{ _iivdiAvailabilityZone :: Text
, _iivdiBytesConverted :: Integer
, _iivdiDescription :: Maybe Text
, _iivdiImage :: DiskImageDescription
, _iivdiStatus :: Text
, _iivdiStatusMessage :: Maybe Text
, _iivdiVolume :: DiskImageVolumeDescription
} deriving (Eq, Read, Show)
-- | 'ImportInstanceVolumeDetailItem' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iivdiAvailabilityZone' @::@ 'Text'
--
-- * 'iivdiBytesConverted' @::@ 'Integer'
--
-- * 'iivdiDescription' @::@ 'Maybe' 'Text'
--
-- * 'iivdiImage' @::@ 'DiskImageDescription'
--
-- * 'iivdiStatus' @::@ 'Text'
--
-- * 'iivdiStatusMessage' @::@ 'Maybe' 'Text'
--
-- * 'iivdiVolume' @::@ 'DiskImageVolumeDescription'
--
importInstanceVolumeDetailItem :: Integer -- ^ 'iivdiBytesConverted'
-> Text -- ^ 'iivdiAvailabilityZone'
-> DiskImageDescription -- ^ 'iivdiImage'
-> DiskImageVolumeDescription -- ^ 'iivdiVolume'
-> Text -- ^ 'iivdiStatus'
-> ImportInstanceVolumeDetailItem
importInstanceVolumeDetailItem p1 p2 p3 p4 p5 = ImportInstanceVolumeDetailItem
{ _iivdiBytesConverted = p1
, _iivdiAvailabilityZone = p2
, _iivdiImage = p3
, _iivdiVolume = p4
, _iivdiStatus = p5
, _iivdiStatusMessage = Nothing
, _iivdiDescription = Nothing
}
-- | The Availability Zone where the resulting instance will reside.
iivdiAvailabilityZone :: Lens' ImportInstanceVolumeDetailItem Text
iivdiAvailabilityZone =
lens _iivdiAvailabilityZone (\s a -> s { _iivdiAvailabilityZone = a })
-- | The number of bytes converted so far.
iivdiBytesConverted :: Lens' ImportInstanceVolumeDetailItem Integer
iivdiBytesConverted =
lens _iivdiBytesConverted (\s a -> s { _iivdiBytesConverted = a })
iivdiDescription :: Lens' ImportInstanceVolumeDetailItem (Maybe Text)
iivdiDescription = lens _iivdiDescription (\s a -> s { _iivdiDescription = a })
-- | The image.
iivdiImage :: Lens' ImportInstanceVolumeDetailItem DiskImageDescription
iivdiImage = lens _iivdiImage (\s a -> s { _iivdiImage = a })
-- | The status of the import of this particular disk image.
iivdiStatus :: Lens' ImportInstanceVolumeDetailItem Text
iivdiStatus = lens _iivdiStatus (\s a -> s { _iivdiStatus = a })
-- | The status information or errors related to the disk image.
iivdiStatusMessage :: Lens' ImportInstanceVolumeDetailItem (Maybe Text)
iivdiStatusMessage =
lens _iivdiStatusMessage (\s a -> s { _iivdiStatusMessage = a })
-- | The volume.
iivdiVolume :: Lens' ImportInstanceVolumeDetailItem DiskImageVolumeDescription
iivdiVolume = lens _iivdiVolume (\s a -> s { _iivdiVolume = a })
instance FromXML ImportInstanceVolumeDetailItem where
parseXML x = ImportInstanceVolumeDetailItem
<$> x .@ "availabilityZone"
<*> x .@ "bytesConverted"
<*> x .@? "description"
<*> x .@ "image"
<*> x .@ "status"
<*> x .@? "statusMessage"
<*> x .@ "volume"
instance ToQuery ImportInstanceVolumeDetailItem where
toQuery ImportInstanceVolumeDetailItem{..} = mconcat
[ "AvailabilityZone" =? _iivdiAvailabilityZone
, "BytesConverted" =? _iivdiBytesConverted
, "Description" =? _iivdiDescription
, "Image" =? _iivdiImage
, "Status" =? _iivdiStatus
, "StatusMessage" =? _iivdiStatusMessage
, "Volume" =? _iivdiVolume
]
data SummaryStatus
= SSImpaired -- ^ impaired
| SSInsufficientData -- ^ insufficient-data
| SSNotApplicable -- ^ not-applicable
| SSOk -- ^ ok
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SummaryStatus
instance FromText SummaryStatus where
parser = takeLowerText >>= \case
"impaired" -> pure SSImpaired
"insufficient-data" -> pure SSInsufficientData
"not-applicable" -> pure SSNotApplicable
"ok" -> pure SSOk
e -> fail $
"Failure parsing SummaryStatus from " ++ show e
instance ToText SummaryStatus where
toText = \case
SSImpaired -> "impaired"
SSInsufficientData -> "insufficient-data"
SSNotApplicable -> "not-applicable"
SSOk -> "ok"
instance ToByteString SummaryStatus
instance ToHeader SummaryStatus
instance ToQuery SummaryStatus
instance FromXML SummaryStatus where
parseXML = parseXMLText "SummaryStatus"
data ReservedInstancesModification = ReservedInstancesModification
{ _rimClientToken :: Maybe Text
, _rimCreateDate :: Maybe ISO8601
, _rimEffectiveDate :: Maybe ISO8601
, _rimModificationResults :: List "item" ReservedInstancesModificationResult
, _rimReservedInstancesIds :: List "item" ReservedInstancesId
, _rimReservedInstancesModificationId :: Maybe Text
, _rimStatus :: Maybe Text
, _rimStatusMessage :: Maybe Text
, _rimUpdateDate :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'ReservedInstancesModification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rimClientToken' @::@ 'Maybe' 'Text'
--
-- * 'rimCreateDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'rimEffectiveDate' @::@ 'Maybe' 'UTCTime'
--
-- * 'rimModificationResults' @::@ ['ReservedInstancesModificationResult']
--
-- * 'rimReservedInstancesIds' @::@ ['ReservedInstancesId']
--
-- * 'rimReservedInstancesModificationId' @::@ 'Maybe' 'Text'
--
-- * 'rimStatus' @::@ 'Maybe' 'Text'
--
-- * 'rimStatusMessage' @::@ 'Maybe' 'Text'
--
-- * 'rimUpdateDate' @::@ 'Maybe' 'UTCTime'
--
reservedInstancesModification :: ReservedInstancesModification
reservedInstancesModification = ReservedInstancesModification
{ _rimReservedInstancesModificationId = Nothing
, _rimReservedInstancesIds = mempty
, _rimModificationResults = mempty
, _rimCreateDate = Nothing
, _rimUpdateDate = Nothing
, _rimEffectiveDate = Nothing
, _rimStatus = Nothing
, _rimStatusMessage = Nothing
, _rimClientToken = Nothing
}
-- | A unique, case-sensitive key supplied by the client to ensure that the
-- request is idempotent. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html Ensuring Idempotency>.
rimClientToken :: Lens' ReservedInstancesModification (Maybe Text)
rimClientToken = lens _rimClientToken (\s a -> s { _rimClientToken = a })
-- | The time when the modification request was created.
rimCreateDate :: Lens' ReservedInstancesModification (Maybe UTCTime)
rimCreateDate = lens _rimCreateDate (\s a -> s { _rimCreateDate = a }) . mapping _Time
-- | The time for the modification to become effective.
rimEffectiveDate :: Lens' ReservedInstancesModification (Maybe UTCTime)
rimEffectiveDate = lens _rimEffectiveDate (\s a -> s { _rimEffectiveDate = a }) . mapping _Time
-- | Contains target configurations along with their corresponding new Reserved
-- Instance IDs.
rimModificationResults :: Lens' ReservedInstancesModification [ReservedInstancesModificationResult]
rimModificationResults =
lens _rimModificationResults (\s a -> s { _rimModificationResults = a })
. _List
-- | The IDs of one or more Reserved Instances.
rimReservedInstancesIds :: Lens' ReservedInstancesModification [ReservedInstancesId]
rimReservedInstancesIds =
lens _rimReservedInstancesIds (\s a -> s { _rimReservedInstancesIds = a })
. _List
-- | A unique ID for the Reserved Instance modification.
rimReservedInstancesModificationId :: Lens' ReservedInstancesModification (Maybe Text)
rimReservedInstancesModificationId =
lens _rimReservedInstancesModificationId
(\s a -> s { _rimReservedInstancesModificationId = a })
-- | The status of the Reserved Instances modification request.
rimStatus :: Lens' ReservedInstancesModification (Maybe Text)
rimStatus = lens _rimStatus (\s a -> s { _rimStatus = a })
-- | The reason for the status.
rimStatusMessage :: Lens' ReservedInstancesModification (Maybe Text)
rimStatusMessage = lens _rimStatusMessage (\s a -> s { _rimStatusMessage = a })
-- | The time when the modification request was last updated.
rimUpdateDate :: Lens' ReservedInstancesModification (Maybe UTCTime)
rimUpdateDate = lens _rimUpdateDate (\s a -> s { _rimUpdateDate = a }) . mapping _Time
instance FromXML ReservedInstancesModification where
parseXML x = ReservedInstancesModification
<$> x .@? "clientToken"
<*> x .@? "createDate"
<*> x .@? "effectiveDate"
<*> x .@? "modificationResultSet" .!@ mempty
<*> x .@? "reservedInstancesSet" .!@ mempty
<*> x .@? "reservedInstancesModificationId"
<*> x .@? "status"
<*> x .@? "statusMessage"
<*> x .@? "updateDate"
instance ToQuery ReservedInstancesModification where
toQuery ReservedInstancesModification{..} = mconcat
[ "ClientToken" =? _rimClientToken
, "CreateDate" =? _rimCreateDate
, "EffectiveDate" =? _rimEffectiveDate
, "ModificationResultSet" `toQueryList` _rimModificationResults
, "ReservedInstancesSet" `toQueryList` _rimReservedInstancesIds
, "ReservedInstancesModificationId" =? _rimReservedInstancesModificationId
, "Status" =? _rimStatus
, "StatusMessage" =? _rimStatusMessage
, "UpdateDate" =? _rimUpdateDate
]
data RuleAction
= Allow -- ^ allow
| Deny -- ^ deny
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable RuleAction
instance FromText RuleAction where
parser = takeLowerText >>= \case
"allow" -> pure Allow
"deny" -> pure Deny
e -> fail $
"Failure parsing RuleAction from " ++ show e
instance ToText RuleAction where
toText = \case
Allow -> "allow"
Deny -> "deny"
instance ToByteString RuleAction
instance ToHeader RuleAction
instance ToQuery RuleAction
instance FromXML RuleAction where
parseXML = parseXMLText "RuleAction"
data NetworkInterface = NetworkInterface
{ _niAssociation :: Maybe NetworkInterfaceAssociation
, _niAttachment :: Maybe NetworkInterfaceAttachment
, _niAvailabilityZone :: Maybe Text
, _niDescription :: Maybe Text
, _niGroups :: List "item" GroupIdentifier
, _niMacAddress :: Maybe Text
, _niNetworkInterfaceId :: Maybe Text
, _niOwnerId :: Maybe Text
, _niPrivateDnsName :: Maybe Text
, _niPrivateIpAddress :: Maybe Text
, _niPrivateIpAddresses :: List "item" NetworkInterfacePrivateIpAddress
, _niRequesterId :: Maybe Text
, _niRequesterManaged :: Maybe Bool
, _niSourceDestCheck :: Maybe Bool
, _niStatus :: Maybe NetworkInterfaceStatus
, _niSubnetId :: Maybe Text
, _niTagSet :: List "item" Tag
, _niVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'NetworkInterface' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'niAssociation' @::@ 'Maybe' 'NetworkInterfaceAssociation'
--
-- * 'niAttachment' @::@ 'Maybe' 'NetworkInterfaceAttachment'
--
-- * 'niAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'niDescription' @::@ 'Maybe' 'Text'
--
-- * 'niGroups' @::@ ['GroupIdentifier']
--
-- * 'niMacAddress' @::@ 'Maybe' 'Text'
--
-- * 'niNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'niOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'niPrivateDnsName' @::@ 'Maybe' 'Text'
--
-- * 'niPrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'niPrivateIpAddresses' @::@ ['NetworkInterfacePrivateIpAddress']
--
-- * 'niRequesterId' @::@ 'Maybe' 'Text'
--
-- * 'niRequesterManaged' @::@ 'Maybe' 'Bool'
--
-- * 'niSourceDestCheck' @::@ 'Maybe' 'Bool'
--
-- * 'niStatus' @::@ 'Maybe' 'NetworkInterfaceStatus'
--
-- * 'niSubnetId' @::@ 'Maybe' 'Text'
--
-- * 'niTagSet' @::@ ['Tag']
--
-- * 'niVpcId' @::@ 'Maybe' 'Text'
--
networkInterface :: NetworkInterface
networkInterface = NetworkInterface
{ _niNetworkInterfaceId = Nothing
, _niSubnetId = Nothing
, _niVpcId = Nothing
, _niAvailabilityZone = Nothing
, _niDescription = Nothing
, _niOwnerId = Nothing
, _niRequesterId = Nothing
, _niRequesterManaged = Nothing
, _niStatus = Nothing
, _niMacAddress = Nothing
, _niPrivateIpAddress = Nothing
, _niPrivateDnsName = Nothing
, _niSourceDestCheck = Nothing
, _niGroups = mempty
, _niAttachment = Nothing
, _niAssociation = Nothing
, _niTagSet = mempty
, _niPrivateIpAddresses = mempty
}
-- | The association information for an Elastic IP associated with the network
-- interface.
niAssociation :: Lens' NetworkInterface (Maybe NetworkInterfaceAssociation)
niAssociation = lens _niAssociation (\s a -> s { _niAssociation = a })
-- | The network interface attachment.
niAttachment :: Lens' NetworkInterface (Maybe NetworkInterfaceAttachment)
niAttachment = lens _niAttachment (\s a -> s { _niAttachment = a })
-- | The Availability Zone.
niAvailabilityZone :: Lens' NetworkInterface (Maybe Text)
niAvailabilityZone =
lens _niAvailabilityZone (\s a -> s { _niAvailabilityZone = a })
-- | A description.
niDescription :: Lens' NetworkInterface (Maybe Text)
niDescription = lens _niDescription (\s a -> s { _niDescription = a })
-- | Any security groups for the network interface.
niGroups :: Lens' NetworkInterface [GroupIdentifier]
niGroups = lens _niGroups (\s a -> s { _niGroups = a }) . _List
-- | The MAC address.
niMacAddress :: Lens' NetworkInterface (Maybe Text)
niMacAddress = lens _niMacAddress (\s a -> s { _niMacAddress = a })
-- | The ID of the network interface.
niNetworkInterfaceId :: Lens' NetworkInterface (Maybe Text)
niNetworkInterfaceId =
lens _niNetworkInterfaceId (\s a -> s { _niNetworkInterfaceId = a })
-- | The AWS account ID of the owner of the network interface.
niOwnerId :: Lens' NetworkInterface (Maybe Text)
niOwnerId = lens _niOwnerId (\s a -> s { _niOwnerId = a })
-- | The private DNS name.
niPrivateDnsName :: Lens' NetworkInterface (Maybe Text)
niPrivateDnsName = lens _niPrivateDnsName (\s a -> s { _niPrivateDnsName = a })
-- | The IP address of the network interface within the subnet.
niPrivateIpAddress :: Lens' NetworkInterface (Maybe Text)
niPrivateIpAddress =
lens _niPrivateIpAddress (\s a -> s { _niPrivateIpAddress = a })
-- | The private IP addresses associated with the network interface.
niPrivateIpAddresses :: Lens' NetworkInterface [NetworkInterfacePrivateIpAddress]
niPrivateIpAddresses =
lens _niPrivateIpAddresses (\s a -> s { _niPrivateIpAddresses = a })
. _List
-- | The ID of the entity that launched the instance on your behalf (for example,
-- AWS Management Console or Auto Scaling).
niRequesterId :: Lens' NetworkInterface (Maybe Text)
niRequesterId = lens _niRequesterId (\s a -> s { _niRequesterId = a })
-- | Indicates whether the network interface is being managed by AWS.
niRequesterManaged :: Lens' NetworkInterface (Maybe Bool)
niRequesterManaged =
lens _niRequesterManaged (\s a -> s { _niRequesterManaged = a })
-- | Indicates whether traffic to or from the instance is validated.
niSourceDestCheck :: Lens' NetworkInterface (Maybe Bool)
niSourceDestCheck =
lens _niSourceDestCheck (\s a -> s { _niSourceDestCheck = a })
-- | The status of the network interface.
niStatus :: Lens' NetworkInterface (Maybe NetworkInterfaceStatus)
niStatus = lens _niStatus (\s a -> s { _niStatus = a })
-- | The ID of the subnet.
niSubnetId :: Lens' NetworkInterface (Maybe Text)
niSubnetId = lens _niSubnetId (\s a -> s { _niSubnetId = a })
-- | Any tags assigned to the network interface.
niTagSet :: Lens' NetworkInterface [Tag]
niTagSet = lens _niTagSet (\s a -> s { _niTagSet = a }) . _List
-- | The ID of the VPC.
niVpcId :: Lens' NetworkInterface (Maybe Text)
niVpcId = lens _niVpcId (\s a -> s { _niVpcId = a })
instance FromXML NetworkInterface where
parseXML x = NetworkInterface
<$> x .@? "association"
<*> x .@? "attachment"
<*> x .@? "availabilityZone"
<*> x .@? "description"
<*> x .@? "groupSet" .!@ mempty
<*> x .@? "macAddress"
<*> x .@? "networkInterfaceId"
<*> x .@? "ownerId"
<*> x .@? "privateDnsName"
<*> x .@? "privateIpAddress"
<*> x .@? "privateIpAddressesSet" .!@ mempty
<*> x .@? "requesterId"
<*> x .@? "requesterManaged"
<*> x .@? "sourceDestCheck"
<*> x .@? "status"
<*> x .@? "subnetId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery NetworkInterface where
toQuery NetworkInterface{..} = mconcat
[ "Association" =? _niAssociation
, "Attachment" =? _niAttachment
, "AvailabilityZone" =? _niAvailabilityZone
, "Description" =? _niDescription
, "GroupSet" `toQueryList` _niGroups
, "MacAddress" =? _niMacAddress
, "NetworkInterfaceId" =? _niNetworkInterfaceId
, "OwnerId" =? _niOwnerId
, "PrivateDnsName" =? _niPrivateDnsName
, "PrivateIpAddress" =? _niPrivateIpAddress
, "PrivateIpAddressesSet" `toQueryList` _niPrivateIpAddresses
, "RequesterId" =? _niRequesterId
, "RequesterManaged" =? _niRequesterManaged
, "SourceDestCheck" =? _niSourceDestCheck
, "Status" =? _niStatus
, "SubnetId" =? _niSubnetId
, "TagSet" `toQueryList` _niTagSet
, "VpcId" =? _niVpcId
]
data TelemetryStatus
= Down -- ^ DOWN
| Up -- ^ UP
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable TelemetryStatus
instance FromText TelemetryStatus where
parser = takeLowerText >>= \case
"down" -> pure Down
"up" -> pure Up
e -> fail $
"Failure parsing TelemetryStatus from " ++ show e
instance ToText TelemetryStatus where
toText = \case
Down -> "DOWN"
Up -> "UP"
instance ToByteString TelemetryStatus
instance ToHeader TelemetryStatus
instance ToQuery TelemetryStatus
instance FromXML TelemetryStatus where
parseXML = parseXMLText "TelemetryStatus"
data Subnet = Subnet
{ _s1AvailabilityZone :: Text
, _s1AvailableIpAddressCount :: Int
, _s1CidrBlock :: Text
, _s1DefaultForAz :: Bool
, _s1MapPublicIpOnLaunch :: Bool
, _s1State :: SubnetState
, _s1SubnetId :: Text
, _s1Tags :: List "item" Tag
, _s1VpcId :: Text
} deriving (Eq, Read, Show)
-- | 'Subnet' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 's1AvailabilityZone' @::@ 'Text'
--
-- * 's1AvailableIpAddressCount' @::@ 'Int'
--
-- * 's1CidrBlock' @::@ 'Text'
--
-- * 's1DefaultForAz' @::@ 'Bool'
--
-- * 's1MapPublicIpOnLaunch' @::@ 'Bool'
--
-- * 's1State' @::@ 'SubnetState'
--
-- * 's1SubnetId' @::@ 'Text'
--
-- * 's1Tags' @::@ ['Tag']
--
-- * 's1VpcId' @::@ 'Text'
--
subnet :: Text -- ^ 's1SubnetId'
-> SubnetState -- ^ 's1State'
-> Text -- ^ 's1VpcId'
-> Text -- ^ 's1CidrBlock'
-> Int -- ^ 's1AvailableIpAddressCount'
-> Text -- ^ 's1AvailabilityZone'
-> Bool -- ^ 's1DefaultForAz'
-> Bool -- ^ 's1MapPublicIpOnLaunch'
-> Subnet
subnet p1 p2 p3 p4 p5 p6 p7 p8 = Subnet
{ _s1SubnetId = p1
, _s1State = p2
, _s1VpcId = p3
, _s1CidrBlock = p4
, _s1AvailableIpAddressCount = p5
, _s1AvailabilityZone = p6
, _s1DefaultForAz = p7
, _s1MapPublicIpOnLaunch = p8
, _s1Tags = mempty
}
-- | The Availability Zone of the subnet.
s1AvailabilityZone :: Lens' Subnet Text
s1AvailabilityZone =
lens _s1AvailabilityZone (\s a -> s { _s1AvailabilityZone = a })
-- | The number of unused IP addresses in the subnet. Note that the IP addresses
-- for any stopped instances are considered unavailable.
s1AvailableIpAddressCount :: Lens' Subnet Int
s1AvailableIpAddressCount =
lens _s1AvailableIpAddressCount
(\s a -> s { _s1AvailableIpAddressCount = a })
-- | The CIDR block assigned to the subnet.
s1CidrBlock :: Lens' Subnet Text
s1CidrBlock = lens _s1CidrBlock (\s a -> s { _s1CidrBlock = a })
-- | Indicates whether this is the default subnet for the Availability Zone.
s1DefaultForAz :: Lens' Subnet Bool
s1DefaultForAz = lens _s1DefaultForAz (\s a -> s { _s1DefaultForAz = a })
-- | Indicates whether instances launched in this subnet receive a public IP
-- address.
s1MapPublicIpOnLaunch :: Lens' Subnet Bool
s1MapPublicIpOnLaunch =
lens _s1MapPublicIpOnLaunch (\s a -> s { _s1MapPublicIpOnLaunch = a })
-- | The current state of the subnet.
s1State :: Lens' Subnet SubnetState
s1State = lens _s1State (\s a -> s { _s1State = a })
-- | The ID of the subnet.
s1SubnetId :: Lens' Subnet Text
s1SubnetId = lens _s1SubnetId (\s a -> s { _s1SubnetId = a })
-- | Any tags assigned to the subnet.
s1Tags :: Lens' Subnet [Tag]
s1Tags = lens _s1Tags (\s a -> s { _s1Tags = a }) . _List
-- | The ID of the VPC the subnet is in.
s1VpcId :: Lens' Subnet Text
s1VpcId = lens _s1VpcId (\s a -> s { _s1VpcId = a })
instance FromXML Subnet where
parseXML x = Subnet
<$> x .@ "availabilityZone"
<*> x .@ "availableIpAddressCount"
<*> x .@ "cidrBlock"
<*> x .@ "defaultForAz"
<*> x .@ "mapPublicIpOnLaunch"
<*> x .@ "state"
<*> x .@ "subnetId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "vpcId"
instance ToQuery Subnet where
toQuery Subnet{..} = mconcat
[ "AvailabilityZone" =? _s1AvailabilityZone
, "AvailableIpAddressCount" =? _s1AvailableIpAddressCount
, "CidrBlock" =? _s1CidrBlock
, "DefaultForAz" =? _s1DefaultForAz
, "MapPublicIpOnLaunch" =? _s1MapPublicIpOnLaunch
, "State" =? _s1State
, "SubnetId" =? _s1SubnetId
, "TagSet" `toQueryList` _s1Tags
, "VpcId" =? _s1VpcId
]
data KeyPairInfo = KeyPairInfo
{ _kpiKeyFingerprint :: Maybe Text
, _kpiKeyName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'KeyPairInfo' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'kpiKeyFingerprint' @::@ 'Maybe' 'Text'
--
-- * 'kpiKeyName' @::@ 'Maybe' 'Text'
--
keyPairInfo :: KeyPairInfo
keyPairInfo = KeyPairInfo
{ _kpiKeyName = Nothing
, _kpiKeyFingerprint = Nothing
}
-- | If you used 'CreateKeyPair' to create the key pair, this is the SHA-1 digest of
-- the DER encoded private key. If you used 'ImportKeyPair' to provide AWS the
-- public key, this is the MD5 public key fingerprint as specified in section 4
-- of RFC4716.
kpiKeyFingerprint :: Lens' KeyPairInfo (Maybe Text)
kpiKeyFingerprint =
lens _kpiKeyFingerprint (\s a -> s { _kpiKeyFingerprint = a })
-- | The name of the key pair.
kpiKeyName :: Lens' KeyPairInfo (Maybe Text)
kpiKeyName = lens _kpiKeyName (\s a -> s { _kpiKeyName = a })
instance FromXML KeyPairInfo where
parseXML x = KeyPairInfo
<$> x .@? "keyFingerprint"
<*> x .@? "keyName"
instance ToQuery KeyPairInfo where
toQuery KeyPairInfo{..} = mconcat
[ "KeyFingerprint" =? _kpiKeyFingerprint
, "KeyName" =? _kpiKeyName
]
data LaunchPermissionModifications = LaunchPermissionModifications
{ _lpmAdd :: List "item" LaunchPermission
, _lpmRemove :: List "item" LaunchPermission
} deriving (Eq, Read, Show)
-- | 'LaunchPermissionModifications' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lpmAdd' @::@ ['LaunchPermission']
--
-- * 'lpmRemove' @::@ ['LaunchPermission']
--
launchPermissionModifications :: LaunchPermissionModifications
launchPermissionModifications = LaunchPermissionModifications
{ _lpmAdd = mempty
, _lpmRemove = mempty
}
-- | The AWS account ID to add to the list of launch permissions for the AMI.
lpmAdd :: Lens' LaunchPermissionModifications [LaunchPermission]
lpmAdd = lens _lpmAdd (\s a -> s { _lpmAdd = a }) . _List
-- | The AWS account ID to remove from the list of launch permissions for the AMI.
lpmRemove :: Lens' LaunchPermissionModifications [LaunchPermission]
lpmRemove = lens _lpmRemove (\s a -> s { _lpmRemove = a }) . _List
instance FromXML LaunchPermissionModifications where
parseXML x = LaunchPermissionModifications
<$> x .@? "Add" .!@ mempty
<*> x .@? "Remove" .!@ mempty
instance ToQuery LaunchPermissionModifications where
toQuery LaunchPermissionModifications{..} = mconcat
[ "Add" `toQueryList` _lpmAdd
, "Remove" `toQueryList` _lpmRemove
]
data SnapshotState
= Completed -- ^ completed
| Error -- ^ error
| Pending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SnapshotState
instance FromText SnapshotState where
parser = takeLowerText >>= \case
"completed" -> pure Completed
"error" -> pure Error
"pending" -> pure Pending
e -> fail $
"Failure parsing SnapshotState from " ++ show e
instance ToText SnapshotState where
toText = \case
Completed -> "completed"
Error -> "error"
Pending -> "pending"
instance ToByteString SnapshotState
instance ToHeader SnapshotState
instance ToQuery SnapshotState
instance FromXML SnapshotState where
parseXML = parseXMLText "SnapshotState"
data InstanceNetworkInterfaceAssociation = InstanceNetworkInterfaceAssociation
{ _iniaIpOwnerId :: Maybe Text
, _iniaPublicDnsName :: Maybe Text
, _iniaPublicIp :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'InstanceNetworkInterfaceAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iniaIpOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'iniaPublicDnsName' @::@ 'Maybe' 'Text'
--
-- * 'iniaPublicIp' @::@ 'Maybe' 'Text'
--
instanceNetworkInterfaceAssociation :: InstanceNetworkInterfaceAssociation
instanceNetworkInterfaceAssociation = InstanceNetworkInterfaceAssociation
{ _iniaPublicIp = Nothing
, _iniaPublicDnsName = Nothing
, _iniaIpOwnerId = Nothing
}
-- | The ID of the owner of the Elastic IP address.
iniaIpOwnerId :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text)
iniaIpOwnerId = lens _iniaIpOwnerId (\s a -> s { _iniaIpOwnerId = a })
-- | The public DNS name.
iniaPublicDnsName :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text)
iniaPublicDnsName =
lens _iniaPublicDnsName (\s a -> s { _iniaPublicDnsName = a })
-- | The public IP address or Elastic IP address bound to the network interface.
iniaPublicIp :: Lens' InstanceNetworkInterfaceAssociation (Maybe Text)
iniaPublicIp = lens _iniaPublicIp (\s a -> s { _iniaPublicIp = a })
instance FromXML InstanceNetworkInterfaceAssociation where
parseXML x = InstanceNetworkInterfaceAssociation
<$> x .@? "ipOwnerId"
<*> x .@? "publicDnsName"
<*> x .@? "publicIp"
instance ToQuery InstanceNetworkInterfaceAssociation where
toQuery InstanceNetworkInterfaceAssociation{..} = mconcat
[ "IpOwnerId" =? _iniaIpOwnerId
, "PublicDnsName" =? _iniaPublicDnsName
, "PublicIp" =? _iniaPublicIp
]
data DiskImageDetail = DiskImageDetail
{ _didBytes :: Integer
, _didFormat :: DiskImageFormat
, _didImportManifestUrl :: Text
} deriving (Eq, Read, Show)
-- | 'DiskImageDetail' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'didBytes' @::@ 'Integer'
--
-- * 'didFormat' @::@ 'DiskImageFormat'
--
-- * 'didImportManifestUrl' @::@ 'Text'
--
diskImageDetail :: DiskImageFormat -- ^ 'didFormat'
-> Integer -- ^ 'didBytes'
-> Text -- ^ 'didImportManifestUrl'
-> DiskImageDetail
diskImageDetail p1 p2 p3 = DiskImageDetail
{ _didFormat = p1
, _didBytes = p2
, _didImportManifestUrl = p3
}
didBytes :: Lens' DiskImageDetail Integer
didBytes = lens _didBytes (\s a -> s { _didBytes = a })
-- | The disk image format.
didFormat :: Lens' DiskImageDetail DiskImageFormat
didFormat = lens _didFormat (\s a -> s { _didFormat = a })
-- | A presigned URL for the import manifest stored in Amazon S3 and presented
-- here as an Amazon S3 presigned URL. For information about creating a
-- presigned URL for an Amazon S3 object, read the "Query String Request
-- Authentication Alternative" section of the <http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html Authenticating REST Requests> topic
-- in the /Amazon Simple Storage Service Developer Guide/.
didImportManifestUrl :: Lens' DiskImageDetail Text
didImportManifestUrl =
lens _didImportManifestUrl (\s a -> s { _didImportManifestUrl = a })
instance FromXML DiskImageDetail where
parseXML x = DiskImageDetail
<$> x .@ "bytes"
<*> x .@ "format"
<*> x .@ "importManifestUrl"
instance ToQuery DiskImageDetail where
toQuery DiskImageDetail{..} = mconcat
[ "Bytes" =? _didBytes
, "Format" =? _didFormat
, "ImportManifestUrl" =? _didImportManifestUrl
]
data InstancePrivateIpAddress = InstancePrivateIpAddress
{ _ipiaAssociation :: Maybe InstanceNetworkInterfaceAssociation
, _ipiaPrimary :: Maybe Bool
, _ipiaPrivateDnsName :: Maybe Text
, _ipiaPrivateIpAddress :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'InstancePrivateIpAddress' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ipiaAssociation' @::@ 'Maybe' 'InstanceNetworkInterfaceAssociation'
--
-- * 'ipiaPrimary' @::@ 'Maybe' 'Bool'
--
-- * 'ipiaPrivateDnsName' @::@ 'Maybe' 'Text'
--
-- * 'ipiaPrivateIpAddress' @::@ 'Maybe' 'Text'
--
instancePrivateIpAddress :: InstancePrivateIpAddress
instancePrivateIpAddress = InstancePrivateIpAddress
{ _ipiaPrivateIpAddress = Nothing
, _ipiaPrivateDnsName = Nothing
, _ipiaPrimary = Nothing
, _ipiaAssociation = Nothing
}
-- | The association information for an Elastic IP address for the network
-- interface.
ipiaAssociation :: Lens' InstancePrivateIpAddress (Maybe InstanceNetworkInterfaceAssociation)
ipiaAssociation = lens _ipiaAssociation (\s a -> s { _ipiaAssociation = a })
-- | Indicates whether this IP address is the primary private IP address of the
-- network interface.
ipiaPrimary :: Lens' InstancePrivateIpAddress (Maybe Bool)
ipiaPrimary = lens _ipiaPrimary (\s a -> s { _ipiaPrimary = a })
-- | The private DNS name.
ipiaPrivateDnsName :: Lens' InstancePrivateIpAddress (Maybe Text)
ipiaPrivateDnsName =
lens _ipiaPrivateDnsName (\s a -> s { _ipiaPrivateDnsName = a })
-- | The private IP address of the network interface.
ipiaPrivateIpAddress :: Lens' InstancePrivateIpAddress (Maybe Text)
ipiaPrivateIpAddress =
lens _ipiaPrivateIpAddress (\s a -> s { _ipiaPrivateIpAddress = a })
instance FromXML InstancePrivateIpAddress where
parseXML x = InstancePrivateIpAddress
<$> x .@? "association"
<*> x .@? "primary"
<*> x .@? "privateDnsName"
<*> x .@? "privateIpAddress"
instance ToQuery InstancePrivateIpAddress where
toQuery InstancePrivateIpAddress{..} = mconcat
[ "Association" =? _ipiaAssociation
, "Primary" =? _ipiaPrimary
, "PrivateDnsName" =? _ipiaPrivateDnsName
, "PrivateIpAddress" =? _ipiaPrivateIpAddress
]
data CancelledSpotInstanceRequest = CancelledSpotInstanceRequest
{ _csiSpotInstanceRequestId :: Maybe Text
, _csiState :: Maybe CancelSpotInstanceRequestState
} deriving (Eq, Read, Show)
-- | 'CancelledSpotInstanceRequest' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'csiSpotInstanceRequestId' @::@ 'Maybe' 'Text'
--
-- * 'csiState' @::@ 'Maybe' 'CancelSpotInstanceRequestState'
--
cancelledSpotInstanceRequest :: CancelledSpotInstanceRequest
cancelledSpotInstanceRequest = CancelledSpotInstanceRequest
{ _csiSpotInstanceRequestId = Nothing
, _csiState = Nothing
}
-- | The ID of the Spot Instance request.
csiSpotInstanceRequestId :: Lens' CancelledSpotInstanceRequest (Maybe Text)
csiSpotInstanceRequestId =
lens _csiSpotInstanceRequestId
(\s a -> s { _csiSpotInstanceRequestId = a })
-- | The state of the Spot Instance request.
csiState :: Lens' CancelledSpotInstanceRequest (Maybe CancelSpotInstanceRequestState)
csiState = lens _csiState (\s a -> s { _csiState = a })
instance FromXML CancelledSpotInstanceRequest where
parseXML x = CancelledSpotInstanceRequest
<$> x .@? "spotInstanceRequestId"
<*> x .@? "state"
instance ToQuery CancelledSpotInstanceRequest where
toQuery CancelledSpotInstanceRequest{..} = mconcat
[ "SpotInstanceRequestId" =? _csiSpotInstanceRequestId
, "State" =? _csiState
]
newtype VpnConnectionOptionsSpecification = VpnConnectionOptionsSpecification
{ _vcosStaticRoutesOnly :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'VpnConnectionOptionsSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vcosStaticRoutesOnly' @::@ 'Maybe' 'Bool'
--
vpnConnectionOptionsSpecification :: VpnConnectionOptionsSpecification
vpnConnectionOptionsSpecification = VpnConnectionOptionsSpecification
{ _vcosStaticRoutesOnly = Nothing
}
-- | Indicates whether the VPN connection uses static routes only. Static routes
-- must be used for devices that don't support BGP.
vcosStaticRoutesOnly :: Lens' VpnConnectionOptionsSpecification (Maybe Bool)
vcosStaticRoutesOnly =
lens _vcosStaticRoutesOnly (\s a -> s { _vcosStaticRoutesOnly = a })
instance FromXML VpnConnectionOptionsSpecification where
parseXML x = VpnConnectionOptionsSpecification
<$> x .@? "staticRoutesOnly"
instance ToQuery VpnConnectionOptionsSpecification where
toQuery VpnConnectionOptionsSpecification{..} = mconcat
[ "StaticRoutesOnly" =? _vcosStaticRoutesOnly
]
data Address = Address
{ _aAllocationId :: Maybe Text
, _aAssociationId :: Maybe Text
, _aDomain :: Maybe DomainType
, _aInstanceId :: Maybe Text
, _aNetworkInterfaceId :: Maybe Text
, _aNetworkInterfaceOwnerId :: Maybe Text
, _aPrivateIpAddress :: Maybe Text
, _aPublicIp :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'Address' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'aAllocationId' @::@ 'Maybe' 'Text'
--
-- * 'aAssociationId' @::@ 'Maybe' 'Text'
--
-- * 'aDomain' @::@ 'Maybe' 'DomainType'
--
-- * 'aInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'aNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'aNetworkInterfaceOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'aPrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'aPublicIp' @::@ 'Maybe' 'Text'
--
address :: Address
address = Address
{ _aInstanceId = Nothing
, _aPublicIp = Nothing
, _aAllocationId = Nothing
, _aAssociationId = Nothing
, _aDomain = Nothing
, _aNetworkInterfaceId = Nothing
, _aNetworkInterfaceOwnerId = Nothing
, _aPrivateIpAddress = Nothing
}
-- | The ID representing the allocation of the address for use with EC2-VPC.
aAllocationId :: Lens' Address (Maybe Text)
aAllocationId = lens _aAllocationId (\s a -> s { _aAllocationId = a })
-- | The ID representing the association of the address with an instance in a VPC.
aAssociationId :: Lens' Address (Maybe Text)
aAssociationId = lens _aAssociationId (\s a -> s { _aAssociationId = a })
-- | Indicates whether this Elastic IP address is for use with instances in
-- EC2-Classic ('standard') or instances in a VPC ('vpc').
aDomain :: Lens' Address (Maybe DomainType)
aDomain = lens _aDomain (\s a -> s { _aDomain = a })
-- | The ID of the instance the address is associated with (if any).
aInstanceId :: Lens' Address (Maybe Text)
aInstanceId = lens _aInstanceId (\s a -> s { _aInstanceId = a })
-- | The ID of the network interface.
aNetworkInterfaceId :: Lens' Address (Maybe Text)
aNetworkInterfaceId =
lens _aNetworkInterfaceId (\s a -> s { _aNetworkInterfaceId = a })
-- | The ID of the AWS account that owns the network interface.
aNetworkInterfaceOwnerId :: Lens' Address (Maybe Text)
aNetworkInterfaceOwnerId =
lens _aNetworkInterfaceOwnerId
(\s a -> s { _aNetworkInterfaceOwnerId = a })
-- | The private IP address associated with the Elastic IP address.
aPrivateIpAddress :: Lens' Address (Maybe Text)
aPrivateIpAddress =
lens _aPrivateIpAddress (\s a -> s { _aPrivateIpAddress = a })
-- | The Elastic IP address.
aPublicIp :: Lens' Address (Maybe Text)
aPublicIp = lens _aPublicIp (\s a -> s { _aPublicIp = a })
instance FromXML Address where
parseXML x = Address
<$> x .@? "allocationId"
<*> x .@? "associationId"
<*> x .@? "domain"
<*> x .@? "instanceId"
<*> x .@? "networkInterfaceId"
<*> x .@? "networkInterfaceOwnerId"
<*> x .@? "privateIpAddress"
<*> x .@? "publicIp"
instance ToQuery Address where
toQuery Address{..} = mconcat
[ "AllocationId" =? _aAllocationId
, "AssociationId" =? _aAssociationId
, "Domain" =? _aDomain
, "InstanceId" =? _aInstanceId
, "NetworkInterfaceId" =? _aNetworkInterfaceId
, "NetworkInterfaceOwnerId" =? _aNetworkInterfaceOwnerId
, "PrivateIpAddress" =? _aPrivateIpAddress
, "PublicIp" =? _aPublicIp
]
data VolumeAttachmentState
= VASAttached -- ^ attached
| VASAttaching -- ^ attaching
| VASDetached -- ^ detached
| VASDetaching -- ^ detaching
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeAttachmentState
instance FromText VolumeAttachmentState where
parser = takeLowerText >>= \case
"attached" -> pure VASAttached
"attaching" -> pure VASAttaching
"detached" -> pure VASDetached
"detaching" -> pure VASDetaching
e -> fail $
"Failure parsing VolumeAttachmentState from " ++ show e
instance ToText VolumeAttachmentState where
toText = \case
VASAttached -> "attached"
VASAttaching -> "attaching"
VASDetached -> "detached"
VASDetaching -> "detaching"
instance ToByteString VolumeAttachmentState
instance ToHeader VolumeAttachmentState
instance ToQuery VolumeAttachmentState
instance FromXML VolumeAttachmentState where
parseXML = parseXMLText "VolumeAttachmentState"
data LaunchPermission = LaunchPermission
{ _lpGroup :: Maybe PermissionGroup
, _lpUserId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'LaunchPermission' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lpGroup' @::@ 'Maybe' 'PermissionGroup'
--
-- * 'lpUserId' @::@ 'Maybe' 'Text'
--
launchPermission :: LaunchPermission
launchPermission = LaunchPermission
{ _lpUserId = Nothing
, _lpGroup = Nothing
}
-- | The name of the group.
lpGroup :: Lens' LaunchPermission (Maybe PermissionGroup)
lpGroup = lens _lpGroup (\s a -> s { _lpGroup = a })
-- | The AWS account ID.
lpUserId :: Lens' LaunchPermission (Maybe Text)
lpUserId = lens _lpUserId (\s a -> s { _lpUserId = a })
instance FromXML LaunchPermission where
parseXML x = LaunchPermission
<$> x .@? "group"
<*> x .@? "userId"
instance ToQuery LaunchPermission where
toQuery LaunchPermission{..} = mconcat
[ "Group" =? _lpGroup
, "UserId" =? _lpUserId
]
data RouteState
= Active -- ^ active
| Blackhole -- ^ blackhole
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable RouteState
instance FromText RouteState where
parser = takeLowerText >>= \case
"active" -> pure Active
"blackhole" -> pure Blackhole
e -> fail $
"Failure parsing RouteState from " ++ show e
instance ToText RouteState where
toText = \case
Active -> "active"
Blackhole -> "blackhole"
instance ToByteString RouteState
instance ToHeader RouteState
instance ToQuery RouteState
instance FromXML RouteState where
parseXML = parseXMLText "RouteState"
data RouteTableAssociation = RouteTableAssociation
{ _rtaMain :: Maybe Bool
, _rtaRouteTableAssociationId :: Maybe Text
, _rtaRouteTableId :: Maybe Text
, _rtaSubnetId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'RouteTableAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rtaMain' @::@ 'Maybe' 'Bool'
--
-- * 'rtaRouteTableAssociationId' @::@ 'Maybe' 'Text'
--
-- * 'rtaRouteTableId' @::@ 'Maybe' 'Text'
--
-- * 'rtaSubnetId' @::@ 'Maybe' 'Text'
--
routeTableAssociation :: RouteTableAssociation
routeTableAssociation = RouteTableAssociation
{ _rtaRouteTableAssociationId = Nothing
, _rtaRouteTableId = Nothing
, _rtaSubnetId = Nothing
, _rtaMain = Nothing
}
-- | Indicates whether this is the main route table.
rtaMain :: Lens' RouteTableAssociation (Maybe Bool)
rtaMain = lens _rtaMain (\s a -> s { _rtaMain = a })
-- | The ID of the association between a route table and a subnet.
rtaRouteTableAssociationId :: Lens' RouteTableAssociation (Maybe Text)
rtaRouteTableAssociationId =
lens _rtaRouteTableAssociationId
(\s a -> s { _rtaRouteTableAssociationId = a })
-- | The ID of the route table.
rtaRouteTableId :: Lens' RouteTableAssociation (Maybe Text)
rtaRouteTableId = lens _rtaRouteTableId (\s a -> s { _rtaRouteTableId = a })
-- | The ID of the subnet.
rtaSubnetId :: Lens' RouteTableAssociation (Maybe Text)
rtaSubnetId = lens _rtaSubnetId (\s a -> s { _rtaSubnetId = a })
instance FromXML RouteTableAssociation where
parseXML x = RouteTableAssociation
<$> x .@? "main"
<*> x .@? "routeTableAssociationId"
<*> x .@? "routeTableId"
<*> x .@? "subnetId"
instance ToQuery RouteTableAssociation where
toQuery RouteTableAssociation{..} = mconcat
[ "Main" =? _rtaMain
, "RouteTableAssociationId" =? _rtaRouteTableAssociationId
, "RouteTableId" =? _rtaRouteTableId
, "SubnetId" =? _rtaSubnetId
]
data BundleTaskState
= BTSBundling -- ^ bundling
| BTSCancelling -- ^ cancelling
| BTSComplete -- ^ complete
| BTSFailed -- ^ failed
| BTSPending -- ^ pending
| BTSStoring -- ^ storing
| BTSWaitingForShutdown -- ^ waiting-for-shutdown
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable BundleTaskState
instance FromText BundleTaskState where
parser = takeLowerText >>= \case
"bundling" -> pure BTSBundling
"cancelling" -> pure BTSCancelling
"complete" -> pure BTSComplete
"failed" -> pure BTSFailed
"pending" -> pure BTSPending
"storing" -> pure BTSStoring
"waiting-for-shutdown" -> pure BTSWaitingForShutdown
e -> fail $
"Failure parsing BundleTaskState from " ++ show e
instance ToText BundleTaskState where
toText = \case
BTSBundling -> "bundling"
BTSCancelling -> "cancelling"
BTSComplete -> "complete"
BTSFailed -> "failed"
BTSPending -> "pending"
BTSStoring -> "storing"
BTSWaitingForShutdown -> "waiting-for-shutdown"
instance ToByteString BundleTaskState
instance ToHeader BundleTaskState
instance ToQuery BundleTaskState
instance FromXML BundleTaskState where
parseXML = parseXMLText "BundleTaskState"
data PortRange = PortRange
{ _prFrom :: Maybe Int
, _prTo :: Maybe Int
} deriving (Eq, Ord, Read, Show)
-- | 'PortRange' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'prFrom' @::@ 'Maybe' 'Int'
--
-- * 'prTo' @::@ 'Maybe' 'Int'
--
portRange :: PortRange
portRange = PortRange
{ _prFrom = Nothing
, _prTo = Nothing
}
-- | The first port in the range.
prFrom :: Lens' PortRange (Maybe Int)
prFrom = lens _prFrom (\s a -> s { _prFrom = a })
-- | The last port in the range.
prTo :: Lens' PortRange (Maybe Int)
prTo = lens _prTo (\s a -> s { _prTo = a })
instance FromXML PortRange where
parseXML x = PortRange
<$> x .@? "from"
<*> x .@? "to"
instance ToQuery PortRange where
toQuery PortRange{..} = mconcat
[ "From" =? _prFrom
, "To" =? _prTo
]
data VpcAttributeName
= EnableDnsHostnames -- ^ enableDnsHostnames
| EnableDnsSupport -- ^ enableDnsSupport
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VpcAttributeName
instance FromText VpcAttributeName where
parser = takeLowerText >>= \case
"enablednshostnames" -> pure EnableDnsHostnames
"enablednssupport" -> pure EnableDnsSupport
e -> fail $
"Failure parsing VpcAttributeName from " ++ show e
instance ToText VpcAttributeName where
toText = \case
EnableDnsHostnames -> "enableDnsHostnames"
EnableDnsSupport -> "enableDnsSupport"
instance ToByteString VpcAttributeName
instance ToHeader VpcAttributeName
instance ToQuery VpcAttributeName
instance FromXML VpcAttributeName where
parseXML = parseXMLText "VpcAttributeName"
data ReservedInstancesConfiguration = ReservedInstancesConfiguration
{ _ricAvailabilityZone :: Maybe Text
, _ricInstanceCount :: Maybe Int
, _ricInstanceType :: Maybe InstanceType
, _ricPlatform :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ReservedInstancesConfiguration' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ricAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'ricInstanceCount' @::@ 'Maybe' 'Int'
--
-- * 'ricInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'ricPlatform' @::@ 'Maybe' 'Text'
--
reservedInstancesConfiguration :: ReservedInstancesConfiguration
reservedInstancesConfiguration = ReservedInstancesConfiguration
{ _ricAvailabilityZone = Nothing
, _ricPlatform = Nothing
, _ricInstanceCount = Nothing
, _ricInstanceType = Nothing
}
-- | The Availability Zone for the modified Reserved Instances.
ricAvailabilityZone :: Lens' ReservedInstancesConfiguration (Maybe Text)
ricAvailabilityZone =
lens _ricAvailabilityZone (\s a -> s { _ricAvailabilityZone = a })
-- | The number of modified Reserved Instances.
ricInstanceCount :: Lens' ReservedInstancesConfiguration (Maybe Int)
ricInstanceCount = lens _ricInstanceCount (\s a -> s { _ricInstanceCount = a })
-- | The instance type for the modified Reserved Instances.
ricInstanceType :: Lens' ReservedInstancesConfiguration (Maybe InstanceType)
ricInstanceType = lens _ricInstanceType (\s a -> s { _ricInstanceType = a })
-- | The network platform of the modified Reserved Instances, which is either
-- EC2-Classic or EC2-VPC.
ricPlatform :: Lens' ReservedInstancesConfiguration (Maybe Text)
ricPlatform = lens _ricPlatform (\s a -> s { _ricPlatform = a })
instance FromXML ReservedInstancesConfiguration where
parseXML x = ReservedInstancesConfiguration
<$> x .@? "availabilityZone"
<*> x .@? "instanceCount"
<*> x .@? "instanceType"
<*> x .@? "platform"
instance ToQuery ReservedInstancesConfiguration where
toQuery ReservedInstancesConfiguration{..} = mconcat
[ "AvailabilityZone" =? _ricAvailabilityZone
, "InstanceCount" =? _ricInstanceCount
, "InstanceType" =? _ricInstanceType
, "Platform" =? _ricPlatform
]
data VolumeStatusDetails = VolumeStatusDetails
{ _vsdName :: Maybe VolumeStatusName
, _vsdStatus :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VolumeStatusDetails' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vsdName' @::@ 'Maybe' 'VolumeStatusName'
--
-- * 'vsdStatus' @::@ 'Maybe' 'Text'
--
volumeStatusDetails :: VolumeStatusDetails
volumeStatusDetails = VolumeStatusDetails
{ _vsdName = Nothing
, _vsdStatus = Nothing
}
-- | The name of the volume status.
vsdName :: Lens' VolumeStatusDetails (Maybe VolumeStatusName)
vsdName = lens _vsdName (\s a -> s { _vsdName = a })
-- | The intended status of the volume status.
vsdStatus :: Lens' VolumeStatusDetails (Maybe Text)
vsdStatus = lens _vsdStatus (\s a -> s { _vsdStatus = a })
instance FromXML VolumeStatusDetails where
parseXML x = VolumeStatusDetails
<$> x .@? "name"
<*> x .@? "status"
instance ToQuery VolumeStatusDetails where
toQuery VolumeStatusDetails{..} = mconcat
[ "Name" =? _vsdName
, "Status" =? _vsdStatus
]
data SpotInstanceState
= SISActive -- ^ active
| SISCancelled -- ^ cancelled
| SISClosed -- ^ closed
| SISFailed -- ^ failed
| SISOpen -- ^ open
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SpotInstanceState
instance FromText SpotInstanceState where
parser = takeLowerText >>= \case
"active" -> pure SISActive
"cancelled" -> pure SISCancelled
"closed" -> pure SISClosed
"failed" -> pure SISFailed
"open" -> pure SISOpen
e -> fail $
"Failure parsing SpotInstanceState from " ++ show e
instance ToText SpotInstanceState where
toText = \case
SISActive -> "active"
SISCancelled -> "cancelled"
SISClosed -> "closed"
SISFailed -> "failed"
SISOpen -> "open"
instance ToByteString SpotInstanceState
instance ToHeader SpotInstanceState
instance ToQuery SpotInstanceState
instance FromXML SpotInstanceState where
parseXML = parseXMLText "SpotInstanceState"
newtype VpnConnectionOptions = VpnConnectionOptions
{ _vcoStaticRoutesOnly :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'VpnConnectionOptions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vcoStaticRoutesOnly' @::@ 'Maybe' 'Bool'
--
vpnConnectionOptions :: VpnConnectionOptions
vpnConnectionOptions = VpnConnectionOptions
{ _vcoStaticRoutesOnly = Nothing
}
-- | Indicates whether the VPN connection uses static routes only. Static routes
-- must be used for devices that don't support BGP.
vcoStaticRoutesOnly :: Lens' VpnConnectionOptions (Maybe Bool)
vcoStaticRoutesOnly =
lens _vcoStaticRoutesOnly (\s a -> s { _vcoStaticRoutesOnly = a })
instance FromXML VpnConnectionOptions where
parseXML x = VpnConnectionOptions
<$> x .@? "staticRoutesOnly"
instance ToQuery VpnConnectionOptions where
toQuery VpnConnectionOptions{..} = mconcat
[ "StaticRoutesOnly" =? _vcoStaticRoutesOnly
]
data UserIdGroupPair = UserIdGroupPair
{ _uigpGroupId :: Maybe Text
, _uigpGroupName :: Maybe Text
, _uigpUserId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'UserIdGroupPair' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uigpGroupId' @::@ 'Maybe' 'Text'
--
-- * 'uigpGroupName' @::@ 'Maybe' 'Text'
--
-- * 'uigpUserId' @::@ 'Maybe' 'Text'
--
userIdGroupPair :: UserIdGroupPair
userIdGroupPair = UserIdGroupPair
{ _uigpUserId = Nothing
, _uigpGroupName = Nothing
, _uigpGroupId = Nothing
}
-- | The ID of the security group.
uigpGroupId :: Lens' UserIdGroupPair (Maybe Text)
uigpGroupId = lens _uigpGroupId (\s a -> s { _uigpGroupId = a })
-- | The name of the security group. In a request, use this parameter for a
-- security group in EC2-Classic or a default VPC only. For a security group in
-- a nondefault VPC, use 'GroupId'.
uigpGroupName :: Lens' UserIdGroupPair (Maybe Text)
uigpGroupName = lens _uigpGroupName (\s a -> s { _uigpGroupName = a })
-- | The ID of an AWS account. EC2-Classic only.
uigpUserId :: Lens' UserIdGroupPair (Maybe Text)
uigpUserId = lens _uigpUserId (\s a -> s { _uigpUserId = a })
instance FromXML UserIdGroupPair where
parseXML x = UserIdGroupPair
<$> x .@? "groupId"
<*> x .@? "groupName"
<*> x .@? "userId"
instance ToQuery UserIdGroupPair where
toQuery UserIdGroupPair{..} = mconcat
[ "GroupId" =? _uigpGroupId
, "GroupName" =? _uigpGroupName
, "UserId" =? _uigpUserId
]
data InstanceStatusSummary = InstanceStatusSummary
{ _issDetails :: List "item" InstanceStatusDetails
, _issStatus :: Maybe SummaryStatus
} deriving (Eq, Read, Show)
-- | 'InstanceStatusSummary' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'issDetails' @::@ ['InstanceStatusDetails']
--
-- * 'issStatus' @::@ 'Maybe' 'SummaryStatus'
--
instanceStatusSummary :: InstanceStatusSummary
instanceStatusSummary = InstanceStatusSummary
{ _issStatus = Nothing
, _issDetails = mempty
}
-- | The system instance health or application instance health.
issDetails :: Lens' InstanceStatusSummary [InstanceStatusDetails]
issDetails = lens _issDetails (\s a -> s { _issDetails = a }) . _List
-- | The status.
issStatus :: Lens' InstanceStatusSummary (Maybe SummaryStatus)
issStatus = lens _issStatus (\s a -> s { _issStatus = a })
instance FromXML InstanceStatusSummary where
parseXML x = InstanceStatusSummary
<$> x .@? "details" .!@ mempty
<*> x .@? "status"
instance ToQuery InstanceStatusSummary where
toQuery InstanceStatusSummary{..} = mconcat
[ "Details" `toQueryList` _issDetails
, "Status" =? _issStatus
]
data SpotPlacement = SpotPlacement
{ _sp1AvailabilityZone :: Maybe Text
, _sp1GroupName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'SpotPlacement' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sp1AvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'sp1GroupName' @::@ 'Maybe' 'Text'
--
spotPlacement :: SpotPlacement
spotPlacement = SpotPlacement
{ _sp1AvailabilityZone = Nothing
, _sp1GroupName = Nothing
}
-- | The Availability Zone.
sp1AvailabilityZone :: Lens' SpotPlacement (Maybe Text)
sp1AvailabilityZone =
lens _sp1AvailabilityZone (\s a -> s { _sp1AvailabilityZone = a })
-- | The name of the placement group (for cluster instances).
sp1GroupName :: Lens' SpotPlacement (Maybe Text)
sp1GroupName = lens _sp1GroupName (\s a -> s { _sp1GroupName = a })
instance FromXML SpotPlacement where
parseXML x = SpotPlacement
<$> x .@? "availabilityZone"
<*> x .@? "groupName"
instance ToQuery SpotPlacement where
toQuery SpotPlacement{..} = mconcat
[ "AvailabilityZone" =? _sp1AvailabilityZone
, "GroupName" =? _sp1GroupName
]
data EbsInstanceBlockDeviceSpecification = EbsInstanceBlockDeviceSpecification
{ _eibdsDeleteOnTermination :: Maybe Bool
, _eibdsVolumeId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'EbsInstanceBlockDeviceSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'eibdsDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'eibdsVolumeId' @::@ 'Maybe' 'Text'
--
ebsInstanceBlockDeviceSpecification :: EbsInstanceBlockDeviceSpecification
ebsInstanceBlockDeviceSpecification = EbsInstanceBlockDeviceSpecification
{ _eibdsVolumeId = Nothing
, _eibdsDeleteOnTermination = Nothing
}
-- | Indicates whether the volume is deleted on instance termination.
eibdsDeleteOnTermination :: Lens' EbsInstanceBlockDeviceSpecification (Maybe Bool)
eibdsDeleteOnTermination =
lens _eibdsDeleteOnTermination
(\s a -> s { _eibdsDeleteOnTermination = a })
-- | The ID of the Amazon EBS volume.
eibdsVolumeId :: Lens' EbsInstanceBlockDeviceSpecification (Maybe Text)
eibdsVolumeId = lens _eibdsVolumeId (\s a -> s { _eibdsVolumeId = a })
instance FromXML EbsInstanceBlockDeviceSpecification where
parseXML x = EbsInstanceBlockDeviceSpecification
<$> x .@? "deleteOnTermination"
<*> x .@? "volumeId"
instance ToQuery EbsInstanceBlockDeviceSpecification where
toQuery EbsInstanceBlockDeviceSpecification{..} = mconcat
[ "DeleteOnTermination" =? _eibdsDeleteOnTermination
, "VolumeId" =? _eibdsVolumeId
]
data NetworkAclAssociation = NetworkAclAssociation
{ _naaNetworkAclAssociationId :: Maybe Text
, _naaNetworkAclId :: Maybe Text
, _naaSubnetId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'NetworkAclAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'naaNetworkAclAssociationId' @::@ 'Maybe' 'Text'
--
-- * 'naaNetworkAclId' @::@ 'Maybe' 'Text'
--
-- * 'naaSubnetId' @::@ 'Maybe' 'Text'
--
networkAclAssociation :: NetworkAclAssociation
networkAclAssociation = NetworkAclAssociation
{ _naaNetworkAclAssociationId = Nothing
, _naaNetworkAclId = Nothing
, _naaSubnetId = Nothing
}
-- | The ID of the association between a network ACL and a subnet.
naaNetworkAclAssociationId :: Lens' NetworkAclAssociation (Maybe Text)
naaNetworkAclAssociationId =
lens _naaNetworkAclAssociationId
(\s a -> s { _naaNetworkAclAssociationId = a })
-- | The ID of the network ACL.
naaNetworkAclId :: Lens' NetworkAclAssociation (Maybe Text)
naaNetworkAclId = lens _naaNetworkAclId (\s a -> s { _naaNetworkAclId = a })
-- | The ID of the subnet.
naaSubnetId :: Lens' NetworkAclAssociation (Maybe Text)
naaSubnetId = lens _naaSubnetId (\s a -> s { _naaSubnetId = a })
instance FromXML NetworkAclAssociation where
parseXML x = NetworkAclAssociation
<$> x .@? "networkAclAssociationId"
<*> x .@? "networkAclId"
<*> x .@? "subnetId"
instance ToQuery NetworkAclAssociation where
toQuery NetworkAclAssociation{..} = mconcat
[ "NetworkAclAssociationId" =? _naaNetworkAclAssociationId
, "NetworkAclId" =? _naaNetworkAclId
, "SubnetId" =? _naaSubnetId
]
data BundleTask = BundleTask
{ _btBundleId :: Text
, _btBundleTaskError :: Maybe BundleTaskError
, _btInstanceId :: Text
, _btProgress :: Text
, _btStartTime :: ISO8601
, _btState :: BundleTaskState
, _btStorage :: Storage
, _btUpdateTime :: ISO8601
} deriving (Eq, Read, Show)
-- | 'BundleTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'btBundleId' @::@ 'Text'
--
-- * 'btBundleTaskError' @::@ 'Maybe' 'BundleTaskError'
--
-- * 'btInstanceId' @::@ 'Text'
--
-- * 'btProgress' @::@ 'Text'
--
-- * 'btStartTime' @::@ 'UTCTime'
--
-- * 'btState' @::@ 'BundleTaskState'
--
-- * 'btStorage' @::@ 'Storage'
--
-- * 'btUpdateTime' @::@ 'UTCTime'
--
bundleTask :: Text -- ^ 'btInstanceId'
-> Text -- ^ 'btBundleId'
-> BundleTaskState -- ^ 'btState'
-> UTCTime -- ^ 'btStartTime'
-> UTCTime -- ^ 'btUpdateTime'
-> Storage -- ^ 'btStorage'
-> Text -- ^ 'btProgress'
-> BundleTask
bundleTask p1 p2 p3 p4 p5 p6 p7 = BundleTask
{ _btInstanceId = p1
, _btBundleId = p2
, _btState = p3
, _btStartTime = withIso _Time (const id) p4
, _btUpdateTime = withIso _Time (const id) p5
, _btStorage = p6
, _btProgress = p7
, _btBundleTaskError = Nothing
}
-- | The ID of the bundle task.
btBundleId :: Lens' BundleTask Text
btBundleId = lens _btBundleId (\s a -> s { _btBundleId = a })
-- | If the task fails, a description of the error.
btBundleTaskError :: Lens' BundleTask (Maybe BundleTaskError)
btBundleTaskError =
lens _btBundleTaskError (\s a -> s { _btBundleTaskError = a })
-- | The ID of the instance associated with this bundle task.
btInstanceId :: Lens' BundleTask Text
btInstanceId = lens _btInstanceId (\s a -> s { _btInstanceId = a })
-- | The level of task completion, as a percent (for example, 20%).
btProgress :: Lens' BundleTask Text
btProgress = lens _btProgress (\s a -> s { _btProgress = a })
-- | The time this task started.
btStartTime :: Lens' BundleTask UTCTime
btStartTime = lens _btStartTime (\s a -> s { _btStartTime = a }) . _Time
-- | The state of the task.
btState :: Lens' BundleTask BundleTaskState
btState = lens _btState (\s a -> s { _btState = a })
-- | The Amazon S3 storage locations.
btStorage :: Lens' BundleTask Storage
btStorage = lens _btStorage (\s a -> s { _btStorage = a })
-- | The time of the most recent update for the task.
btUpdateTime :: Lens' BundleTask UTCTime
btUpdateTime = lens _btUpdateTime (\s a -> s { _btUpdateTime = a }) . _Time
instance FromXML BundleTask where
parseXML x = BundleTask
<$> x .@ "bundleId"
<*> x .@? "error"
<*> x .@ "instanceId"
<*> x .@ "progress"
<*> x .@ "startTime"
<*> x .@ "state"
<*> x .@ "storage"
<*> x .@ "updateTime"
instance ToQuery BundleTask where
toQuery BundleTask{..} = mconcat
[ "BundleId" =? _btBundleId
, "Error" =? _btBundleTaskError
, "InstanceId" =? _btInstanceId
, "Progress" =? _btProgress
, "StartTime" =? _btStartTime
, "State" =? _btState
, "Storage" =? _btStorage
, "UpdateTime" =? _btUpdateTime
]
data InstanceStatusEvent = InstanceStatusEvent
{ _iseCode :: Maybe EventCode
, _iseDescription :: Maybe Text
, _iseNotAfter :: Maybe ISO8601
, _iseNotBefore :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'InstanceStatusEvent' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iseCode' @::@ 'Maybe' 'EventCode'
--
-- * 'iseDescription' @::@ 'Maybe' 'Text'
--
-- * 'iseNotAfter' @::@ 'Maybe' 'UTCTime'
--
-- * 'iseNotBefore' @::@ 'Maybe' 'UTCTime'
--
instanceStatusEvent :: InstanceStatusEvent
instanceStatusEvent = InstanceStatusEvent
{ _iseCode = Nothing
, _iseDescription = Nothing
, _iseNotBefore = Nothing
, _iseNotAfter = Nothing
}
-- | The associated code of the event.
iseCode :: Lens' InstanceStatusEvent (Maybe EventCode)
iseCode = lens _iseCode (\s a -> s { _iseCode = a })
-- | A description of the event.
iseDescription :: Lens' InstanceStatusEvent (Maybe Text)
iseDescription = lens _iseDescription (\s a -> s { _iseDescription = a })
-- | The latest scheduled end time for the event.
iseNotAfter :: Lens' InstanceStatusEvent (Maybe UTCTime)
iseNotAfter = lens _iseNotAfter (\s a -> s { _iseNotAfter = a }) . mapping _Time
-- | The earliest scheduled start time for the event.
iseNotBefore :: Lens' InstanceStatusEvent (Maybe UTCTime)
iseNotBefore = lens _iseNotBefore (\s a -> s { _iseNotBefore = a }) . mapping _Time
instance FromXML InstanceStatusEvent where
parseXML x = InstanceStatusEvent
<$> x .@? "code"
<*> x .@? "description"
<*> x .@? "notAfter"
<*> x .@? "notBefore"
instance ToQuery InstanceStatusEvent where
toQuery InstanceStatusEvent{..} = mconcat
[ "Code" =? _iseCode
, "Description" =? _iseDescription
, "NotAfter" =? _iseNotAfter
, "NotBefore" =? _iseNotBefore
]
data InstanceType
= C1_Medium -- ^ c1.medium
| C1_XLarge -- ^ c1.xlarge
| C3_2XLarge -- ^ c3.2xlarge
| C3_4XLarge -- ^ c3.4xlarge
| C3_8XLarge -- ^ c3.8xlarge
| C3_Large -- ^ c3.large
| C3_XLarge -- ^ c3.xlarge
| C4_2XLarge -- ^ c4.2xlarge
| C4_4XLarge -- ^ c4.4xlarge
| C4_8XLarge -- ^ c4.8xlarge
| C4_Large -- ^ c4.large
| C4_XLarge -- ^ c4.xlarge
| CC1_4XLarge -- ^ cc1.4xlarge
| CC2_8XLarge -- ^ cc2.8xlarge
| CG1_4XLarge -- ^ cg1.4xlarge
| CR1_8XLarge -- ^ cr1.8xlarge
| D2_2XLarge -- ^ d2.2xlarge
| D2_4XLarge -- ^ d2.4xlarge
| D2_8XLarge -- ^ d2.8xlarge
| D2_XLarge -- ^ d2.xlarge
| G2_2XLarge -- ^ g2.2xlarge
| HI1_4XLarge -- ^ hi1.4xlarge
| HS1_8XLarge -- ^ hs1.8xlarge
| I2_2XLarge -- ^ i2.2xlarge
| I2_4XLarge -- ^ i2.4xlarge
| I2_8XLarge -- ^ i2.8xlarge
| I2_XLarge -- ^ i2.xlarge
| M1_Large -- ^ m1.large
| M1_Medium -- ^ m1.medium
| M1_Small -- ^ m1.small
| M1_XLarge -- ^ m1.xlarge
| M2_2XLarge -- ^ m2.2xlarge
| M2_4XLarge -- ^ m2.4xlarge
| M2_XLarge -- ^ m2.xlarge
| M3_2XLarge -- ^ m3.2xlarge
| M3_Large -- ^ m3.large
| M3_Medium -- ^ m3.medium
| M3_XLarge -- ^ m3.xlarge
| R3_2XLarge -- ^ r3.2xlarge
| R3_4XLarge -- ^ r3.4xlarge
| R3_8XLarge -- ^ r3.8xlarge
| R3_Large -- ^ r3.large
| R3_XLarge -- ^ r3.xlarge
| T1_Micro -- ^ t1.micro
| T2_Medium -- ^ t2.medium
| T2_Micro -- ^ t2.micro
| T2_Small -- ^ t2.small
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable InstanceType
instance FromText InstanceType where
parser = takeLowerText >>= \case
"c1.medium" -> pure C1_Medium
"c1.xlarge" -> pure C1_XLarge
"c3.2xlarge" -> pure C3_2XLarge
"c3.4xlarge" -> pure C3_4XLarge
"c3.8xlarge" -> pure C3_8XLarge
"c3.large" -> pure C3_Large
"c3.xlarge" -> pure C3_XLarge
"c4.2xlarge" -> pure C4_2XLarge
"c4.4xlarge" -> pure C4_4XLarge
"c4.8xlarge" -> pure C4_8XLarge
"c4.large" -> pure C4_Large
"c4.xlarge" -> pure C4_XLarge
"cc1.4xlarge" -> pure CC1_4XLarge
"cc2.8xlarge" -> pure CC2_8XLarge
"cg1.4xlarge" -> pure CG1_4XLarge
"cr1.8xlarge" -> pure CR1_8XLarge
"d2.2xlarge" -> pure D2_2XLarge
"d2.4xlarge" -> pure D2_4XLarge
"d2.8xlarge" -> pure D2_8XLarge
"d2.xlarge" -> pure D2_XLarge
"g2.2xlarge" -> pure G2_2XLarge
"hi1.4xlarge" -> pure HI1_4XLarge
"hs1.8xlarge" -> pure HS1_8XLarge
"i2.2xlarge" -> pure I2_2XLarge
"i2.4xlarge" -> pure I2_4XLarge
"i2.8xlarge" -> pure I2_8XLarge
"i2.xlarge" -> pure I2_XLarge
"m1.large" -> pure M1_Large
"m1.medium" -> pure M1_Medium
"m1.small" -> pure M1_Small
"m1.xlarge" -> pure M1_XLarge
"m2.2xlarge" -> pure M2_2XLarge
"m2.4xlarge" -> pure M2_4XLarge
"m2.xlarge" -> pure M2_XLarge
"m3.2xlarge" -> pure M3_2XLarge
"m3.large" -> pure M3_Large
"m3.medium" -> pure M3_Medium
"m3.xlarge" -> pure M3_XLarge
"r3.2xlarge" -> pure R3_2XLarge
"r3.4xlarge" -> pure R3_4XLarge
"r3.8xlarge" -> pure R3_8XLarge
"r3.large" -> pure R3_Large
"r3.xlarge" -> pure R3_XLarge
"t1.micro" -> pure T1_Micro
"t2.medium" -> pure T2_Medium
"t2.micro" -> pure T2_Micro
"t2.small" -> pure T2_Small
e -> fail $
"Failure parsing InstanceType from " ++ show e
instance ToText InstanceType where
toText = \case
C1_Medium -> "c1.medium"
C1_XLarge -> "c1.xlarge"
C3_2XLarge -> "c3.2xlarge"
C3_4XLarge -> "c3.4xlarge"
C3_8XLarge -> "c3.8xlarge"
C3_Large -> "c3.large"
C3_XLarge -> "c3.xlarge"
C4_2XLarge -> "c4.2xlarge"
C4_4XLarge -> "c4.4xlarge"
C4_8XLarge -> "c4.8xlarge"
C4_Large -> "c4.large"
C4_XLarge -> "c4.xlarge"
CC1_4XLarge -> "cc1.4xlarge"
CC2_8XLarge -> "cc2.8xlarge"
CG1_4XLarge -> "cg1.4xlarge"
CR1_8XLarge -> "cr1.8xlarge"
D2_2XLarge -> "d2.2xlarge"
D2_4XLarge -> "d2.4xlarge"
D2_8XLarge -> "d2.8xlarge"
D2_XLarge -> "d2.xlarge"
G2_2XLarge -> "g2.2xlarge"
HI1_4XLarge -> "hi1.4xlarge"
HS1_8XLarge -> "hs1.8xlarge"
I2_2XLarge -> "i2.2xlarge"
I2_4XLarge -> "i2.4xlarge"
I2_8XLarge -> "i2.8xlarge"
I2_XLarge -> "i2.xlarge"
M1_Large -> "m1.large"
M1_Medium -> "m1.medium"
M1_Small -> "m1.small"
M1_XLarge -> "m1.xlarge"
M2_2XLarge -> "m2.2xlarge"
M2_4XLarge -> "m2.4xlarge"
M2_XLarge -> "m2.xlarge"
M3_2XLarge -> "m3.2xlarge"
M3_Large -> "m3.large"
M3_Medium -> "m3.medium"
M3_XLarge -> "m3.xlarge"
R3_2XLarge -> "r3.2xlarge"
R3_4XLarge -> "r3.4xlarge"
R3_8XLarge -> "r3.8xlarge"
R3_Large -> "r3.large"
R3_XLarge -> "r3.xlarge"
T1_Micro -> "t1.micro"
T2_Medium -> "t2.medium"
T2_Micro -> "t2.micro"
T2_Small -> "t2.small"
instance ToByteString InstanceType
instance ToHeader InstanceType
instance ToQuery InstanceType
instance FromXML InstanceType where
parseXML = parseXMLText "InstanceType"
data Route = Route
{ _rDestinationCidrBlock :: Maybe Text
, _rGatewayId :: Maybe Text
, _rInstanceId :: Maybe Text
, _rInstanceOwnerId :: Maybe Text
, _rNetworkInterfaceId :: Maybe Text
, _rOrigin :: Maybe RouteOrigin
, _rState :: Maybe RouteState
, _rVpcPeeringConnectionId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'Route' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rDestinationCidrBlock' @::@ 'Maybe' 'Text'
--
-- * 'rGatewayId' @::@ 'Maybe' 'Text'
--
-- * 'rInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'rInstanceOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'rNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'rOrigin' @::@ 'Maybe' 'RouteOrigin'
--
-- * 'rState' @::@ 'Maybe' 'RouteState'
--
-- * 'rVpcPeeringConnectionId' @::@ 'Maybe' 'Text'
--
route :: Route
route = Route
{ _rDestinationCidrBlock = Nothing
, _rGatewayId = Nothing
, _rInstanceId = Nothing
, _rInstanceOwnerId = Nothing
, _rNetworkInterfaceId = Nothing
, _rVpcPeeringConnectionId = Nothing
, _rState = Nothing
, _rOrigin = Nothing
}
-- | The CIDR block used for the destination match.
rDestinationCidrBlock :: Lens' Route (Maybe Text)
rDestinationCidrBlock =
lens _rDestinationCidrBlock (\s a -> s { _rDestinationCidrBlock = a })
-- | The ID of a gateway attached to your VPC.
rGatewayId :: Lens' Route (Maybe Text)
rGatewayId = lens _rGatewayId (\s a -> s { _rGatewayId = a })
-- | The ID of a NAT instance in your VPC.
rInstanceId :: Lens' Route (Maybe Text)
rInstanceId = lens _rInstanceId (\s a -> s { _rInstanceId = a })
-- | The AWS account ID of the owner of the instance.
rInstanceOwnerId :: Lens' Route (Maybe Text)
rInstanceOwnerId = lens _rInstanceOwnerId (\s a -> s { _rInstanceOwnerId = a })
-- | The ID of the network interface.
rNetworkInterfaceId :: Lens' Route (Maybe Text)
rNetworkInterfaceId =
lens _rNetworkInterfaceId (\s a -> s { _rNetworkInterfaceId = a })
-- | Describes how the route was created.
--
-- 'CreateRouteTable' indicates that route was automatically created when the
-- route table was created. 'CreateRoute' indicates that the route was manually
-- added to the route table. 'EnableVgwRoutePropagation' indicates that the route
-- was propagated by route propagation.
rOrigin :: Lens' Route (Maybe RouteOrigin)
rOrigin = lens _rOrigin (\s a -> s { _rOrigin = a })
-- | The state of the route. The 'blackhole' state indicates that the route's target
-- isn't available (for example, the specified gateway isn't attached to the
-- VPC, or the specified NAT instance has been terminated).
rState :: Lens' Route (Maybe RouteState)
rState = lens _rState (\s a -> s { _rState = a })
-- | The ID of the VPC peering connection.
rVpcPeeringConnectionId :: Lens' Route (Maybe Text)
rVpcPeeringConnectionId =
lens _rVpcPeeringConnectionId (\s a -> s { _rVpcPeeringConnectionId = a })
instance FromXML Route where
parseXML x = Route
<$> x .@? "destinationCidrBlock"
<*> x .@? "gatewayId"
<*> x .@? "instanceId"
<*> x .@? "instanceOwnerId"
<*> x .@? "networkInterfaceId"
<*> x .@? "origin"
<*> x .@? "state"
<*> x .@? "vpcPeeringConnectionId"
instance ToQuery Route where
toQuery Route{..} = mconcat
[ "DestinationCidrBlock" =? _rDestinationCidrBlock
, "GatewayId" =? _rGatewayId
, "InstanceId" =? _rInstanceId
, "InstanceOwnerId" =? _rInstanceOwnerId
, "NetworkInterfaceId" =? _rNetworkInterfaceId
, "Origin" =? _rOrigin
, "State" =? _rState
, "VpcPeeringConnectionId" =? _rVpcPeeringConnectionId
]
data SpotDatafeedSubscription = SpotDatafeedSubscription
{ _sdsBucket :: Maybe Text
, _sdsFault :: Maybe SpotInstanceStateFault
, _sdsOwnerId :: Maybe Text
, _sdsPrefix :: Maybe Text
, _sdsState :: Maybe DatafeedSubscriptionState
} deriving (Eq, Read, Show)
-- | 'SpotDatafeedSubscription' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sdsBucket' @::@ 'Maybe' 'Text'
--
-- * 'sdsFault' @::@ 'Maybe' 'SpotInstanceStateFault'
--
-- * 'sdsOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'sdsPrefix' @::@ 'Maybe' 'Text'
--
-- * 'sdsState' @::@ 'Maybe' 'DatafeedSubscriptionState'
--
spotDatafeedSubscription :: SpotDatafeedSubscription
spotDatafeedSubscription = SpotDatafeedSubscription
{ _sdsOwnerId = Nothing
, _sdsBucket = Nothing
, _sdsPrefix = Nothing
, _sdsState = Nothing
, _sdsFault = Nothing
}
-- | The Amazon S3 bucket where the Spot Instance data feed is located.
sdsBucket :: Lens' SpotDatafeedSubscription (Maybe Text)
sdsBucket = lens _sdsBucket (\s a -> s { _sdsBucket = a })
-- | The fault codes for the Spot Instance request, if any.
sdsFault :: Lens' SpotDatafeedSubscription (Maybe SpotInstanceStateFault)
sdsFault = lens _sdsFault (\s a -> s { _sdsFault = a })
-- | The AWS account ID of the account.
sdsOwnerId :: Lens' SpotDatafeedSubscription (Maybe Text)
sdsOwnerId = lens _sdsOwnerId (\s a -> s { _sdsOwnerId = a })
-- | The prefix that is prepended to data feed files.
sdsPrefix :: Lens' SpotDatafeedSubscription (Maybe Text)
sdsPrefix = lens _sdsPrefix (\s a -> s { _sdsPrefix = a })
-- | The state of the Spot Instance data feed subscription.
sdsState :: Lens' SpotDatafeedSubscription (Maybe DatafeedSubscriptionState)
sdsState = lens _sdsState (\s a -> s { _sdsState = a })
instance FromXML SpotDatafeedSubscription where
parseXML x = SpotDatafeedSubscription
<$> x .@? "bucket"
<*> x .@? "fault"
<*> x .@? "ownerId"
<*> x .@? "prefix"
<*> x .@? "state"
instance ToQuery SpotDatafeedSubscription where
toQuery SpotDatafeedSubscription{..} = mconcat
[ "Bucket" =? _sdsBucket
, "Fault" =? _sdsFault
, "OwnerId" =? _sdsOwnerId
, "Prefix" =? _sdsPrefix
, "State" =? _sdsState
]
newtype Storage = Storage
{ _sS3 :: Maybe S3Storage
} deriving (Eq, Read, Show)
-- | 'Storage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sS3' @::@ 'Maybe' 'S3Storage'
--
storage :: Storage
storage = Storage
{ _sS3 = Nothing
}
-- | An Amazon S3 storage location.
sS3 :: Lens' Storage (Maybe S3Storage)
sS3 = lens _sS3 (\s a -> s { _sS3 = a })
instance FromXML Storage where
parseXML x = Storage
<$> x .@? "S3"
instance ToQuery Storage where
toQuery Storage{..} = mconcat
[ "S3" =? _sS3
]
data SecurityGroup = SecurityGroup
{ _sgDescription :: Text
, _sgGroupId :: Text
, _sgGroupName :: Text
, _sgIpPermissions :: List "item" IpPermission
, _sgIpPermissionsEgress :: List "item" IpPermission
, _sgOwnerId :: Text
, _sgTags :: List "item" Tag
, _sgVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'SecurityGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sgDescription' @::@ 'Text'
--
-- * 'sgGroupId' @::@ 'Text'
--
-- * 'sgGroupName' @::@ 'Text'
--
-- * 'sgIpPermissions' @::@ ['IpPermission']
--
-- * 'sgIpPermissionsEgress' @::@ ['IpPermission']
--
-- * 'sgOwnerId' @::@ 'Text'
--
-- * 'sgTags' @::@ ['Tag']
--
-- * 'sgVpcId' @::@ 'Maybe' 'Text'
--
securityGroup :: Text -- ^ 'sgOwnerId'
-> Text -- ^ 'sgGroupName'
-> Text -- ^ 'sgGroupId'
-> Text -- ^ 'sgDescription'
-> SecurityGroup
securityGroup p1 p2 p3 p4 = SecurityGroup
{ _sgOwnerId = p1
, _sgGroupName = p2
, _sgGroupId = p3
, _sgDescription = p4
, _sgIpPermissions = mempty
, _sgIpPermissionsEgress = mempty
, _sgVpcId = Nothing
, _sgTags = mempty
}
-- | A description of the security group.
sgDescription :: Lens' SecurityGroup Text
sgDescription = lens _sgDescription (\s a -> s { _sgDescription = a })
-- | The ID of the security group.
sgGroupId :: Lens' SecurityGroup Text
sgGroupId = lens _sgGroupId (\s a -> s { _sgGroupId = a })
-- | The name of the security group.
sgGroupName :: Lens' SecurityGroup Text
sgGroupName = lens _sgGroupName (\s a -> s { _sgGroupName = a })
-- | One or more inbound rules associated with the security group.
sgIpPermissions :: Lens' SecurityGroup [IpPermission]
sgIpPermissions = lens _sgIpPermissions (\s a -> s { _sgIpPermissions = a }) . _List
-- | [EC2-VPC] One or more outbound rules associated with the security group.
sgIpPermissionsEgress :: Lens' SecurityGroup [IpPermission]
sgIpPermissionsEgress =
lens _sgIpPermissionsEgress (\s a -> s { _sgIpPermissionsEgress = a })
. _List
-- | The AWS account ID of the owner of the security group.
sgOwnerId :: Lens' SecurityGroup Text
sgOwnerId = lens _sgOwnerId (\s a -> s { _sgOwnerId = a })
-- | Any tags assigned to the security group.
sgTags :: Lens' SecurityGroup [Tag]
sgTags = lens _sgTags (\s a -> s { _sgTags = a }) . _List
-- | [EC2-VPC] The ID of the VPC for the security group.
sgVpcId :: Lens' SecurityGroup (Maybe Text)
sgVpcId = lens _sgVpcId (\s a -> s { _sgVpcId = a })
instance FromXML SecurityGroup where
parseXML x = SecurityGroup
<$> x .@ "groupDescription"
<*> x .@ "groupId"
<*> x .@ "groupName"
<*> x .@? "ipPermissions" .!@ mempty
<*> x .@? "ipPermissionsEgress" .!@ mempty
<*> x .@ "ownerId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery SecurityGroup where
toQuery SecurityGroup{..} = mconcat
[ "GroupDescription" =? _sgDescription
, "GroupId" =? _sgGroupId
, "GroupName" =? _sgGroupName
, "IpPermissions" `toQueryList` _sgIpPermissions
, "IpPermissionsEgress" `toQueryList` _sgIpPermissionsEgress
, "OwnerId" =? _sgOwnerId
, "TagSet" `toQueryList` _sgTags
, "VpcId" =? _sgVpcId
]
data CancelSpotInstanceRequestState
= CSIRSActive -- ^ active
| CSIRSCancelled -- ^ cancelled
| CSIRSClosed -- ^ closed
| CSIRSCompleted -- ^ completed
| CSIRSOpen -- ^ open
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable CancelSpotInstanceRequestState
instance FromText CancelSpotInstanceRequestState where
parser = takeLowerText >>= \case
"active" -> pure CSIRSActive
"cancelled" -> pure CSIRSCancelled
"closed" -> pure CSIRSClosed
"completed" -> pure CSIRSCompleted
"open" -> pure CSIRSOpen
e -> fail $
"Failure parsing CancelSpotInstanceRequestState from " ++ show e
instance ToText CancelSpotInstanceRequestState where
toText = \case
CSIRSActive -> "active"
CSIRSCancelled -> "cancelled"
CSIRSClosed -> "closed"
CSIRSCompleted -> "completed"
CSIRSOpen -> "open"
instance ToByteString CancelSpotInstanceRequestState
instance ToHeader CancelSpotInstanceRequestState
instance ToQuery CancelSpotInstanceRequestState
instance FromXML CancelSpotInstanceRequestState where
parseXML = parseXMLText "CancelSpotInstanceRequestState"
data PlacementGroupState
= PGSAvailable -- ^ available
| PGSDeleted -- ^ deleted
| PGSDeleting -- ^ deleting
| PGSPending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable PlacementGroupState
instance FromText PlacementGroupState where
parser = takeLowerText >>= \case
"available" -> pure PGSAvailable
"deleted" -> pure PGSDeleted
"deleting" -> pure PGSDeleting
"pending" -> pure PGSPending
e -> fail $
"Failure parsing PlacementGroupState from " ++ show e
instance ToText PlacementGroupState where
toText = \case
PGSAvailable -> "available"
PGSDeleted -> "deleted"
PGSDeleting -> "deleting"
PGSPending -> "pending"
instance ToByteString PlacementGroupState
instance ToHeader PlacementGroupState
instance ToQuery PlacementGroupState
instance FromXML PlacementGroupState where
parseXML = parseXMLText "PlacementGroupState"
data ReservedInstancesModificationResult = ReservedInstancesModificationResult
{ _rimrReservedInstancesId :: Maybe Text
, _rimrTargetConfiguration :: Maybe ReservedInstancesConfiguration
} deriving (Eq, Read, Show)
-- | 'ReservedInstancesModificationResult' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rimrReservedInstancesId' @::@ 'Maybe' 'Text'
--
-- * 'rimrTargetConfiguration' @::@ 'Maybe' 'ReservedInstancesConfiguration'
--
reservedInstancesModificationResult :: ReservedInstancesModificationResult
reservedInstancesModificationResult = ReservedInstancesModificationResult
{ _rimrReservedInstancesId = Nothing
, _rimrTargetConfiguration = Nothing
}
-- | The ID for the Reserved Instances that were created as part of the
-- modification request. This field is only available when the modification is
-- fulfilled.
rimrReservedInstancesId :: Lens' ReservedInstancesModificationResult (Maybe Text)
rimrReservedInstancesId =
lens _rimrReservedInstancesId (\s a -> s { _rimrReservedInstancesId = a })
-- | The target Reserved Instances configurations supplied as part of the
-- modification request.
rimrTargetConfiguration :: Lens' ReservedInstancesModificationResult (Maybe ReservedInstancesConfiguration)
rimrTargetConfiguration =
lens _rimrTargetConfiguration (\s a -> s { _rimrTargetConfiguration = a })
instance FromXML ReservedInstancesModificationResult where
parseXML x = ReservedInstancesModificationResult
<$> x .@? "reservedInstancesId"
<*> x .@? "targetConfiguration"
instance ToQuery ReservedInstancesModificationResult where
toQuery ReservedInstancesModificationResult{..} = mconcat
[ "ReservedInstancesId" =? _rimrReservedInstancesId
, "TargetConfiguration" =? _rimrTargetConfiguration
]
data InstanceBlockDeviceMappingSpecification = InstanceBlockDeviceMappingSpecification
{ _ibdmsDeviceName :: Maybe Text
, _ibdmsEbs :: Maybe EbsInstanceBlockDeviceSpecification
, _ibdmsNoDevice :: Maybe Text
, _ibdmsVirtualName :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'InstanceBlockDeviceMappingSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ibdmsDeviceName' @::@ 'Maybe' 'Text'
--
-- * 'ibdmsEbs' @::@ 'Maybe' 'EbsInstanceBlockDeviceSpecification'
--
-- * 'ibdmsNoDevice' @::@ 'Maybe' 'Text'
--
-- * 'ibdmsVirtualName' @::@ 'Maybe' 'Text'
--
instanceBlockDeviceMappingSpecification :: InstanceBlockDeviceMappingSpecification
instanceBlockDeviceMappingSpecification = InstanceBlockDeviceMappingSpecification
{ _ibdmsDeviceName = Nothing
, _ibdmsEbs = Nothing
, _ibdmsVirtualName = Nothing
, _ibdmsNoDevice = Nothing
}
-- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh').
ibdmsDeviceName :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text)
ibdmsDeviceName = lens _ibdmsDeviceName (\s a -> s { _ibdmsDeviceName = a })
-- | Parameters used to automatically set up Amazon EBS volumes when the instance
-- is launched.
ibdmsEbs :: Lens' InstanceBlockDeviceMappingSpecification (Maybe EbsInstanceBlockDeviceSpecification)
ibdmsEbs = lens _ibdmsEbs (\s a -> s { _ibdmsEbs = a })
-- | suppress the specified device included in the block device mapping.
ibdmsNoDevice :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text)
ibdmsNoDevice = lens _ibdmsNoDevice (\s a -> s { _ibdmsNoDevice = a })
-- | The virtual device name.
ibdmsVirtualName :: Lens' InstanceBlockDeviceMappingSpecification (Maybe Text)
ibdmsVirtualName = lens _ibdmsVirtualName (\s a -> s { _ibdmsVirtualName = a })
instance FromXML InstanceBlockDeviceMappingSpecification where
parseXML x = InstanceBlockDeviceMappingSpecification
<$> x .@? "deviceName"
<*> x .@? "ebs"
<*> x .@? "noDevice"
<*> x .@? "virtualName"
instance ToQuery InstanceBlockDeviceMappingSpecification where
toQuery InstanceBlockDeviceMappingSpecification{..} = mconcat
[ "DeviceName" =? _ibdmsDeviceName
, "Ebs" =? _ibdmsEbs
, "NoDevice" =? _ibdmsNoDevice
, "VirtualName" =? _ibdmsVirtualName
]
data ExportEnvironment
= Citrix -- ^ citrix
| Microsoft -- ^ microsoft
| Vmware -- ^ vmware
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ExportEnvironment
instance FromText ExportEnvironment where
parser = takeLowerText >>= \case
"citrix" -> pure Citrix
"microsoft" -> pure Microsoft
"vmware" -> pure Vmware
e -> fail $
"Failure parsing ExportEnvironment from " ++ show e
instance ToText ExportEnvironment where
toText = \case
Citrix -> "citrix"
Microsoft -> "microsoft"
Vmware -> "vmware"
instance ToByteString ExportEnvironment
instance ToHeader ExportEnvironment
instance ToQuery ExportEnvironment
instance FromXML ExportEnvironment where
parseXML = parseXMLText "ExportEnvironment"
newtype UserData = UserData
{ _udData :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'UserData' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'udData' @::@ 'Maybe' 'Text'
--
userData :: UserData
userData = UserData
{ _udData = Nothing
}
udData :: Lens' UserData (Maybe Text)
udData = lens _udData (\s a -> s { _udData = a })
instance FromXML UserData where
parseXML x = UserData
<$> x .@? "data"
instance ToQuery UserData where
toQuery UserData{..} = mconcat
[ "Data" =? _udData
]
data VolumeAttachment = VolumeAttachment
{ _vaAttachTime :: Maybe ISO8601
, _vaDeleteOnTermination :: Maybe Bool
, _vaDevice :: Maybe Text
, _vaInstanceId :: Maybe Text
, _vaState :: Maybe VolumeAttachmentState
, _vaVolumeId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VolumeAttachment' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vaAttachTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'vaDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'vaDevice' @::@ 'Maybe' 'Text'
--
-- * 'vaInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'vaState' @::@ 'Maybe' 'VolumeAttachmentState'
--
-- * 'vaVolumeId' @::@ 'Maybe' 'Text'
--
volumeAttachment :: VolumeAttachment
volumeAttachment = VolumeAttachment
{ _vaVolumeId = Nothing
, _vaInstanceId = Nothing
, _vaDevice = Nothing
, _vaState = Nothing
, _vaAttachTime = Nothing
, _vaDeleteOnTermination = Nothing
}
-- | The time stamp when the attachment initiated.
vaAttachTime :: Lens' VolumeAttachment (Maybe UTCTime)
vaAttachTime = lens _vaAttachTime (\s a -> s { _vaAttachTime = a }) . mapping _Time
-- | Indicates whether the Amazon EBS volume is deleted on instance termination.
vaDeleteOnTermination :: Lens' VolumeAttachment (Maybe Bool)
vaDeleteOnTermination =
lens _vaDeleteOnTermination (\s a -> s { _vaDeleteOnTermination = a })
-- | The device name.
vaDevice :: Lens' VolumeAttachment (Maybe Text)
vaDevice = lens _vaDevice (\s a -> s { _vaDevice = a })
-- | The ID of the instance.
vaInstanceId :: Lens' VolumeAttachment (Maybe Text)
vaInstanceId = lens _vaInstanceId (\s a -> s { _vaInstanceId = a })
-- | The attachment state of the volume.
vaState :: Lens' VolumeAttachment (Maybe VolumeAttachmentState)
vaState = lens _vaState (\s a -> s { _vaState = a })
-- | The ID of the volume.
vaVolumeId :: Lens' VolumeAttachment (Maybe Text)
vaVolumeId = lens _vaVolumeId (\s a -> s { _vaVolumeId = a })
instance FromXML VolumeAttachment where
parseXML x = VolumeAttachment
<$> x .@? "attachTime"
<*> x .@? "deleteOnTermination"
<*> x .@? "device"
<*> x .@? "instanceId"
<*> x .@? "status"
<*> x .@? "volumeId"
instance ToQuery VolumeAttachment where
toQuery VolumeAttachment{..} = mconcat
[ "AttachTime" =? _vaAttachTime
, "DeleteOnTermination" =? _vaDeleteOnTermination
, "Device" =? _vaDevice
, "InstanceId" =? _vaInstanceId
, "Status" =? _vaState
, "VolumeId" =? _vaVolumeId
]
data CustomerGateway = CustomerGateway
{ _cgBgpAsn :: Text
, _cgCustomerGatewayId :: Text
, _cgIpAddress :: Text
, _cgState :: Text
, _cgTags :: List "item" Tag
, _cgType :: Text
} deriving (Eq, Read, Show)
-- | 'CustomerGateway' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cgBgpAsn' @::@ 'Text'
--
-- * 'cgCustomerGatewayId' @::@ 'Text'
--
-- * 'cgIpAddress' @::@ 'Text'
--
-- * 'cgState' @::@ 'Text'
--
-- * 'cgTags' @::@ ['Tag']
--
-- * 'cgType' @::@ 'Text'
--
customerGateway :: Text -- ^ 'cgCustomerGatewayId'
-> Text -- ^ 'cgState'
-> Text -- ^ 'cgType'
-> Text -- ^ 'cgIpAddress'
-> Text -- ^ 'cgBgpAsn'
-> CustomerGateway
customerGateway p1 p2 p3 p4 p5 = CustomerGateway
{ _cgCustomerGatewayId = p1
, _cgState = p2
, _cgType = p3
, _cgIpAddress = p4
, _cgBgpAsn = p5
, _cgTags = mempty
}
-- | The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number
-- (ASN).
cgBgpAsn :: Lens' CustomerGateway Text
cgBgpAsn = lens _cgBgpAsn (\s a -> s { _cgBgpAsn = a })
-- | The ID of the customer gateway.
cgCustomerGatewayId :: Lens' CustomerGateway Text
cgCustomerGatewayId =
lens _cgCustomerGatewayId (\s a -> s { _cgCustomerGatewayId = a })
-- | The Internet-routable IP address of the customer gateway's outside interface.
cgIpAddress :: Lens' CustomerGateway Text
cgIpAddress = lens _cgIpAddress (\s a -> s { _cgIpAddress = a })
-- | The current state of the customer gateway ('pending | available | deleting |deleted').
cgState :: Lens' CustomerGateway Text
cgState = lens _cgState (\s a -> s { _cgState = a })
-- | Any tags assigned to the customer gateway.
cgTags :: Lens' CustomerGateway [Tag]
cgTags = lens _cgTags (\s a -> s { _cgTags = a }) . _List
-- | The type of VPN connection the customer gateway supports ('ipsec.1').
cgType :: Lens' CustomerGateway Text
cgType = lens _cgType (\s a -> s { _cgType = a })
instance FromXML CustomerGateway where
parseXML x = CustomerGateway
<$> x .@ "bgpAsn"
<*> x .@ "customerGatewayId"
<*> x .@ "ipAddress"
<*> x .@ "state"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "type"
instance ToQuery CustomerGateway where
toQuery CustomerGateway{..} = mconcat
[ "BgpAsn" =? _cgBgpAsn
, "CustomerGatewayId" =? _cgCustomerGatewayId
, "IpAddress" =? _cgIpAddress
, "State" =? _cgState
, "TagSet" `toQueryList` _cgTags
, "Type" =? _cgType
]
data EbsInstanceBlockDevice = EbsInstanceBlockDevice
{ _eibdAttachTime :: Maybe ISO8601
, _eibdDeleteOnTermination :: Maybe Bool
, _eibdStatus :: Maybe AttachmentStatus
, _eibdVolumeId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'EbsInstanceBlockDevice' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'eibdAttachTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'eibdDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'eibdStatus' @::@ 'Maybe' 'AttachmentStatus'
--
-- * 'eibdVolumeId' @::@ 'Maybe' 'Text'
--
ebsInstanceBlockDevice :: EbsInstanceBlockDevice
ebsInstanceBlockDevice = EbsInstanceBlockDevice
{ _eibdVolumeId = Nothing
, _eibdStatus = Nothing
, _eibdAttachTime = Nothing
, _eibdDeleteOnTermination = Nothing
}
-- | The time stamp when the attachment initiated.
eibdAttachTime :: Lens' EbsInstanceBlockDevice (Maybe UTCTime)
eibdAttachTime = lens _eibdAttachTime (\s a -> s { _eibdAttachTime = a }) . mapping _Time
-- | Indicates whether the volume is deleted on instance termination.
eibdDeleteOnTermination :: Lens' EbsInstanceBlockDevice (Maybe Bool)
eibdDeleteOnTermination =
lens _eibdDeleteOnTermination (\s a -> s { _eibdDeleteOnTermination = a })
-- | The attachment state.
eibdStatus :: Lens' EbsInstanceBlockDevice (Maybe AttachmentStatus)
eibdStatus = lens _eibdStatus (\s a -> s { _eibdStatus = a })
-- | The ID of the Amazon EBS volume.
eibdVolumeId :: Lens' EbsInstanceBlockDevice (Maybe Text)
eibdVolumeId = lens _eibdVolumeId (\s a -> s { _eibdVolumeId = a })
instance FromXML EbsInstanceBlockDevice where
parseXML x = EbsInstanceBlockDevice
<$> x .@? "attachTime"
<*> x .@? "deleteOnTermination"
<*> x .@? "status"
<*> x .@? "volumeId"
instance ToQuery EbsInstanceBlockDevice where
toQuery EbsInstanceBlockDevice{..} = mconcat
[ "AttachTime" =? _eibdAttachTime
, "DeleteOnTermination" =? _eibdDeleteOnTermination
, "Status" =? _eibdStatus
, "VolumeId" =? _eibdVolumeId
]
data ShutdownBehavior
= Stop -- ^ stop
| Terminate -- ^ terminate
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ShutdownBehavior
instance FromText ShutdownBehavior where
parser = takeLowerText >>= \case
"stop" -> pure Stop
"terminate" -> pure Terminate
e -> fail $
"Failure parsing ShutdownBehavior from " ++ show e
instance ToText ShutdownBehavior where
toText = \case
Stop -> "stop"
Terminate -> "terminate"
instance ToByteString ShutdownBehavior
instance ToHeader ShutdownBehavior
instance ToQuery ShutdownBehavior
instance FromXML ShutdownBehavior where
parseXML = parseXMLText "ShutdownBehavior"
data DiskImageDescription = DiskImageDescription
{ _did1Checksum :: Maybe Text
, _did1Format :: DiskImageFormat
, _did1ImportManifestUrl :: Text
, _did1Size :: Integer
} deriving (Eq, Read, Show)
-- | 'DiskImageDescription' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'did1Checksum' @::@ 'Maybe' 'Text'
--
-- * 'did1Format' @::@ 'DiskImageFormat'
--
-- * 'did1ImportManifestUrl' @::@ 'Text'
--
-- * 'did1Size' @::@ 'Integer'
--
diskImageDescription :: DiskImageFormat -- ^ 'did1Format'
-> Integer -- ^ 'did1Size'
-> Text -- ^ 'did1ImportManifestUrl'
-> DiskImageDescription
diskImageDescription p1 p2 p3 = DiskImageDescription
{ _did1Format = p1
, _did1Size = p2
, _did1ImportManifestUrl = p3
, _did1Checksum = Nothing
}
-- | The checksum computed for the disk image.
did1Checksum :: Lens' DiskImageDescription (Maybe Text)
did1Checksum = lens _did1Checksum (\s a -> s { _did1Checksum = a })
-- | The disk image format.
did1Format :: Lens' DiskImageDescription DiskImageFormat
did1Format = lens _did1Format (\s a -> s { _did1Format = a })
-- | A presigned URL for the import manifest stored in Amazon S3. For information
-- about creating a presigned URL for an Amazon S3 object, read the "Query
-- String Request Authentication Alternative" section of the <http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html Authenticating RESTRequests> topic in the /Amazon Simple Storage Service Developer Guide/.
did1ImportManifestUrl :: Lens' DiskImageDescription Text
did1ImportManifestUrl =
lens _did1ImportManifestUrl (\s a -> s { _did1ImportManifestUrl = a })
-- | The size of the disk image.
did1Size :: Lens' DiskImageDescription Integer
did1Size = lens _did1Size (\s a -> s { _did1Size = a })
instance FromXML DiskImageDescription where
parseXML x = DiskImageDescription
<$> x .@? "checksum"
<*> x .@ "format"
<*> x .@ "importManifestUrl"
<*> x .@ "size"
instance ToQuery DiskImageDescription where
toQuery DiskImageDescription{..} = mconcat
[ "Checksum" =? _did1Checksum
, "Format" =? _did1Format
, "ImportManifestUrl" =? _did1ImportManifestUrl
, "Size" =? _did1Size
]
data DiskImageVolumeDescription = DiskImageVolumeDescription
{ _divdId :: Text
, _divdSize :: Maybe Integer
} deriving (Eq, Ord, Read, Show)
-- | 'DiskImageVolumeDescription' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'divdId' @::@ 'Text'
--
-- * 'divdSize' @::@ 'Maybe' 'Integer'
--
diskImageVolumeDescription :: Text -- ^ 'divdId'
-> DiskImageVolumeDescription
diskImageVolumeDescription p1 = DiskImageVolumeDescription
{ _divdId = p1
, _divdSize = Nothing
}
-- | The volume identifier.
divdId :: Lens' DiskImageVolumeDescription Text
divdId = lens _divdId (\s a -> s { _divdId = a })
-- | The size of the volume.
divdSize :: Lens' DiskImageVolumeDescription (Maybe Integer)
divdSize = lens _divdSize (\s a -> s { _divdSize = a })
instance FromXML DiskImageVolumeDescription where
parseXML x = DiskImageVolumeDescription
<$> x .@ "id"
<*> x .@? "size"
instance ToQuery DiskImageVolumeDescription where
toQuery DiskImageVolumeDescription{..} = mconcat
[ "Id" =? _divdId
, "Size" =? _divdSize
]
newtype Monitoring = Monitoring
{ _mState :: Maybe MonitoringState
} deriving (Eq, Read, Show)
-- | 'Monitoring' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mState' @::@ 'Maybe' 'MonitoringState'
--
monitoring :: Monitoring
monitoring = Monitoring
{ _mState = Nothing
}
-- | Indicates whether monitoring is enabled for the instance.
mState :: Lens' Monitoring (Maybe MonitoringState)
mState = lens _mState (\s a -> s { _mState = a })
instance FromXML Monitoring where
parseXML x = Monitoring
<$> x .@? "state"
instance ToQuery Monitoring where
toQuery Monitoring{..} = mconcat
[ "State" =? _mState
]
data SubnetState
= SSAvailable -- ^ available
| SSPending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SubnetState
instance FromText SubnetState where
parser = takeLowerText >>= \case
"available" -> pure SSAvailable
"pending" -> pure SSPending
e -> fail $
"Failure parsing SubnetState from " ++ show e
instance ToText SubnetState where
toText = \case
SSAvailable -> "available"
SSPending -> "pending"
instance ToByteString SubnetState
instance ToHeader SubnetState
instance ToQuery SubnetState
instance FromXML SubnetState where
parseXML = parseXMLText "SubnetState"
data ContainerFormat
= Ova -- ^ ova
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ContainerFormat
instance FromText ContainerFormat where
parser = takeLowerText >>= \case
"ova" -> pure Ova
e -> fail $
"Failure parsing ContainerFormat from " ++ show e
instance ToText ContainerFormat where
toText Ova = "ova"
instance ToByteString ContainerFormat
instance ToHeader ContainerFormat
instance ToQuery ContainerFormat
instance FromXML ContainerFormat where
parseXML = parseXMLText "ContainerFormat"
newtype AvailabilityZoneMessage = AvailabilityZoneMessage
{ _azmMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'AvailabilityZoneMessage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'azmMessage' @::@ 'Maybe' 'Text'
--
availabilityZoneMessage :: AvailabilityZoneMessage
availabilityZoneMessage = AvailabilityZoneMessage
{ _azmMessage = Nothing
}
-- | The message about the Availability Zone.
azmMessage :: Lens' AvailabilityZoneMessage (Maybe Text)
azmMessage = lens _azmMessage (\s a -> s { _azmMessage = a })
instance FromXML AvailabilityZoneMessage where
parseXML x = AvailabilityZoneMessage
<$> x .@? "message"
instance ToQuery AvailabilityZoneMessage where
toQuery AvailabilityZoneMessage{..} = mconcat
[ "Message" =? _azmMessage
]
data VpcAttachment = VpcAttachment
{ _va1State :: Maybe AttachmentStatus
, _va1VpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VpcAttachment' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'va1State' @::@ 'Maybe' 'AttachmentStatus'
--
-- * 'va1VpcId' @::@ 'Maybe' 'Text'
--
vpcAttachment :: VpcAttachment
vpcAttachment = VpcAttachment
{ _va1VpcId = Nothing
, _va1State = Nothing
}
-- | The current state of the attachment.
va1State :: Lens' VpcAttachment (Maybe AttachmentStatus)
va1State = lens _va1State (\s a -> s { _va1State = a })
-- | The ID of the VPC.
va1VpcId :: Lens' VpcAttachment (Maybe Text)
va1VpcId = lens _va1VpcId (\s a -> s { _va1VpcId = a })
instance FromXML VpcAttachment where
parseXML x = VpcAttachment
<$> x .@? "state"
<*> x .@? "vpcId"
instance ToQuery VpcAttachment where
toQuery VpcAttachment{..} = mconcat
[ "State" =? _va1State
, "VpcId" =? _va1VpcId
]
data InstanceBlockDeviceMapping = InstanceBlockDeviceMapping
{ _ibdmDeviceName :: Maybe Text
, _ibdmEbs :: Maybe EbsInstanceBlockDevice
} deriving (Eq, Read, Show)
-- | 'InstanceBlockDeviceMapping' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ibdmDeviceName' @::@ 'Maybe' 'Text'
--
-- * 'ibdmEbs' @::@ 'Maybe' 'EbsInstanceBlockDevice'
--
instanceBlockDeviceMapping :: InstanceBlockDeviceMapping
instanceBlockDeviceMapping = InstanceBlockDeviceMapping
{ _ibdmDeviceName = Nothing
, _ibdmEbs = Nothing
}
-- | The device name exposed to the instance (for example, '/dev/sdh' or 'xvdh').
ibdmDeviceName :: Lens' InstanceBlockDeviceMapping (Maybe Text)
ibdmDeviceName = lens _ibdmDeviceName (\s a -> s { _ibdmDeviceName = a })
-- | Parameters used to automatically set up Amazon EBS volumes when the instance
-- is launched.
ibdmEbs :: Lens' InstanceBlockDeviceMapping (Maybe EbsInstanceBlockDevice)
ibdmEbs = lens _ibdmEbs (\s a -> s { _ibdmEbs = a })
instance FromXML InstanceBlockDeviceMapping where
parseXML x = InstanceBlockDeviceMapping
<$> x .@? "deviceName"
<*> x .@? "ebs"
instance ToQuery InstanceBlockDeviceMapping where
toQuery InstanceBlockDeviceMapping{..} = mconcat
[ "DeviceName" =? _ibdmDeviceName
, "Ebs" =? _ibdmEbs
]
data StatusType
= Failed -- ^ failed
| InsufficientData -- ^ insufficient-data
| Passed -- ^ passed
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable StatusType
instance FromText StatusType where
parser = takeLowerText >>= \case
"failed" -> pure Failed
"insufficient-data" -> pure InsufficientData
"passed" -> pure Passed
e -> fail $
"Failure parsing StatusType from " ++ show e
instance ToText StatusType where
toText = \case
Failed -> "failed"
InsufficientData -> "insufficient-data"
Passed -> "passed"
instance ToByteString StatusType
instance ToHeader StatusType
instance ToQuery StatusType
instance FromXML StatusType where
parseXML = parseXMLText "StatusType"
data ExportToS3TaskSpecification = ExportToS3TaskSpecification
{ _etstsContainerFormat :: Maybe ContainerFormat
, _etstsDiskImageFormat :: Maybe DiskImageFormat
, _etstsS3Bucket :: Maybe Text
, _etstsS3Prefix :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ExportToS3TaskSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'etstsContainerFormat' @::@ 'Maybe' 'ContainerFormat'
--
-- * 'etstsDiskImageFormat' @::@ 'Maybe' 'DiskImageFormat'
--
-- * 'etstsS3Bucket' @::@ 'Maybe' 'Text'
--
-- * 'etstsS3Prefix' @::@ 'Maybe' 'Text'
--
exportToS3TaskSpecification :: ExportToS3TaskSpecification
exportToS3TaskSpecification = ExportToS3TaskSpecification
{ _etstsDiskImageFormat = Nothing
, _etstsContainerFormat = Nothing
, _etstsS3Bucket = Nothing
, _etstsS3Prefix = Nothing
}
etstsContainerFormat :: Lens' ExportToS3TaskSpecification (Maybe ContainerFormat)
etstsContainerFormat =
lens _etstsContainerFormat (\s a -> s { _etstsContainerFormat = a })
etstsDiskImageFormat :: Lens' ExportToS3TaskSpecification (Maybe DiskImageFormat)
etstsDiskImageFormat =
lens _etstsDiskImageFormat (\s a -> s { _etstsDiskImageFormat = a })
etstsS3Bucket :: Lens' ExportToS3TaskSpecification (Maybe Text)
etstsS3Bucket = lens _etstsS3Bucket (\s a -> s { _etstsS3Bucket = a })
-- | The image is written to a single object in the Amazon S3 bucket at the S3 key
-- s3prefix + exportTaskId + '.' + diskImageFormat.
etstsS3Prefix :: Lens' ExportToS3TaskSpecification (Maybe Text)
etstsS3Prefix = lens _etstsS3Prefix (\s a -> s { _etstsS3Prefix = a })
instance FromXML ExportToS3TaskSpecification where
parseXML x = ExportToS3TaskSpecification
<$> x .@? "containerFormat"
<*> x .@? "diskImageFormat"
<*> x .@? "s3Bucket"
<*> x .@? "s3Prefix"
instance ToQuery ExportToS3TaskSpecification where
toQuery ExportToS3TaskSpecification{..} = mconcat
[ "ContainerFormat" =? _etstsContainerFormat
, "DiskImageFormat" =? _etstsDiskImageFormat
, "S3Bucket" =? _etstsS3Bucket
, "S3Prefix" =? _etstsS3Prefix
]
data NetworkInterfaceAttribute
= Attachment -- ^ attachment
| Description -- ^ description
| GroupSet -- ^ groupSet
| SourceDestCheck -- ^ sourceDestCheck
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable NetworkInterfaceAttribute
instance FromText NetworkInterfaceAttribute where
parser = takeLowerText >>= \case
"attachment" -> pure Attachment
"description" -> pure Description
"groupset" -> pure GroupSet
"sourcedestcheck" -> pure SourceDestCheck
e -> fail $
"Failure parsing NetworkInterfaceAttribute from " ++ show e
instance ToText NetworkInterfaceAttribute where
toText = \case
Attachment -> "attachment"
Description -> "description"
GroupSet -> "groupSet"
SourceDestCheck -> "sourceDestCheck"
instance ToByteString NetworkInterfaceAttribute
instance ToHeader NetworkInterfaceAttribute
instance ToQuery NetworkInterfaceAttribute
instance FromXML NetworkInterfaceAttribute where
parseXML = parseXMLText "NetworkInterfaceAttribute"
data ImageTypeValues
= Kernel -- ^ kernel
| Machine -- ^ machine
| Ramdisk -- ^ ramdisk
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ImageTypeValues
instance FromText ImageTypeValues where
parser = takeLowerText >>= \case
"kernel" -> pure Kernel
"machine" -> pure Machine
"ramdisk" -> pure Ramdisk
e -> fail $
"Failure parsing ImageTypeValues from " ++ show e
instance ToText ImageTypeValues where
toText = \case
Kernel -> "kernel"
Machine -> "machine"
Ramdisk -> "ramdisk"
instance ToByteString ImageTypeValues
instance ToHeader ImageTypeValues
instance ToQuery ImageTypeValues
instance FromXML ImageTypeValues where
parseXML = parseXMLText "ImageTypeValues"
data InstanceExportDetails = InstanceExportDetails
{ _iedInstanceId :: Maybe Text
, _iedTargetEnvironment :: Maybe ExportEnvironment
} deriving (Eq, Read, Show)
-- | 'InstanceExportDetails' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iedInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'iedTargetEnvironment' @::@ 'Maybe' 'ExportEnvironment'
--
instanceExportDetails :: InstanceExportDetails
instanceExportDetails = InstanceExportDetails
{ _iedInstanceId = Nothing
, _iedTargetEnvironment = Nothing
}
-- | The ID of the resource being exported.
iedInstanceId :: Lens' InstanceExportDetails (Maybe Text)
iedInstanceId = lens _iedInstanceId (\s a -> s { _iedInstanceId = a })
-- | The target virtualization environment.
iedTargetEnvironment :: Lens' InstanceExportDetails (Maybe ExportEnvironment)
iedTargetEnvironment =
lens _iedTargetEnvironment (\s a -> s { _iedTargetEnvironment = a })
instance FromXML InstanceExportDetails where
parseXML x = InstanceExportDetails
<$> x .@? "instanceId"
<*> x .@? "targetEnvironment"
instance ToQuery InstanceExportDetails where
toQuery InstanceExportDetails{..} = mconcat
[ "InstanceId" =? _iedInstanceId
, "TargetEnvironment" =? _iedTargetEnvironment
]
data SnapshotAttributeName
= SANCreateVolumePermission -- ^ createVolumePermission
| SANProductCodes -- ^ productCodes
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SnapshotAttributeName
instance FromText SnapshotAttributeName where
parser = takeLowerText >>= \case
"createvolumepermission" -> pure SANCreateVolumePermission
"productcodes" -> pure SANProductCodes
e -> fail $
"Failure parsing SnapshotAttributeName from " ++ show e
instance ToText SnapshotAttributeName where
toText = \case
SANCreateVolumePermission -> "createVolumePermission"
SANProductCodes -> "productCodes"
instance ToByteString SnapshotAttributeName
instance ToHeader SnapshotAttributeName
instance ToQuery SnapshotAttributeName
instance FromXML SnapshotAttributeName where
parseXML = parseXMLText "SnapshotAttributeName"
data AvailabilityZone = AvailabilityZone
{ _azMessages :: List "item" AvailabilityZoneMessage
, _azRegionName :: Maybe Text
, _azState :: Maybe AvailabilityZoneState
, _azZoneName :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'AvailabilityZone' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'azMessages' @::@ ['AvailabilityZoneMessage']
--
-- * 'azRegionName' @::@ 'Maybe' 'Text'
--
-- * 'azState' @::@ 'Maybe' 'AvailabilityZoneState'
--
-- * 'azZoneName' @::@ 'Maybe' 'Text'
--
availabilityZone :: AvailabilityZone
availabilityZone = AvailabilityZone
{ _azZoneName = Nothing
, _azState = Nothing
, _azRegionName = Nothing
, _azMessages = mempty
}
-- | Any messages about the Availability Zone.
azMessages :: Lens' AvailabilityZone [AvailabilityZoneMessage]
azMessages = lens _azMessages (\s a -> s { _azMessages = a }) . _List
-- | The name of the region.
azRegionName :: Lens' AvailabilityZone (Maybe Text)
azRegionName = lens _azRegionName (\s a -> s { _azRegionName = a })
-- | The state of the Availability Zone ('available' | 'impaired' | 'unavailable').
azState :: Lens' AvailabilityZone (Maybe AvailabilityZoneState)
azState = lens _azState (\s a -> s { _azState = a })
-- | The name of the Availability Zone.
azZoneName :: Lens' AvailabilityZone (Maybe Text)
azZoneName = lens _azZoneName (\s a -> s { _azZoneName = a })
instance FromXML AvailabilityZone where
parseXML x = AvailabilityZone
<$> x .@? "messageSet" .!@ mempty
<*> x .@? "regionName"
<*> x .@? "zoneState"
<*> x .@? "zoneName"
instance ToQuery AvailabilityZone where
toQuery AvailabilityZone{..} = mconcat
[ "MessageSet" `toQueryList` _azMessages
, "RegionName" =? _azRegionName
, "ZoneState" =? _azState
, "ZoneName" =? _azZoneName
]
data VpnState
= VpnStateAvailable -- ^ available
| VpnStateDeleted -- ^ deleted
| VpnStateDeleting -- ^ deleting
| VpnStatePending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VpnState
instance FromText VpnState where
parser = takeLowerText >>= \case
"available" -> pure VpnStateAvailable
"deleted" -> pure VpnStateDeleted
"deleting" -> pure VpnStateDeleting
"pending" -> pure VpnStatePending
e -> fail $
"Failure parsing VpnState from " ++ show e
instance ToText VpnState where
toText = \case
VpnStateAvailable -> "available"
VpnStateDeleted -> "deleted"
VpnStateDeleting -> "deleting"
VpnStatePending -> "pending"
instance ToByteString VpnState
instance ToHeader VpnState
instance ToQuery VpnState
instance FromXML VpnState where
parseXML = parseXMLText "VpnState"
data RouteTable = RouteTable
{ _rtAssociations :: List "item" RouteTableAssociation
, _rtPropagatingVgws :: List "item" PropagatingVgw
, _rtRouteTableId :: Maybe Text
, _rtRoutes :: List "item" Route
, _rtTags :: List "item" Tag
, _rtVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'RouteTable' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rtAssociations' @::@ ['RouteTableAssociation']
--
-- * 'rtPropagatingVgws' @::@ ['PropagatingVgw']
--
-- * 'rtRouteTableId' @::@ 'Maybe' 'Text'
--
-- * 'rtRoutes' @::@ ['Route']
--
-- * 'rtTags' @::@ ['Tag']
--
-- * 'rtVpcId' @::@ 'Maybe' 'Text'
--
routeTable :: RouteTable
routeTable = RouteTable
{ _rtRouteTableId = Nothing
, _rtVpcId = Nothing
, _rtRoutes = mempty
, _rtAssociations = mempty
, _rtTags = mempty
, _rtPropagatingVgws = mempty
}
-- | The associations between the route table and one or more subnets.
rtAssociations :: Lens' RouteTable [RouteTableAssociation]
rtAssociations = lens _rtAssociations (\s a -> s { _rtAssociations = a }) . _List
-- | Any virtual private gateway (VGW) propagating routes.
rtPropagatingVgws :: Lens' RouteTable [PropagatingVgw]
rtPropagatingVgws =
lens _rtPropagatingVgws (\s a -> s { _rtPropagatingVgws = a })
. _List
-- | The ID of the route table.
rtRouteTableId :: Lens' RouteTable (Maybe Text)
rtRouteTableId = lens _rtRouteTableId (\s a -> s { _rtRouteTableId = a })
-- | The routes in the route table.
rtRoutes :: Lens' RouteTable [Route]
rtRoutes = lens _rtRoutes (\s a -> s { _rtRoutes = a }) . _List
-- | Any tags assigned to the route table.
rtTags :: Lens' RouteTable [Tag]
rtTags = lens _rtTags (\s a -> s { _rtTags = a }) . _List
-- | The ID of the VPC.
rtVpcId :: Lens' RouteTable (Maybe Text)
rtVpcId = lens _rtVpcId (\s a -> s { _rtVpcId = a })
instance FromXML RouteTable where
parseXML x = RouteTable
<$> x .@? "associationSet" .!@ mempty
<*> x .@? "propagatingVgwSet" .!@ mempty
<*> x .@? "routeTableId"
<*> x .@? "routeSet" .!@ mempty
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery RouteTable where
toQuery RouteTable{..} = mconcat
[ "AssociationSet" `toQueryList` _rtAssociations
, "PropagatingVgwSet" `toQueryList` _rtPropagatingVgws
, "RouteTableId" =? _rtRouteTableId
, "RouteSet" `toQueryList` _rtRoutes
, "TagSet" `toQueryList` _rtTags
, "VpcId" =? _rtVpcId
]
data HypervisorType
= Ovm -- ^ ovm
| Xen -- ^ xen
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable HypervisorType
instance FromText HypervisorType where
parser = takeLowerText >>= \case
"ovm" -> pure Ovm
"xen" -> pure Xen
e -> fail $
"Failure parsing HypervisorType from " ++ show e
instance ToText HypervisorType where
toText = \case
Ovm -> "ovm"
Xen -> "xen"
instance ToByteString HypervisorType
instance ToHeader HypervisorType
instance ToQuery HypervisorType
instance FromXML HypervisorType where
parseXML = parseXMLText "HypervisorType"
data InstanceStatusDetails = InstanceStatusDetails
{ _isdImpairedSince :: Maybe ISO8601
, _isdName :: Maybe StatusName
, _isdStatus :: Maybe StatusType
} deriving (Eq, Read, Show)
-- | 'InstanceStatusDetails' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'isdImpairedSince' @::@ 'Maybe' 'UTCTime'
--
-- * 'isdName' @::@ 'Maybe' 'StatusName'
--
-- * 'isdStatus' @::@ 'Maybe' 'StatusType'
--
instanceStatusDetails :: InstanceStatusDetails
instanceStatusDetails = InstanceStatusDetails
{ _isdName = Nothing
, _isdStatus = Nothing
, _isdImpairedSince = Nothing
}
-- | The time when a status check failed. For an instance that was launched and
-- impaired, this is the time when the instance was launched.
isdImpairedSince :: Lens' InstanceStatusDetails (Maybe UTCTime)
isdImpairedSince = lens _isdImpairedSince (\s a -> s { _isdImpairedSince = a }) . mapping _Time
-- | The type of instance status.
isdName :: Lens' InstanceStatusDetails (Maybe StatusName)
isdName = lens _isdName (\s a -> s { _isdName = a })
-- | The status.
isdStatus :: Lens' InstanceStatusDetails (Maybe StatusType)
isdStatus = lens _isdStatus (\s a -> s { _isdStatus = a })
instance FromXML InstanceStatusDetails where
parseXML x = InstanceStatusDetails
<$> x .@? "impairedSince"
<*> x .@? "name"
<*> x .@? "status"
instance ToQuery InstanceStatusDetails where
toQuery InstanceStatusDetails{..} = mconcat
[ "ImpairedSince" =? _isdImpairedSince
, "Name" =? _isdName
, "Status" =? _isdStatus
]
data IamInstanceProfile = IamInstanceProfile
{ _iipArn :: Maybe Text
, _iipId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'IamInstanceProfile' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iipArn' @::@ 'Maybe' 'Text'
--
-- * 'iipId' @::@ 'Maybe' 'Text'
--
iamInstanceProfile :: IamInstanceProfile
iamInstanceProfile = IamInstanceProfile
{ _iipArn = Nothing
, _iipId = Nothing
}
-- | The Amazon Resource Name (ARN) of the instance profile.
iipArn :: Lens' IamInstanceProfile (Maybe Text)
iipArn = lens _iipArn (\s a -> s { _iipArn = a })
-- | The ID of the instance profile.
iipId :: Lens' IamInstanceProfile (Maybe Text)
iipId = lens _iipId (\s a -> s { _iipId = a })
instance FromXML IamInstanceProfile where
parseXML x = IamInstanceProfile
<$> x .@? "arn"
<*> x .@? "id"
instance ToQuery IamInstanceProfile where
toQuery IamInstanceProfile{..} = mconcat
[ "Arn" =? _iipArn
, "Id" =? _iipId
]
data InternetGatewayAttachment = InternetGatewayAttachment
{ _igaState :: AttachmentStatus
, _igaVpcId :: Text
} deriving (Eq, Read, Show)
-- | 'InternetGatewayAttachment' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'igaState' @::@ 'AttachmentStatus'
--
-- * 'igaVpcId' @::@ 'Text'
--
internetGatewayAttachment :: Text -- ^ 'igaVpcId'
-> AttachmentStatus -- ^ 'igaState'
-> InternetGatewayAttachment
internetGatewayAttachment p1 p2 = InternetGatewayAttachment
{ _igaVpcId = p1
, _igaState = p2
}
-- | The current state of the attachment.
igaState :: Lens' InternetGatewayAttachment AttachmentStatus
igaState = lens _igaState (\s a -> s { _igaState = a })
-- | The ID of the VPC.
igaVpcId :: Lens' InternetGatewayAttachment Text
igaVpcId = lens _igaVpcId (\s a -> s { _igaVpcId = a })
instance FromXML InternetGatewayAttachment where
parseXML x = InternetGatewayAttachment
<$> x .@ "state"
<*> x .@ "vpcId"
instance ToQuery InternetGatewayAttachment where
toQuery InternetGatewayAttachment{..} = mconcat
[ "State" =? _igaState
, "VpcId" =? _igaVpcId
]
data ReservedInstanceState
= RISActive -- ^ active
| RISPaymentFailed -- ^ payment-failed
| RISPaymentPending -- ^ payment-pending
| RISRetired -- ^ retired
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ReservedInstanceState
instance FromText ReservedInstanceState where
parser = takeLowerText >>= \case
"active" -> pure RISActive
"payment-failed" -> pure RISPaymentFailed
"payment-pending" -> pure RISPaymentPending
"retired" -> pure RISRetired
e -> fail $
"Failure parsing ReservedInstanceState from " ++ show e
instance ToText ReservedInstanceState where
toText = \case
RISActive -> "active"
RISPaymentFailed -> "payment-failed"
RISPaymentPending -> "payment-pending"
RISRetired -> "retired"
instance ToByteString ReservedInstanceState
instance ToHeader ReservedInstanceState
instance ToQuery ReservedInstanceState
instance FromXML ReservedInstanceState where
parseXML = parseXMLText "ReservedInstanceState"
data InstanceAttributeName
= IANInstanceBlockDeviceMapping -- ^ blockDeviceMapping
| IANInstanceDisableApiTermination -- ^ disableApiTermination
| IANInstanceEbsOptimized -- ^ ebsOptimized
| IANInstanceGroupSet -- ^ groupSet
| IANInstanceInstanceInitiatedShutdownBehavior -- ^ instanceInitiatedShutdownBehavior
| IANInstanceInstanceType -- ^ instanceType
| IANInstanceKernel -- ^ kernel
| IANInstanceProductCodes -- ^ productCodes
| IANInstanceRamdisk -- ^ ramdisk
| IANInstanceRootDeviceName -- ^ rootDeviceName
| IANInstanceSourceDestCheck -- ^ sourceDestCheck
| IANInstanceSriovNetSupport -- ^ sriovNetSupport
| IANInstanceUserData -- ^ userData
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable InstanceAttributeName
instance FromText InstanceAttributeName where
parser = takeLowerText >>= \case
"blockdevicemapping" -> pure IANInstanceBlockDeviceMapping
"disableapitermination" -> pure IANInstanceDisableApiTermination
"ebsoptimized" -> pure IANInstanceEbsOptimized
"groupset" -> pure IANInstanceGroupSet
"instanceinitiatedshutdownbehavior" -> pure IANInstanceInstanceInitiatedShutdownBehavior
"instancetype" -> pure IANInstanceInstanceType
"kernel" -> pure IANInstanceKernel
"productcodes" -> pure IANInstanceProductCodes
"ramdisk" -> pure IANInstanceRamdisk
"rootdevicename" -> pure IANInstanceRootDeviceName
"sourcedestcheck" -> pure IANInstanceSourceDestCheck
"sriovnetsupport" -> pure IANInstanceSriovNetSupport
"userdata" -> pure IANInstanceUserData
e -> fail $
"Failure parsing InstanceAttributeName from " ++ show e
instance ToText InstanceAttributeName where
toText = \case
IANInstanceBlockDeviceMapping -> "blockDeviceMapping"
IANInstanceDisableApiTermination -> "disableApiTermination"
IANInstanceEbsOptimized -> "ebsOptimized"
IANInstanceGroupSet -> "groupSet"
IANInstanceInstanceInitiatedShutdownBehavior -> "instanceInitiatedShutdownBehavior"
IANInstanceInstanceType -> "instanceType"
IANInstanceKernel -> "kernel"
IANInstanceProductCodes -> "productCodes"
IANInstanceRamdisk -> "ramdisk"
IANInstanceRootDeviceName -> "rootDeviceName"
IANInstanceSourceDestCheck -> "sourceDestCheck"
IANInstanceSriovNetSupport -> "sriovNetSupport"
IANInstanceUserData -> "userData"
instance ToByteString InstanceAttributeName
instance ToHeader InstanceAttributeName
instance ToQuery InstanceAttributeName
instance FromXML InstanceAttributeName where
parseXML = parseXMLText "InstanceAttributeName"
data IpPermission = IpPermission
{ _ipFromPort :: Maybe Int
, _ipIpProtocol :: Text
, _ipIpRanges :: List "item" IpRange
, _ipToPort :: Maybe Int
, _ipUserIdGroupPairs :: List "item" UserIdGroupPair
} deriving (Eq, Read, Show)
-- | 'IpPermission' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ipFromPort' @::@ 'Maybe' 'Int'
--
-- * 'ipIpProtocol' @::@ 'Text'
--
-- * 'ipIpRanges' @::@ ['IpRange']
--
-- * 'ipToPort' @::@ 'Maybe' 'Int'
--
-- * 'ipUserIdGroupPairs' @::@ ['UserIdGroupPair']
--
ipPermission :: Text -- ^ 'ipIpProtocol'
-> IpPermission
ipPermission p1 = IpPermission
{ _ipIpProtocol = p1
, _ipFromPort = Nothing
, _ipToPort = Nothing
, _ipUserIdGroupPairs = mempty
, _ipIpRanges = mempty
}
-- | The start of port range for the TCP and UDP protocols, or an ICMP type
-- number. A value of '-1' indicates all ICMP types.
ipFromPort :: Lens' IpPermission (Maybe Int)
ipFromPort = lens _ipFromPort (\s a -> s { _ipFromPort = a })
-- | The protocol.
--
-- When you call 'DescribeSecurityGroups', the protocol value returned is the
-- number. Exception: For TCP, UDP, and ICMP, the value returned is the name
-- (for example, 'tcp', 'udp', or 'icmp'). For a list of protocol numbers, see <http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml Protocol Numbers>. (VPC only) When you call 'AuthorizeSecurityGroupIngress', you can use '-1' to
-- specify all.
ipIpProtocol :: Lens' IpPermission Text
ipIpProtocol = lens _ipIpProtocol (\s a -> s { _ipIpProtocol = a })
-- | One or more IP ranges.
ipIpRanges :: Lens' IpPermission [IpRange]
ipIpRanges = lens _ipIpRanges (\s a -> s { _ipIpRanges = a }) . _List
-- | The end of port range for the TCP and UDP protocols, or an ICMP code. A value
-- of '-1' indicates all ICMP codes for the specified ICMP type.
ipToPort :: Lens' IpPermission (Maybe Int)
ipToPort = lens _ipToPort (\s a -> s { _ipToPort = a })
-- | One or more security group and AWS account ID pairs.
ipUserIdGroupPairs :: Lens' IpPermission [UserIdGroupPair]
ipUserIdGroupPairs =
lens _ipUserIdGroupPairs (\s a -> s { _ipUserIdGroupPairs = a })
. _List
instance FromXML IpPermission where
parseXML x = IpPermission
<$> x .@? "fromPort"
<*> x .@ "ipProtocol"
<*> x .@? "ipRanges" .!@ mempty
<*> x .@? "toPort"
<*> x .@? "groups" .!@ mempty
instance ToQuery IpPermission where
toQuery IpPermission{..} = mconcat
[ "FromPort" =? _ipFromPort
, "IpProtocol" =? _ipIpProtocol
, "IpRanges" `toQueryList` _ipIpRanges
, "ToPort" =? _ipToPort
, "Groups" `toQueryList` _ipUserIdGroupPairs
]
data ConversionTaskState
= CTSActive -- ^ active
| CTSCancelled -- ^ cancelled
| CTSCancelling -- ^ cancelling
| CTSCompleted -- ^ completed
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ConversionTaskState
instance FromText ConversionTaskState where
parser = takeLowerText >>= \case
"active" -> pure CTSActive
"cancelled" -> pure CTSCancelled
"cancelling" -> pure CTSCancelling
"completed" -> pure CTSCompleted
e -> fail $
"Failure parsing ConversionTaskState from " ++ show e
instance ToText ConversionTaskState where
toText = \case
CTSActive -> "active"
CTSCancelled -> "cancelled"
CTSCancelling -> "cancelling"
CTSCompleted -> "completed"
instance ToByteString ConversionTaskState
instance ToHeader ConversionTaskState
instance ToQuery ConversionTaskState
instance FromXML ConversionTaskState where
parseXML = parseXMLText "ConversionTaskState"
data DiskImage = DiskImage
{ _diDescription :: Maybe Text
, _diImage :: Maybe DiskImageDetail
, _diVolume :: Maybe VolumeDetail
} deriving (Eq, Read, Show)
-- | 'DiskImage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'diDescription' @::@ 'Maybe' 'Text'
--
-- * 'diImage' @::@ 'Maybe' 'DiskImageDetail'
--
-- * 'diVolume' @::@ 'Maybe' 'VolumeDetail'
--
diskImage :: DiskImage
diskImage = DiskImage
{ _diImage = Nothing
, _diDescription = Nothing
, _diVolume = Nothing
}
diDescription :: Lens' DiskImage (Maybe Text)
diDescription = lens _diDescription (\s a -> s { _diDescription = a })
diImage :: Lens' DiskImage (Maybe DiskImageDetail)
diImage = lens _diImage (\s a -> s { _diImage = a })
diVolume :: Lens' DiskImage (Maybe VolumeDetail)
diVolume = lens _diVolume (\s a -> s { _diVolume = a })
instance FromXML DiskImage where
parseXML x = DiskImage
<$> x .@? "Description"
<*> x .@? "Image"
<*> x .@? "Volume"
instance ToQuery DiskImage where
toQuery DiskImage{..} = mconcat
[ "Description" =? _diDescription
, "Image" =? _diImage
, "Volume" =? _diVolume
]
data Tenancy
= Dedicated -- ^ dedicated
| Default' -- ^ default
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable Tenancy
instance FromText Tenancy where
parser = takeLowerText >>= \case
"dedicated" -> pure Dedicated
"default" -> pure Default'
e -> fail $
"Failure parsing Tenancy from " ++ show e
instance ToText Tenancy where
toText = \case
Dedicated -> "dedicated"
Default' -> "default"
instance ToByteString Tenancy
instance ToHeader Tenancy
instance ToQuery Tenancy
instance FromXML Tenancy where
parseXML = parseXMLText "Tenancy"
data VpcPeeringConnectionStateReason = VpcPeeringConnectionStateReason
{ _vpcsrCode :: Maybe Text
, _vpcsrMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'VpcPeeringConnectionStateReason' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vpcsrCode' @::@ 'Maybe' 'Text'
--
-- * 'vpcsrMessage' @::@ 'Maybe' 'Text'
--
vpcPeeringConnectionStateReason :: VpcPeeringConnectionStateReason
vpcPeeringConnectionStateReason = VpcPeeringConnectionStateReason
{ _vpcsrCode = Nothing
, _vpcsrMessage = Nothing
}
-- | The status of the VPC peering connection.
vpcsrCode :: Lens' VpcPeeringConnectionStateReason (Maybe Text)
vpcsrCode = lens _vpcsrCode (\s a -> s { _vpcsrCode = a })
-- | A message that provides more information about the status, if applicable.
vpcsrMessage :: Lens' VpcPeeringConnectionStateReason (Maybe Text)
vpcsrMessage = lens _vpcsrMessage (\s a -> s { _vpcsrMessage = a })
instance FromXML VpcPeeringConnectionStateReason where
parseXML x = VpcPeeringConnectionStateReason
<$> x .@? "code"
<*> x .@? "message"
instance ToQuery VpcPeeringConnectionStateReason where
toQuery VpcPeeringConnectionStateReason{..} = mconcat
[ "Code" =? _vpcsrCode
, "Message" =? _vpcsrMessage
]
data IamInstanceProfileSpecification = IamInstanceProfileSpecification
{ _iipsArn :: Maybe Text
, _iipsName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'IamInstanceProfileSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iipsArn' @::@ 'Maybe' 'Text'
--
-- * 'iipsName' @::@ 'Maybe' 'Text'
--
iamInstanceProfileSpecification :: IamInstanceProfileSpecification
iamInstanceProfileSpecification = IamInstanceProfileSpecification
{ _iipsArn = Nothing
, _iipsName = Nothing
}
-- | The Amazon Resource Name (ARN) of the instance profile.
iipsArn :: Lens' IamInstanceProfileSpecification (Maybe Text)
iipsArn = lens _iipsArn (\s a -> s { _iipsArn = a })
-- | The name of the instance profile.
iipsName :: Lens' IamInstanceProfileSpecification (Maybe Text)
iipsName = lens _iipsName (\s a -> s { _iipsName = a })
instance FromXML IamInstanceProfileSpecification where
parseXML x = IamInstanceProfileSpecification
<$> x .@? "arn"
<*> x .@? "name"
instance ToQuery IamInstanceProfileSpecification where
toQuery IamInstanceProfileSpecification{..} = mconcat
[ "Arn" =? _iipsArn
, "Name" =? _iipsName
]
data ImportVolumeTaskDetails = ImportVolumeTaskDetails
{ _ivtdAvailabilityZone :: Text
, _ivtdBytesConverted :: Integer
, _ivtdDescription :: Maybe Text
, _ivtdImage :: DiskImageDescription
, _ivtdVolume :: DiskImageVolumeDescription
} deriving (Eq, Read, Show)
-- | 'ImportVolumeTaskDetails' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ivtdAvailabilityZone' @::@ 'Text'
--
-- * 'ivtdBytesConverted' @::@ 'Integer'
--
-- * 'ivtdDescription' @::@ 'Maybe' 'Text'
--
-- * 'ivtdImage' @::@ 'DiskImageDescription'
--
-- * 'ivtdVolume' @::@ 'DiskImageVolumeDescription'
--
importVolumeTaskDetails :: Integer -- ^ 'ivtdBytesConverted'
-> Text -- ^ 'ivtdAvailabilityZone'
-> DiskImageDescription -- ^ 'ivtdImage'
-> DiskImageVolumeDescription -- ^ 'ivtdVolume'
-> ImportVolumeTaskDetails
importVolumeTaskDetails p1 p2 p3 p4 = ImportVolumeTaskDetails
{ _ivtdBytesConverted = p1
, _ivtdAvailabilityZone = p2
, _ivtdImage = p3
, _ivtdVolume = p4
, _ivtdDescription = Nothing
}
-- | The Availability Zone where the resulting volume will reside.
ivtdAvailabilityZone :: Lens' ImportVolumeTaskDetails Text
ivtdAvailabilityZone =
lens _ivtdAvailabilityZone (\s a -> s { _ivtdAvailabilityZone = a })
-- | The number of bytes converted so far.
ivtdBytesConverted :: Lens' ImportVolumeTaskDetails Integer
ivtdBytesConverted =
lens _ivtdBytesConverted (\s a -> s { _ivtdBytesConverted = a })
-- | The description you provided when starting the import volume task.
ivtdDescription :: Lens' ImportVolumeTaskDetails (Maybe Text)
ivtdDescription = lens _ivtdDescription (\s a -> s { _ivtdDescription = a })
-- | The image.
ivtdImage :: Lens' ImportVolumeTaskDetails DiskImageDescription
ivtdImage = lens _ivtdImage (\s a -> s { _ivtdImage = a })
-- | The volume.
ivtdVolume :: Lens' ImportVolumeTaskDetails DiskImageVolumeDescription
ivtdVolume = lens _ivtdVolume (\s a -> s { _ivtdVolume = a })
instance FromXML ImportVolumeTaskDetails where
parseXML x = ImportVolumeTaskDetails
<$> x .@ "availabilityZone"
<*> x .@ "bytesConverted"
<*> x .@? "description"
<*> x .@ "image"
<*> x .@ "volume"
instance ToQuery ImportVolumeTaskDetails where
toQuery ImportVolumeTaskDetails{..} = mconcat
[ "AvailabilityZone" =? _ivtdAvailabilityZone
, "BytesConverted" =? _ivtdBytesConverted
, "Description" =? _ivtdDescription
, "Image" =? _ivtdImage
, "Volume" =? _ivtdVolume
]
data PlacementStrategy
= Cluster -- ^ cluster
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable PlacementStrategy
instance FromText PlacementStrategy where
parser = takeLowerText >>= \case
"cluster" -> pure Cluster
e -> fail $
"Failure parsing PlacementStrategy from " ++ show e
instance ToText PlacementStrategy where
toText Cluster = "cluster"
instance ToByteString PlacementStrategy
instance ToHeader PlacementStrategy
instance ToQuery PlacementStrategy
instance FromXML PlacementStrategy where
parseXML = parseXMLText "PlacementStrategy"
data InstanceNetworkInterface = InstanceNetworkInterface
{ _iniAssociation :: Maybe InstanceNetworkInterfaceAssociation
, _iniAttachment :: Maybe InstanceNetworkInterfaceAttachment
, _iniDescription :: Maybe Text
, _iniGroups :: List "item" GroupIdentifier
, _iniMacAddress :: Maybe Text
, _iniNetworkInterfaceId :: Maybe Text
, _iniOwnerId :: Maybe Text
, _iniPrivateDnsName :: Maybe Text
, _iniPrivateIpAddress :: Maybe Text
, _iniPrivateIpAddresses :: List "item" InstancePrivateIpAddress
, _iniSourceDestCheck :: Maybe Bool
, _iniStatus :: Maybe NetworkInterfaceStatus
, _iniSubnetId :: Maybe Text
, _iniVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'InstanceNetworkInterface' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iniAssociation' @::@ 'Maybe' 'InstanceNetworkInterfaceAssociation'
--
-- * 'iniAttachment' @::@ 'Maybe' 'InstanceNetworkInterfaceAttachment'
--
-- * 'iniDescription' @::@ 'Maybe' 'Text'
--
-- * 'iniGroups' @::@ ['GroupIdentifier']
--
-- * 'iniMacAddress' @::@ 'Maybe' 'Text'
--
-- * 'iniNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'iniOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'iniPrivateDnsName' @::@ 'Maybe' 'Text'
--
-- * 'iniPrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'iniPrivateIpAddresses' @::@ ['InstancePrivateIpAddress']
--
-- * 'iniSourceDestCheck' @::@ 'Maybe' 'Bool'
--
-- * 'iniStatus' @::@ 'Maybe' 'NetworkInterfaceStatus'
--
-- * 'iniSubnetId' @::@ 'Maybe' 'Text'
--
-- * 'iniVpcId' @::@ 'Maybe' 'Text'
--
instanceNetworkInterface :: InstanceNetworkInterface
instanceNetworkInterface = InstanceNetworkInterface
{ _iniNetworkInterfaceId = Nothing
, _iniSubnetId = Nothing
, _iniVpcId = Nothing
, _iniDescription = Nothing
, _iniOwnerId = Nothing
, _iniStatus = Nothing
, _iniMacAddress = Nothing
, _iniPrivateIpAddress = Nothing
, _iniPrivateDnsName = Nothing
, _iniSourceDestCheck = Nothing
, _iniGroups = mempty
, _iniAttachment = Nothing
, _iniAssociation = Nothing
, _iniPrivateIpAddresses = mempty
}
-- | The association information for an Elastic IP associated with the network
-- interface.
iniAssociation :: Lens' InstanceNetworkInterface (Maybe InstanceNetworkInterfaceAssociation)
iniAssociation = lens _iniAssociation (\s a -> s { _iniAssociation = a })
-- | The network interface attachment.
iniAttachment :: Lens' InstanceNetworkInterface (Maybe InstanceNetworkInterfaceAttachment)
iniAttachment = lens _iniAttachment (\s a -> s { _iniAttachment = a })
-- | The description.
iniDescription :: Lens' InstanceNetworkInterface (Maybe Text)
iniDescription = lens _iniDescription (\s a -> s { _iniDescription = a })
-- | One or more security groups.
iniGroups :: Lens' InstanceNetworkInterface [GroupIdentifier]
iniGroups = lens _iniGroups (\s a -> s { _iniGroups = a }) . _List
-- | The MAC address.
iniMacAddress :: Lens' InstanceNetworkInterface (Maybe Text)
iniMacAddress = lens _iniMacAddress (\s a -> s { _iniMacAddress = a })
-- | The ID of the network interface.
iniNetworkInterfaceId :: Lens' InstanceNetworkInterface (Maybe Text)
iniNetworkInterfaceId =
lens _iniNetworkInterfaceId (\s a -> s { _iniNetworkInterfaceId = a })
-- | The ID of the AWS account that created the network interface.
iniOwnerId :: Lens' InstanceNetworkInterface (Maybe Text)
iniOwnerId = lens _iniOwnerId (\s a -> s { _iniOwnerId = a })
-- | The private DNS name.
iniPrivateDnsName :: Lens' InstanceNetworkInterface (Maybe Text)
iniPrivateDnsName =
lens _iniPrivateDnsName (\s a -> s { _iniPrivateDnsName = a })
-- | The IP address of the network interface within the subnet.
iniPrivateIpAddress :: Lens' InstanceNetworkInterface (Maybe Text)
iniPrivateIpAddress =
lens _iniPrivateIpAddress (\s a -> s { _iniPrivateIpAddress = a })
-- | The private IP addresses associated with the network interface.
iniPrivateIpAddresses :: Lens' InstanceNetworkInterface [InstancePrivateIpAddress]
iniPrivateIpAddresses =
lens _iniPrivateIpAddresses (\s a -> s { _iniPrivateIpAddresses = a })
. _List
-- | Indicates whether to validate network traffic to or from this network
-- interface.
iniSourceDestCheck :: Lens' InstanceNetworkInterface (Maybe Bool)
iniSourceDestCheck =
lens _iniSourceDestCheck (\s a -> s { _iniSourceDestCheck = a })
-- | The status of the network interface.
iniStatus :: Lens' InstanceNetworkInterface (Maybe NetworkInterfaceStatus)
iniStatus = lens _iniStatus (\s a -> s { _iniStatus = a })
-- | The ID of the subnet.
iniSubnetId :: Lens' InstanceNetworkInterface (Maybe Text)
iniSubnetId = lens _iniSubnetId (\s a -> s { _iniSubnetId = a })
-- | The ID of the VPC.
iniVpcId :: Lens' InstanceNetworkInterface (Maybe Text)
iniVpcId = lens _iniVpcId (\s a -> s { _iniVpcId = a })
instance FromXML InstanceNetworkInterface where
parseXML x = InstanceNetworkInterface
<$> x .@? "association"
<*> x .@? "attachment"
<*> x .@? "description"
<*> x .@? "groupSet" .!@ mempty
<*> x .@? "macAddress"
<*> x .@? "networkInterfaceId"
<*> x .@? "ownerId"
<*> x .@? "privateDnsName"
<*> x .@? "privateIpAddress"
<*> x .@? "privateIpAddressesSet" .!@ mempty
<*> x .@? "sourceDestCheck"
<*> x .@? "status"
<*> x .@? "subnetId"
<*> x .@? "vpcId"
instance ToQuery InstanceNetworkInterface where
toQuery InstanceNetworkInterface{..} = mconcat
[ "Association" =? _iniAssociation
, "Attachment" =? _iniAttachment
, "Description" =? _iniDescription
, "GroupSet" `toQueryList` _iniGroups
, "MacAddress" =? _iniMacAddress
, "NetworkInterfaceId" =? _iniNetworkInterfaceId
, "OwnerId" =? _iniOwnerId
, "PrivateDnsName" =? _iniPrivateDnsName
, "PrivateIpAddress" =? _iniPrivateIpAddress
, "PrivateIpAddressesSet" `toQueryList` _iniPrivateIpAddresses
, "SourceDestCheck" =? _iniSourceDestCheck
, "Status" =? _iniStatus
, "SubnetId" =? _iniSubnetId
, "VpcId" =? _iniVpcId
]
data VolumeStatusAction = VolumeStatusAction
{ _vsaCode :: Maybe Text
, _vsaDescription :: Maybe Text
, _vsaEventId :: Maybe Text
, _vsaEventType :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'VolumeStatusAction' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vsaCode' @::@ 'Maybe' 'Text'
--
-- * 'vsaDescription' @::@ 'Maybe' 'Text'
--
-- * 'vsaEventId' @::@ 'Maybe' 'Text'
--
-- * 'vsaEventType' @::@ 'Maybe' 'Text'
--
volumeStatusAction :: VolumeStatusAction
volumeStatusAction = VolumeStatusAction
{ _vsaCode = Nothing
, _vsaDescription = Nothing
, _vsaEventType = Nothing
, _vsaEventId = Nothing
}
-- | The code identifying the operation, for example, 'enable-volume-io'.
vsaCode :: Lens' VolumeStatusAction (Maybe Text)
vsaCode = lens _vsaCode (\s a -> s { _vsaCode = a })
-- | A description of the operation.
vsaDescription :: Lens' VolumeStatusAction (Maybe Text)
vsaDescription = lens _vsaDescription (\s a -> s { _vsaDescription = a })
-- | The ID of the event associated with this operation.
vsaEventId :: Lens' VolumeStatusAction (Maybe Text)
vsaEventId = lens _vsaEventId (\s a -> s { _vsaEventId = a })
-- | The event type associated with this operation.
vsaEventType :: Lens' VolumeStatusAction (Maybe Text)
vsaEventType = lens _vsaEventType (\s a -> s { _vsaEventType = a })
instance FromXML VolumeStatusAction where
parseXML x = VolumeStatusAction
<$> x .@? "code"
<*> x .@? "description"
<*> x .@? "eventId"
<*> x .@? "eventType"
instance ToQuery VolumeStatusAction where
toQuery VolumeStatusAction{..} = mconcat
[ "Code" =? _vsaCode
, "Description" =? _vsaDescription
, "EventId" =? _vsaEventId
, "EventType" =? _vsaEventType
]
data VpcPeeringConnectionVpcInfo = VpcPeeringConnectionVpcInfo
{ _vpcviCidrBlock :: Maybe Text
, _vpcviOwnerId :: Maybe Text
, _vpcviVpcId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'VpcPeeringConnectionVpcInfo' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vpcviCidrBlock' @::@ 'Maybe' 'Text'
--
-- * 'vpcviOwnerId' @::@ 'Maybe' 'Text'
--
-- * 'vpcviVpcId' @::@ 'Maybe' 'Text'
--
vpcPeeringConnectionVpcInfo :: VpcPeeringConnectionVpcInfo
vpcPeeringConnectionVpcInfo = VpcPeeringConnectionVpcInfo
{ _vpcviCidrBlock = Nothing
, _vpcviOwnerId = Nothing
, _vpcviVpcId = Nothing
}
-- | The CIDR block for the VPC.
vpcviCidrBlock :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text)
vpcviCidrBlock = lens _vpcviCidrBlock (\s a -> s { _vpcviCidrBlock = a })
-- | The AWS account ID of the VPC owner.
vpcviOwnerId :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text)
vpcviOwnerId = lens _vpcviOwnerId (\s a -> s { _vpcviOwnerId = a })
-- | The ID of the VPC.
vpcviVpcId :: Lens' VpcPeeringConnectionVpcInfo (Maybe Text)
vpcviVpcId = lens _vpcviVpcId (\s a -> s { _vpcviVpcId = a })
instance FromXML VpcPeeringConnectionVpcInfo where
parseXML x = VpcPeeringConnectionVpcInfo
<$> x .@? "cidrBlock"
<*> x .@? "ownerId"
<*> x .@? "vpcId"
instance ToQuery VpcPeeringConnectionVpcInfo where
toQuery VpcPeeringConnectionVpcInfo{..} = mconcat
[ "CidrBlock" =? _vpcviCidrBlock
, "OwnerId" =? _vpcviOwnerId
, "VpcId" =? _vpcviVpcId
]
data ReservedInstanceLimitPrice = ReservedInstanceLimitPrice
{ _rilpAmount :: Maybe Double
, _rilpCurrencyCode :: Maybe CurrencyCodeValues
} deriving (Eq, Read, Show)
-- | 'ReservedInstanceLimitPrice' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rilpAmount' @::@ 'Maybe' 'Double'
--
-- * 'rilpCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues'
--
reservedInstanceLimitPrice :: ReservedInstanceLimitPrice
reservedInstanceLimitPrice = ReservedInstanceLimitPrice
{ _rilpAmount = Nothing
, _rilpCurrencyCode = Nothing
}
-- | Used for Reserved Instance Marketplace offerings. Specifies the limit price
-- on the total order (instanceCount * price).
rilpAmount :: Lens' ReservedInstanceLimitPrice (Maybe Double)
rilpAmount = lens _rilpAmount (\s a -> s { _rilpAmount = a })
-- | The currency in which the 'limitPrice' amount is specified. At this time, the
-- only supported currency is 'USD'.
rilpCurrencyCode :: Lens' ReservedInstanceLimitPrice (Maybe CurrencyCodeValues)
rilpCurrencyCode = lens _rilpCurrencyCode (\s a -> s { _rilpCurrencyCode = a })
instance FromXML ReservedInstanceLimitPrice where
parseXML x = ReservedInstanceLimitPrice
<$> x .@? "amount"
<*> x .@? "currencyCode"
instance ToQuery ReservedInstanceLimitPrice where
toQuery ReservedInstanceLimitPrice{..} = mconcat
[ "Amount" =? _rilpAmount
, "CurrencyCode" =? _rilpCurrencyCode
]
data Vpc = Vpc
{ _vpcCidrBlock :: Text
, _vpcDhcpOptionsId :: Text
, _vpcInstanceTenancy :: Tenancy
, _vpcIsDefault :: Bool
, _vpcState :: VpcState
, _vpcTags :: List "item" Tag
, _vpcVpcId :: Text
} deriving (Eq, Read, Show)
-- | 'Vpc' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vpcCidrBlock' @::@ 'Text'
--
-- * 'vpcDhcpOptionsId' @::@ 'Text'
--
-- * 'vpcInstanceTenancy' @::@ 'Tenancy'
--
-- * 'vpcIsDefault' @::@ 'Bool'
--
-- * 'vpcState' @::@ 'VpcState'
--
-- * 'vpcTags' @::@ ['Tag']
--
-- * 'vpcVpcId' @::@ 'Text'
--
vpc :: Text -- ^ 'vpcVpcId'
-> VpcState -- ^ 'vpcState'
-> Text -- ^ 'vpcCidrBlock'
-> Text -- ^ 'vpcDhcpOptionsId'
-> Tenancy -- ^ 'vpcInstanceTenancy'
-> Bool -- ^ 'vpcIsDefault'
-> Vpc
vpc p1 p2 p3 p4 p5 p6 = Vpc
{ _vpcVpcId = p1
, _vpcState = p2
, _vpcCidrBlock = p3
, _vpcDhcpOptionsId = p4
, _vpcInstanceTenancy = p5
, _vpcIsDefault = p6
, _vpcTags = mempty
}
-- | The CIDR block for the VPC.
vpcCidrBlock :: Lens' Vpc Text
vpcCidrBlock = lens _vpcCidrBlock (\s a -> s { _vpcCidrBlock = a })
-- | The ID of the set of DHCP options you've associated with the VPC (or 'default'
-- if the default options are associated with the VPC).
vpcDhcpOptionsId :: Lens' Vpc Text
vpcDhcpOptionsId = lens _vpcDhcpOptionsId (\s a -> s { _vpcDhcpOptionsId = a })
-- | The allowed tenancy of instances launched into the VPC.
vpcInstanceTenancy :: Lens' Vpc Tenancy
vpcInstanceTenancy =
lens _vpcInstanceTenancy (\s a -> s { _vpcInstanceTenancy = a })
-- | Indicates whether the VPC is the default VPC.
vpcIsDefault :: Lens' Vpc Bool
vpcIsDefault = lens _vpcIsDefault (\s a -> s { _vpcIsDefault = a })
-- | The current state of the VPC.
vpcState :: Lens' Vpc VpcState
vpcState = lens _vpcState (\s a -> s { _vpcState = a })
-- | Any tags assigned to the VPC.
vpcTags :: Lens' Vpc [Tag]
vpcTags = lens _vpcTags (\s a -> s { _vpcTags = a }) . _List
-- | The ID of the VPC.
vpcVpcId :: Lens' Vpc Text
vpcVpcId = lens _vpcVpcId (\s a -> s { _vpcVpcId = a })
instance FromXML Vpc where
parseXML x = Vpc
<$> x .@ "cidrBlock"
<*> x .@ "dhcpOptionsId"
<*> x .@ "instanceTenancy"
<*> x .@ "isDefault"
<*> x .@ "state"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "vpcId"
instance ToQuery Vpc where
toQuery Vpc{..} = mconcat
[ "CidrBlock" =? _vpcCidrBlock
, "DhcpOptionsId" =? _vpcDhcpOptionsId
, "InstanceTenancy" =? _vpcInstanceTenancy
, "IsDefault" =? _vpcIsDefault
, "State" =? _vpcState
, "TagSet" `toQueryList` _vpcTags
, "VpcId" =? _vpcVpcId
]
data InstanceStatus = InstanceStatus
{ _isAvailabilityZone :: Maybe Text
, _isEvents :: List "item" InstanceStatusEvent
, _isInstanceId :: Maybe Text
, _isInstanceState :: Maybe InstanceState
, _isInstanceStatus :: Maybe InstanceStatusSummary
, _isSystemStatus :: Maybe InstanceStatusSummary
} deriving (Eq, Read, Show)
-- | 'InstanceStatus' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'isAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'isEvents' @::@ ['InstanceStatusEvent']
--
-- * 'isInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'isInstanceState' @::@ 'Maybe' 'InstanceState'
--
-- * 'isInstanceStatus' @::@ 'Maybe' 'InstanceStatusSummary'
--
-- * 'isSystemStatus' @::@ 'Maybe' 'InstanceStatusSummary'
--
instanceStatus :: InstanceStatus
instanceStatus = InstanceStatus
{ _isInstanceId = Nothing
, _isAvailabilityZone = Nothing
, _isEvents = mempty
, _isInstanceState = Nothing
, _isSystemStatus = Nothing
, _isInstanceStatus = Nothing
}
-- | The Availability Zone of the instance.
isAvailabilityZone :: Lens' InstanceStatus (Maybe Text)
isAvailabilityZone =
lens _isAvailabilityZone (\s a -> s { _isAvailabilityZone = a })
-- | Extra information regarding events associated with the instance.
isEvents :: Lens' InstanceStatus [InstanceStatusEvent]
isEvents = lens _isEvents (\s a -> s { _isEvents = a }) . _List
-- | The ID of the instance.
isInstanceId :: Lens' InstanceStatus (Maybe Text)
isInstanceId = lens _isInstanceId (\s a -> s { _isInstanceId = a })
-- | The intended state of the instance. 'DescribeInstanceStatus' requires that an
-- instance be in the 'running' state.
isInstanceState :: Lens' InstanceStatus (Maybe InstanceState)
isInstanceState = lens _isInstanceState (\s a -> s { _isInstanceState = a })
-- | Reports impaired functionality that stems from issues internal to the
-- instance, such as impaired reachability.
isInstanceStatus :: Lens' InstanceStatus (Maybe InstanceStatusSummary)
isInstanceStatus = lens _isInstanceStatus (\s a -> s { _isInstanceStatus = a })
-- | Reports impaired functionality that stems from issues related to the systems
-- that support an instance, such as hardware failures and network connectivity
-- problems.
isSystemStatus :: Lens' InstanceStatus (Maybe InstanceStatusSummary)
isSystemStatus = lens _isSystemStatus (\s a -> s { _isSystemStatus = a })
instance FromXML InstanceStatus where
parseXML x = InstanceStatus
<$> x .@? "availabilityZone"
<*> x .@? "eventsSet" .!@ mempty
<*> x .@? "instanceId"
<*> x .@? "instanceState"
<*> x .@? "instanceStatus"
<*> x .@? "systemStatus"
instance ToQuery InstanceStatus where
toQuery InstanceStatus{..} = mconcat
[ "AvailabilityZone" =? _isAvailabilityZone
, "EventsSet" `toQueryList` _isEvents
, "InstanceId" =? _isInstanceId
, "InstanceState" =? _isInstanceState
, "InstanceStatus" =? _isInstanceStatus
, "SystemStatus" =? _isSystemStatus
]
data ArchitectureValues
= I386 -- ^ i386
| X8664 -- ^ x86_64
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ArchitectureValues
instance FromText ArchitectureValues where
parser = takeLowerText >>= \case
"i386" -> pure I386
"x86_64" -> pure X8664
e -> fail $
"Failure parsing ArchitectureValues from " ++ show e
instance ToText ArchitectureValues where
toText = \case
I386 -> "i386"
X8664 -> "x86_64"
instance ToByteString ArchitectureValues
instance ToHeader ArchitectureValues
instance ToQuery ArchitectureValues
instance FromXML ArchitectureValues where
parseXML = parseXMLText "ArchitectureValues"
data ReportInstanceReasonCodes
= InstanceStuckInState -- ^ instance-stuck-in-state
| NotAcceptingCredentials -- ^ not-accepting-credentials
| Other -- ^ other
| PasswordNotAvailable -- ^ password-not-available
| PerformanceEbsVolume -- ^ performance-ebs-volume
| PerformanceInstanceStore -- ^ performance-instance-store
| PerformanceNetwork -- ^ performance-network
| PerformanceOther -- ^ performance-other
| Unresponsive -- ^ unresponsive
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ReportInstanceReasonCodes
instance FromText ReportInstanceReasonCodes where
parser = takeLowerText >>= \case
"instance-stuck-in-state" -> pure InstanceStuckInState
"not-accepting-credentials" -> pure NotAcceptingCredentials
"other" -> pure Other
"password-not-available" -> pure PasswordNotAvailable
"performance-ebs-volume" -> pure PerformanceEbsVolume
"performance-instance-store" -> pure PerformanceInstanceStore
"performance-network" -> pure PerformanceNetwork
"performance-other" -> pure PerformanceOther
"unresponsive" -> pure Unresponsive
e -> fail $
"Failure parsing ReportInstanceReasonCodes from " ++ show e
instance ToText ReportInstanceReasonCodes where
toText = \case
InstanceStuckInState -> "instance-stuck-in-state"
NotAcceptingCredentials -> "not-accepting-credentials"
Other -> "other"
PasswordNotAvailable -> "password-not-available"
PerformanceEbsVolume -> "performance-ebs-volume"
PerformanceInstanceStore -> "performance-instance-store"
PerformanceNetwork -> "performance-network"
PerformanceOther -> "performance-other"
Unresponsive -> "unresponsive"
instance ToByteString ReportInstanceReasonCodes
instance ToHeader ReportInstanceReasonCodes
instance ToQuery ReportInstanceReasonCodes
instance FromXML ReportInstanceReasonCodes where
parseXML = parseXMLText "ReportInstanceReasonCodes"
data EbsBlockDevice = EbsBlockDevice
{ _ebdDeleteOnTermination :: Maybe Bool
, _ebdEncrypted :: Maybe Bool
, _ebdIops :: Maybe Int
, _ebdSnapshotId :: Maybe Text
, _ebdVolumeSize :: Maybe Int
, _ebdVolumeType :: Maybe VolumeType
} deriving (Eq, Read, Show)
-- | 'EbsBlockDevice' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ebdDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'ebdEncrypted' @::@ 'Maybe' 'Bool'
--
-- * 'ebdIops' @::@ 'Maybe' 'Int'
--
-- * 'ebdSnapshotId' @::@ 'Maybe' 'Text'
--
-- * 'ebdVolumeSize' @::@ 'Maybe' 'Int'
--
-- * 'ebdVolumeType' @::@ 'Maybe' 'VolumeType'
--
ebsBlockDevice :: EbsBlockDevice
ebsBlockDevice = EbsBlockDevice
{ _ebdSnapshotId = Nothing
, _ebdVolumeSize = Nothing
, _ebdDeleteOnTermination = Nothing
, _ebdVolumeType = Nothing
, _ebdIops = Nothing
, _ebdEncrypted = Nothing
}
-- | Indicates whether the Amazon EBS volume is deleted on instance termination.
ebdDeleteOnTermination :: Lens' EbsBlockDevice (Maybe Bool)
ebdDeleteOnTermination =
lens _ebdDeleteOnTermination (\s a -> s { _ebdDeleteOnTermination = a })
-- | Indicates whether the Amazon EBS volume is encrypted. Encrypted Amazon EBS
-- volumes may only be attached to instances that support Amazon EBS encryption.
ebdEncrypted :: Lens' EbsBlockDevice (Maybe Bool)
ebdEncrypted = lens _ebdEncrypted (\s a -> s { _ebdEncrypted = a })
-- | The number of I/O operations per second (IOPS) that the volume supports. For
-- Provisioned IOPS (SSD) volumes, this represents the number of IOPS that are
-- provisioned for the volume. For General Purpose (SSD) volumes, this
-- represents the baseline performance of the volume and the rate at which the
-- volume accumulates I/O credits for bursting. For more information on General
-- Purpose (SSD) baseline performance, I/O credits, and bursting, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html Amazon EBSVolume Types> in the /Amazon Elastic Compute Cloud User Guide for Linux/.
--
-- Constraint: Range is 100 to 20000 for Provisioned IOPS (SSD) volumes and 3
-- to 10000 for General Purpose (SSD) volumes.
--
-- Condition: This parameter is required for requests to create 'io1' volumes; it
-- is not used in requests to create 'standard' or 'gp2' volumes.
ebdIops :: Lens' EbsBlockDevice (Maybe Int)
ebdIops = lens _ebdIops (\s a -> s { _ebdIops = a })
-- | The ID of the snapshot.
ebdSnapshotId :: Lens' EbsBlockDevice (Maybe Text)
ebdSnapshotId = lens _ebdSnapshotId (\s a -> s { _ebdSnapshotId = a })
-- | The size of the volume, in GiB.
--
-- Constraints: '1-1024' for 'standard' volumes, '1-16384' for 'gp2' volumes, and '4-16384' for 'io1' volumes. If you specify a snapshot, the volume size must be equal to
-- or larger than the snapshot size.
--
-- Default: If you're creating the volume from a snapshot and don't specify a
-- volume size, the default is the snapshot size.
ebdVolumeSize :: Lens' EbsBlockDevice (Maybe Int)
ebdVolumeSize = lens _ebdVolumeSize (\s a -> s { _ebdVolumeSize = a })
-- | The volume type. 'gp2' for General Purpose (SSD) volumes, 'io1' for Provisioned
-- IOPS (SSD) volumes, and 'standard' for Magnetic volumes.
--
-- Default: 'standard'
ebdVolumeType :: Lens' EbsBlockDevice (Maybe VolumeType)
ebdVolumeType = lens _ebdVolumeType (\s a -> s { _ebdVolumeType = a })
instance FromXML EbsBlockDevice where
parseXML x = EbsBlockDevice
<$> x .@? "deleteOnTermination"
<*> x .@? "encrypted"
<*> x .@? "iops"
<*> x .@? "snapshotId"
<*> x .@? "volumeSize"
<*> x .@? "volumeType"
instance ToQuery EbsBlockDevice where
toQuery EbsBlockDevice{..} = mconcat
[ "DeleteOnTermination" =? _ebdDeleteOnTermination
, "Encrypted" =? _ebdEncrypted
, "Iops" =? _ebdIops
, "SnapshotId" =? _ebdSnapshotId
, "VolumeSize" =? _ebdVolumeSize
, "VolumeType" =? _ebdVolumeType
]
data AccountAttribute = AccountAttribute
{ _aaAttributeName :: Maybe Text
, _aaAttributeValues :: List "item" AccountAttributeValue
} deriving (Eq, Read, Show)
-- | 'AccountAttribute' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'aaAttributeName' @::@ 'Maybe' 'Text'
--
-- * 'aaAttributeValues' @::@ ['AccountAttributeValue']
--
accountAttribute :: AccountAttribute
accountAttribute = AccountAttribute
{ _aaAttributeName = Nothing
, _aaAttributeValues = mempty
}
-- | The name of the account attribute.
aaAttributeName :: Lens' AccountAttribute (Maybe Text)
aaAttributeName = lens _aaAttributeName (\s a -> s { _aaAttributeName = a })
-- | One or more values for the account attribute.
aaAttributeValues :: Lens' AccountAttribute [AccountAttributeValue]
aaAttributeValues =
lens _aaAttributeValues (\s a -> s { _aaAttributeValues = a })
. _List
instance FromXML AccountAttribute where
parseXML x = AccountAttribute
<$> x .@? "attributeName"
<*> x .@? "attributeValueSet" .!@ mempty
instance ToQuery AccountAttribute where
toQuery AccountAttribute{..} = mconcat
[ "AttributeName" =? _aaAttributeName
, "AttributeValueSet" `toQueryList` _aaAttributeValues
]
data PriceSchedule = PriceSchedule
{ _psActive :: Maybe Bool
, _psCurrencyCode :: Maybe CurrencyCodeValues
, _psPrice :: Maybe Double
, _psTerm :: Maybe Integer
} deriving (Eq, Read, Show)
-- | 'PriceSchedule' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'psActive' @::@ 'Maybe' 'Bool'
--
-- * 'psCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues'
--
-- * 'psPrice' @::@ 'Maybe' 'Double'
--
-- * 'psTerm' @::@ 'Maybe' 'Integer'
--
priceSchedule :: PriceSchedule
priceSchedule = PriceSchedule
{ _psTerm = Nothing
, _psPrice = Nothing
, _psCurrencyCode = Nothing
, _psActive = Nothing
}
-- | The current price schedule, as determined by the term remaining for the
-- Reserved Instance in the listing.
--
-- A specific price schedule is always in effect, but only one price schedule
-- can be active at any time. Take, for example, a Reserved Instance listing
-- that has five months remaining in its term. When you specify price schedules
-- for five months and two months, this means that schedule 1, covering the
-- first three months of the remaining term, will be active during months 5, 4,
-- and 3. Then schedule 2, covering the last two months of the term, will be
-- active for months 2 and 1.
psActive :: Lens' PriceSchedule (Maybe Bool)
psActive = lens _psActive (\s a -> s { _psActive = a })
-- | The currency for transacting the Reserved Instance resale. At this time, the
-- only supported currency is 'USD'.
psCurrencyCode :: Lens' PriceSchedule (Maybe CurrencyCodeValues)
psCurrencyCode = lens _psCurrencyCode (\s a -> s { _psCurrencyCode = a })
-- | The fixed price for the term.
psPrice :: Lens' PriceSchedule (Maybe Double)
psPrice = lens _psPrice (\s a -> s { _psPrice = a })
-- | The number of months remaining in the reservation. For example, 2 is the
-- second to the last month before the capacity reservation expires.
psTerm :: Lens' PriceSchedule (Maybe Integer)
psTerm = lens _psTerm (\s a -> s { _psTerm = a })
instance FromXML PriceSchedule where
parseXML x = PriceSchedule
<$> x .@? "active"
<*> x .@? "currencyCode"
<*> x .@? "price"
<*> x .@? "term"
instance ToQuery PriceSchedule where
toQuery PriceSchedule{..} = mconcat
[ "Active" =? _psActive
, "CurrencyCode" =? _psCurrencyCode
, "Price" =? _psPrice
, "Term" =? _psTerm
]
data DeviceType
= Ebs -- ^ ebs
| InstanceStore -- ^ instance-store
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable DeviceType
instance FromText DeviceType where
parser = takeLowerText >>= \case
"ebs" -> pure Ebs
"instance-store" -> pure InstanceStore
e -> fail $
"Failure parsing DeviceType from " ++ show e
instance ToText DeviceType where
toText = \case
Ebs -> "ebs"
InstanceStore -> "instance-store"
instance ToByteString DeviceType
instance ToHeader DeviceType
instance ToQuery DeviceType
instance FromXML DeviceType where
parseXML = parseXMLText "DeviceType"
data DomainType
= DTStandard -- ^ standard
| DTVpc -- ^ vpc
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable DomainType
instance FromText DomainType where
parser = takeLowerText >>= \case
"standard" -> pure DTStandard
"vpc" -> pure DTVpc
e -> fail $
"Failure parsing DomainType from " ++ show e
instance ToText DomainType where
toText = \case
DTStandard -> "standard"
DTVpc -> "vpc"
instance ToByteString DomainType
instance ToHeader DomainType
instance ToQuery DomainType
instance FromXML DomainType where
parseXML = parseXMLText "DomainType"
data Region = Region
{ _rEndpoint :: Maybe Text
, _rRegionName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'Region' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rEndpoint' @::@ 'Maybe' 'Text'
--
-- * 'rRegionName' @::@ 'Maybe' 'Text'
--
region :: Region
region = Region
{ _rRegionName = Nothing
, _rEndpoint = Nothing
}
-- | The region service endpoint.
rEndpoint :: Lens' Region (Maybe Text)
rEndpoint = lens _rEndpoint (\s a -> s { _rEndpoint = a })
-- | The name of the region.
rRegionName :: Lens' Region (Maybe Text)
rRegionName = lens _rRegionName (\s a -> s { _rRegionName = a })
instance FromXML Region where
parseXML x = Region
<$> x .@? "regionEndpoint"
<*> x .@? "regionName"
instance ToQuery Region where
toQuery Region{..} = mconcat
[ "RegionEndpoint" =? _rEndpoint
, "RegionName" =? _rRegionName
]
newtype PropagatingVgw = PropagatingVgw
{ _pvGatewayId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'PropagatingVgw' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pvGatewayId' @::@ 'Maybe' 'Text'
--
propagatingVgw :: PropagatingVgw
propagatingVgw = PropagatingVgw
{ _pvGatewayId = Nothing
}
-- | The ID of the virtual private gateway (VGW).
pvGatewayId :: Lens' PropagatingVgw (Maybe Text)
pvGatewayId = lens _pvGatewayId (\s a -> s { _pvGatewayId = a })
instance FromXML PropagatingVgw where
parseXML x = PropagatingVgw
<$> x .@? "gatewayId"
instance ToQuery PropagatingVgw where
toQuery PropagatingVgw{..} = mconcat
[ "GatewayId" =? _pvGatewayId
]
data OfferingTypeValues
= AllUpfront -- ^ All Upfront
| HeavyUtilization -- ^ Heavy Utilization
| LightUtilization -- ^ Light Utilization
| MediumUtilization -- ^ Medium Utilization
| NoUpfront -- ^ No Upfront
| PartialUpfront -- ^ Partial Upfront
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable OfferingTypeValues
instance FromText OfferingTypeValues where
parser = takeLowerText >>= \case
"all upfront" -> pure AllUpfront
"heavy utilization" -> pure HeavyUtilization
"light utilization" -> pure LightUtilization
"medium utilization" -> pure MediumUtilization
"no upfront" -> pure NoUpfront
"partial upfront" -> pure PartialUpfront
e -> fail $
"Failure parsing OfferingTypeValues from " ++ show e
instance ToText OfferingTypeValues where
toText = \case
AllUpfront -> "All Upfront"
HeavyUtilization -> "Heavy Utilization"
LightUtilization -> "Light Utilization"
MediumUtilization -> "Medium Utilization"
NoUpfront -> "No Upfront"
PartialUpfront -> "Partial Upfront"
instance ToByteString OfferingTypeValues
instance ToHeader OfferingTypeValues
instance ToQuery OfferingTypeValues
instance FromXML OfferingTypeValues where
parseXML = parseXMLText "OfferingTypeValues"
data VpnGateway = VpnGateway
{ _vgAvailabilityZone :: Maybe Text
, _vgState :: Maybe VpnState
, _vgTags :: List "item" Tag
, _vgType :: Maybe GatewayType
, _vgVpcAttachments :: List "item" VpcAttachment
, _vgVpnGatewayId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VpnGateway' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vgAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'vgState' @::@ 'Maybe' 'VpnState'
--
-- * 'vgTags' @::@ ['Tag']
--
-- * 'vgType' @::@ 'Maybe' 'GatewayType'
--
-- * 'vgVpcAttachments' @::@ ['VpcAttachment']
--
-- * 'vgVpnGatewayId' @::@ 'Maybe' 'Text'
--
vpnGateway :: VpnGateway
vpnGateway = VpnGateway
{ _vgVpnGatewayId = Nothing
, _vgState = Nothing
, _vgType = Nothing
, _vgAvailabilityZone = Nothing
, _vgVpcAttachments = mempty
, _vgTags = mempty
}
-- | The Availability Zone where the virtual private gateway was created.
vgAvailabilityZone :: Lens' VpnGateway (Maybe Text)
vgAvailabilityZone =
lens _vgAvailabilityZone (\s a -> s { _vgAvailabilityZone = a })
-- | The current state of the virtual private gateway.
vgState :: Lens' VpnGateway (Maybe VpnState)
vgState = lens _vgState (\s a -> s { _vgState = a })
-- | Any tags assigned to the virtual private gateway.
vgTags :: Lens' VpnGateway [Tag]
vgTags = lens _vgTags (\s a -> s { _vgTags = a }) . _List
-- | The type of VPN connection the virtual private gateway supports.
vgType :: Lens' VpnGateway (Maybe GatewayType)
vgType = lens _vgType (\s a -> s { _vgType = a })
-- | Any VPCs attached to the virtual private gateway.
vgVpcAttachments :: Lens' VpnGateway [VpcAttachment]
vgVpcAttachments = lens _vgVpcAttachments (\s a -> s { _vgVpcAttachments = a }) . _List
-- | The ID of the virtual private gateway.
vgVpnGatewayId :: Lens' VpnGateway (Maybe Text)
vgVpnGatewayId = lens _vgVpnGatewayId (\s a -> s { _vgVpnGatewayId = a })
instance FromXML VpnGateway where
parseXML x = VpnGateway
<$> x .@? "availabilityZone"
<*> x .@? "state"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "type"
<*> x .@? "attachments" .!@ mempty
<*> x .@? "vpnGatewayId"
instance ToQuery VpnGateway where
toQuery VpnGateway{..} = mconcat
[ "AvailabilityZone" =? _vgAvailabilityZone
, "State" =? _vgState
, "TagSet" `toQueryList` _vgTags
, "Type" =? _vgType
, "Attachments" `toQueryList` _vgVpcAttachments
, "VpnGatewayId" =? _vgVpnGatewayId
]
data Filter = Filter
{ _fName :: Text
, _fValues :: List "item" Text
} deriving (Eq, Ord, Read, Show)
-- | 'Filter' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'fName' @::@ 'Text'
--
-- * 'fValues' @::@ ['Text']
--
filter' :: Text -- ^ 'fName'
-> Filter
filter' p1 = Filter
{ _fName = p1
, _fValues = mempty
}
-- | The name of the filter. Filter names are case-sensitive.
fName :: Lens' Filter Text
fName = lens _fName (\s a -> s { _fName = a })
-- | One or more filter values. Filter values are case-sensitive.
fValues :: Lens' Filter [Text]
fValues = lens _fValues (\s a -> s { _fValues = a }) . _List
instance FromXML Filter where
parseXML x = Filter
<$> x .@ "Name"
<*> x .@? "Value" .!@ mempty
instance ToQuery Filter where
toQuery Filter{..} = mconcat
[ "Name" =? _fName
, "Value" `toQueryList` _fValues
]
data VolumeType
= Gp2 -- ^ gp2
| Io1 -- ^ io1
| Standard -- ^ standard
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeType
instance FromText VolumeType where
parser = takeLowerText >>= \case
"gp2" -> pure Gp2
"io1" -> pure Io1
"standard" -> pure Standard
e -> fail $
"Failure parsing VolumeType from " ++ show e
instance ToText VolumeType where
toText = \case
Gp2 -> "gp2"
Io1 -> "io1"
Standard -> "standard"
instance ToByteString VolumeType
instance ToHeader VolumeType
instance ToQuery VolumeType
instance FromXML VolumeType where
parseXML = parseXMLText "VolumeType"
data InstanceStateChange = InstanceStateChange
{ _iscCurrentState :: Maybe InstanceState
, _iscInstanceId :: Maybe Text
, _iscPreviousState :: Maybe InstanceState
} deriving (Eq, Read, Show)
-- | 'InstanceStateChange' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iscCurrentState' @::@ 'Maybe' 'InstanceState'
--
-- * 'iscInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'iscPreviousState' @::@ 'Maybe' 'InstanceState'
--
instanceStateChange :: InstanceStateChange
instanceStateChange = InstanceStateChange
{ _iscInstanceId = Nothing
, _iscCurrentState = Nothing
, _iscPreviousState = Nothing
}
-- | The current state of the instance.
iscCurrentState :: Lens' InstanceStateChange (Maybe InstanceState)
iscCurrentState = lens _iscCurrentState (\s a -> s { _iscCurrentState = a })
-- | The ID of the instance.
iscInstanceId :: Lens' InstanceStateChange (Maybe Text)
iscInstanceId = lens _iscInstanceId (\s a -> s { _iscInstanceId = a })
-- | The previous state of the instance.
iscPreviousState :: Lens' InstanceStateChange (Maybe InstanceState)
iscPreviousState = lens _iscPreviousState (\s a -> s { _iscPreviousState = a })
instance FromXML InstanceStateChange where
parseXML x = InstanceStateChange
<$> x .@? "currentState"
<*> x .@? "instanceId"
<*> x .@? "previousState"
instance ToQuery InstanceStateChange where
toQuery InstanceStateChange{..} = mconcat
[ "CurrentState" =? _iscCurrentState
, "InstanceId" =? _iscInstanceId
, "PreviousState" =? _iscPreviousState
]
data NetworkAcl = NetworkAcl
{ _naAssociations :: List "item" NetworkAclAssociation
, _naEntries :: List "item" NetworkAclEntry
, _naIsDefault :: Maybe Bool
, _naNetworkAclId :: Maybe Text
, _naTags :: List "item" Tag
, _naVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'NetworkAcl' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'naAssociations' @::@ ['NetworkAclAssociation']
--
-- * 'naEntries' @::@ ['NetworkAclEntry']
--
-- * 'naIsDefault' @::@ 'Maybe' 'Bool'
--
-- * 'naNetworkAclId' @::@ 'Maybe' 'Text'
--
-- * 'naTags' @::@ ['Tag']
--
-- * 'naVpcId' @::@ 'Maybe' 'Text'
--
networkAcl :: NetworkAcl
networkAcl = NetworkAcl
{ _naNetworkAclId = Nothing
, _naVpcId = Nothing
, _naIsDefault = Nothing
, _naEntries = mempty
, _naAssociations = mempty
, _naTags = mempty
}
-- | Any associations between the network ACL and one or more subnets
naAssociations :: Lens' NetworkAcl [NetworkAclAssociation]
naAssociations = lens _naAssociations (\s a -> s { _naAssociations = a }) . _List
-- | One or more entries (rules) in the network ACL.
naEntries :: Lens' NetworkAcl [NetworkAclEntry]
naEntries = lens _naEntries (\s a -> s { _naEntries = a }) . _List
-- | Indicates whether this is the default network ACL for the VPC.
naIsDefault :: Lens' NetworkAcl (Maybe Bool)
naIsDefault = lens _naIsDefault (\s a -> s { _naIsDefault = a })
-- | The ID of the network ACL.
naNetworkAclId :: Lens' NetworkAcl (Maybe Text)
naNetworkAclId = lens _naNetworkAclId (\s a -> s { _naNetworkAclId = a })
-- | Any tags assigned to the network ACL.
naTags :: Lens' NetworkAcl [Tag]
naTags = lens _naTags (\s a -> s { _naTags = a }) . _List
-- | The ID of the VPC for the network ACL.
naVpcId :: Lens' NetworkAcl (Maybe Text)
naVpcId = lens _naVpcId (\s a -> s { _naVpcId = a })
instance FromXML NetworkAcl where
parseXML x = NetworkAcl
<$> x .@? "associationSet" .!@ mempty
<*> x .@? "entrySet" .!@ mempty
<*> x .@? "default"
<*> x .@? "networkAclId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery NetworkAcl where
toQuery NetworkAcl{..} = mconcat
[ "AssociationSet" `toQueryList` _naAssociations
, "EntrySet" `toQueryList` _naEntries
, "Default" =? _naIsDefault
, "NetworkAclId" =? _naNetworkAclId
, "TagSet" `toQueryList` _naTags
, "VpcId" =? _naVpcId
]
data ImageState
= ISAvailable -- ^ available
| ISDeregistered -- ^ deregistered
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ImageState
instance FromText ImageState where
parser = takeLowerText >>= \case
"available" -> pure ISAvailable
"deregistered" -> pure ISDeregistered
e -> fail $
"Failure parsing ImageState from " ++ show e
instance ToText ImageState where
toText = \case
ISAvailable -> "available"
ISDeregistered -> "deregistered"
instance ToByteString ImageState
instance ToHeader ImageState
instance ToQuery ImageState
instance FromXML ImageState where
parseXML = parseXMLText "ImageState"
data GatewayType
= Ipsec1 -- ^ ipsec.1
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable GatewayType
instance FromText GatewayType where
parser = takeLowerText >>= \case
"ipsec.1" -> pure Ipsec1
e -> fail $
"Failure parsing GatewayType from " ++ show e
instance ToText GatewayType where
toText Ipsec1 = "ipsec.1"
instance ToByteString GatewayType
instance ToHeader GatewayType
instance ToQuery GatewayType
instance FromXML GatewayType where
parseXML = parseXMLText "GatewayType"
data InstanceNetworkInterfaceAttachment = InstanceNetworkInterfaceAttachment
{ _iniaAttachTime :: Maybe ISO8601
, _iniaAttachmentId :: Maybe Text
, _iniaDeleteOnTermination :: Maybe Bool
, _iniaDeviceIndex :: Maybe Int
, _iniaStatus :: Maybe AttachmentStatus
} deriving (Eq, Read, Show)
-- | 'InstanceNetworkInterfaceAttachment' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iniaAttachTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'iniaAttachmentId' @::@ 'Maybe' 'Text'
--
-- * 'iniaDeleteOnTermination' @::@ 'Maybe' 'Bool'
--
-- * 'iniaDeviceIndex' @::@ 'Maybe' 'Int'
--
-- * 'iniaStatus' @::@ 'Maybe' 'AttachmentStatus'
--
instanceNetworkInterfaceAttachment :: InstanceNetworkInterfaceAttachment
instanceNetworkInterfaceAttachment = InstanceNetworkInterfaceAttachment
{ _iniaAttachmentId = Nothing
, _iniaDeviceIndex = Nothing
, _iniaStatus = Nothing
, _iniaAttachTime = Nothing
, _iniaDeleteOnTermination = Nothing
}
-- | The time stamp when the attachment initiated.
iniaAttachTime :: Lens' InstanceNetworkInterfaceAttachment (Maybe UTCTime)
iniaAttachTime = lens _iniaAttachTime (\s a -> s { _iniaAttachTime = a }) . mapping _Time
-- | The ID of the network interface attachment.
iniaAttachmentId :: Lens' InstanceNetworkInterfaceAttachment (Maybe Text)
iniaAttachmentId = lens _iniaAttachmentId (\s a -> s { _iniaAttachmentId = a })
-- | Indicates whether the network interface is deleted when the instance is
-- terminated.
iniaDeleteOnTermination :: Lens' InstanceNetworkInterfaceAttachment (Maybe Bool)
iniaDeleteOnTermination =
lens _iniaDeleteOnTermination (\s a -> s { _iniaDeleteOnTermination = a })
-- | The index of the device on the instance for the network interface attachment.
iniaDeviceIndex :: Lens' InstanceNetworkInterfaceAttachment (Maybe Int)
iniaDeviceIndex = lens _iniaDeviceIndex (\s a -> s { _iniaDeviceIndex = a })
-- | The attachment state.
iniaStatus :: Lens' InstanceNetworkInterfaceAttachment (Maybe AttachmentStatus)
iniaStatus = lens _iniaStatus (\s a -> s { _iniaStatus = a })
instance FromXML InstanceNetworkInterfaceAttachment where
parseXML x = InstanceNetworkInterfaceAttachment
<$> x .@? "attachTime"
<*> x .@? "attachmentId"
<*> x .@? "deleteOnTermination"
<*> x .@? "deviceIndex"
<*> x .@? "status"
instance ToQuery InstanceNetworkInterfaceAttachment where
toQuery InstanceNetworkInterfaceAttachment{..} = mconcat
[ "AttachTime" =? _iniaAttachTime
, "AttachmentId" =? _iniaAttachmentId
, "DeleteOnTermination" =? _iniaDeleteOnTermination
, "DeviceIndex" =? _iniaDeviceIndex
, "Status" =? _iniaStatus
]
newtype AttributeBooleanValue = AttributeBooleanValue
{ _abvValue :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'AttributeBooleanValue' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'abvValue' @::@ 'Maybe' 'Bool'
--
attributeBooleanValue :: AttributeBooleanValue
attributeBooleanValue = AttributeBooleanValue
{ _abvValue = Nothing
}
-- | Valid values are 'true' or 'false'.
abvValue :: Lens' AttributeBooleanValue (Maybe Bool)
abvValue = lens _abvValue (\s a -> s { _abvValue = a })
instance FromXML AttributeBooleanValue where
parseXML x = AttributeBooleanValue
<$> x .@? "value"
instance ToQuery AttributeBooleanValue where
toQuery AttributeBooleanValue{..} = mconcat
[ "Value" =? _abvValue
]
data RecurringCharge = RecurringCharge
{ _rcAmount :: Maybe Double
, _rcFrequency :: Maybe RecurringChargeFrequency
} deriving (Eq, Read, Show)
-- | 'RecurringCharge' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rcAmount' @::@ 'Maybe' 'Double'
--
-- * 'rcFrequency' @::@ 'Maybe' 'RecurringChargeFrequency'
--
recurringCharge :: RecurringCharge
recurringCharge = RecurringCharge
{ _rcFrequency = Nothing
, _rcAmount = Nothing
}
-- | The amount of the recurring charge.
rcAmount :: Lens' RecurringCharge (Maybe Double)
rcAmount = lens _rcAmount (\s a -> s { _rcAmount = a })
-- | The frequency of the recurring charge.
rcFrequency :: Lens' RecurringCharge (Maybe RecurringChargeFrequency)
rcFrequency = lens _rcFrequency (\s a -> s { _rcFrequency = a })
instance FromXML RecurringCharge where
parseXML x = RecurringCharge
<$> x .@? "amount"
<*> x .@? "frequency"
instance ToQuery RecurringCharge where
toQuery RecurringCharge{..} = mconcat
[ "Amount" =? _rcAmount
, "Frequency" =? _rcFrequency
]
data NewDhcpConfiguration = NewDhcpConfiguration
{ _ndcKey :: Maybe Text
, _ndcValues :: List "item" Text
} deriving (Eq, Ord, Read, Show)
-- | 'NewDhcpConfiguration' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ndcKey' @::@ 'Maybe' 'Text'
--
-- * 'ndcValues' @::@ ['Text']
--
newDhcpConfiguration :: NewDhcpConfiguration
newDhcpConfiguration = NewDhcpConfiguration
{ _ndcKey = Nothing
, _ndcValues = mempty
}
ndcKey :: Lens' NewDhcpConfiguration (Maybe Text)
ndcKey = lens _ndcKey (\s a -> s { _ndcKey = a })
ndcValues :: Lens' NewDhcpConfiguration [Text]
ndcValues = lens _ndcValues (\s a -> s { _ndcValues = a }) . _List
instance FromXML NewDhcpConfiguration where
parseXML x = NewDhcpConfiguration
<$> x .@? "key"
<*> x .@? "Value" .!@ mempty
instance ToQuery NewDhcpConfiguration where
toQuery NewDhcpConfiguration{..} = mconcat
[ "Key" =? _ndcKey
, "Value" `toQueryList` _ndcValues
]
data StateReason = StateReason
{ _srCode :: Maybe Text
, _srMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'StateReason' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'srCode' @::@ 'Maybe' 'Text'
--
-- * 'srMessage' @::@ 'Maybe' 'Text'
--
stateReason :: StateReason
stateReason = StateReason
{ _srCode = Nothing
, _srMessage = Nothing
}
-- | The reason code for the state change.
srCode :: Lens' StateReason (Maybe Text)
srCode = lens _srCode (\s a -> s { _srCode = a })
-- | The message for the state change.
--
-- 'Server.SpotInstanceTermination': A Spot Instance was terminated due to an
-- increase in the market price.
--
-- 'Server.InternalError': An internal error occurred during instance launch,
-- resulting in termination.
--
-- 'Server.InsufficientInstanceCapacity': There was insufficient instance
-- capacity to satisfy the launch request.
--
-- 'Client.InternalError': A client error caused the instance to terminate on
-- launch.
--
-- 'Client.InstanceInitiatedShutdown': The instance was shut down using the 'shutdown -h' command from the instance.
--
-- 'Client.UserInitiatedShutdown': The instance was shut down using the Amazon
-- EC2 API.
--
-- 'Client.VolumeLimitExceeded': The volume limit was exceeded.
--
-- 'Client.InvalidSnapshot.NotFound': The specified snapshot was not found.
--
--
srMessage :: Lens' StateReason (Maybe Text)
srMessage = lens _srMessage (\s a -> s { _srMessage = a })
instance FromXML StateReason where
parseXML x = StateReason
<$> x .@? "code"
<*> x .@? "message"
instance ToQuery StateReason where
toQuery StateReason{..} = mconcat
[ "Code" =? _srCode
, "Message" =? _srMessage
]
data MonitoringState
= MSDisabled -- ^ disabled
| MSEnabled -- ^ enabled
| MSPending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable MonitoringState
instance FromText MonitoringState where
parser = takeLowerText >>= \case
"disabled" -> pure MSDisabled
"enabled" -> pure MSEnabled
"pending" -> pure MSPending
e -> fail $
"Failure parsing MonitoringState from " ++ show e
instance ToText MonitoringState where
toText = \case
MSDisabled -> "disabled"
MSEnabled -> "enabled"
MSPending -> "pending"
instance ToByteString MonitoringState
instance ToHeader MonitoringState
instance ToQuery MonitoringState
instance FromXML MonitoringState where
parseXML = parseXMLText "MonitoringState"
newtype ReservedInstancesId = ReservedInstancesId
{ _riiReservedInstancesId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'ReservedInstancesId' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'riiReservedInstancesId' @::@ 'Maybe' 'Text'
--
reservedInstancesId :: ReservedInstancesId
reservedInstancesId = ReservedInstancesId
{ _riiReservedInstancesId = Nothing
}
-- | The ID of the Reserved Instance.
riiReservedInstancesId :: Lens' ReservedInstancesId (Maybe Text)
riiReservedInstancesId =
lens _riiReservedInstancesId (\s a -> s { _riiReservedInstancesId = a })
instance FromXML ReservedInstancesId where
parseXML x = ReservedInstancesId
<$> x .@? "reservedInstancesId"
instance ToQuery ReservedInstancesId where
toQuery ReservedInstancesId{..} = mconcat
[ "ReservedInstancesId" =? _riiReservedInstancesId
]
data StatusName
= Reachability -- ^ reachability
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable StatusName
instance FromText StatusName where
parser = takeLowerText >>= \case
"reachability" -> pure Reachability
e -> fail $
"Failure parsing StatusName from " ++ show e
instance ToText StatusName where
toText Reachability = "reachability"
instance ToByteString StatusName
instance ToHeader StatusName
instance ToQuery StatusName
instance FromXML StatusName where
parseXML = parseXMLText "StatusName"
data InternetGateway = InternetGateway
{ _igAttachments :: List "item" InternetGatewayAttachment
, _igInternetGatewayId :: Text
, _igTags :: List "item" Tag
} deriving (Eq, Read, Show)
-- | 'InternetGateway' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'igAttachments' @::@ ['InternetGatewayAttachment']
--
-- * 'igInternetGatewayId' @::@ 'Text'
--
-- * 'igTags' @::@ ['Tag']
--
internetGateway :: Text -- ^ 'igInternetGatewayId'
-> InternetGateway
internetGateway p1 = InternetGateway
{ _igInternetGatewayId = p1
, _igAttachments = mempty
, _igTags = mempty
}
-- | Any VPCs attached to the Internet gateway.
igAttachments :: Lens' InternetGateway [InternetGatewayAttachment]
igAttachments = lens _igAttachments (\s a -> s { _igAttachments = a }) . _List
-- | The ID of the Internet gateway.
igInternetGatewayId :: Lens' InternetGateway Text
igInternetGatewayId =
lens _igInternetGatewayId (\s a -> s { _igInternetGatewayId = a })
-- | Any tags assigned to the Internet gateway.
igTags :: Lens' InternetGateway [Tag]
igTags = lens _igTags (\s a -> s { _igTags = a }) . _List
instance FromXML InternetGateway where
parseXML x = InternetGateway
<$> x .@? "attachmentSet" .!@ mempty
<*> x .@ "internetGatewayId"
<*> x .@? "tagSet" .!@ mempty
instance ToQuery InternetGateway where
toQuery InternetGateway{..} = mconcat
[ "AttachmentSet" `toQueryList` _igAttachments
, "InternetGatewayId" =? _igInternetGatewayId
, "TagSet" `toQueryList` _igTags
]
data VolumeStatusName
= IoEnabled -- ^ io-enabled
| IoPerformance -- ^ io-performance
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeStatusName
instance FromText VolumeStatusName where
parser = takeLowerText >>= \case
"io-enabled" -> pure IoEnabled
"io-performance" -> pure IoPerformance
e -> fail $
"Failure parsing VolumeStatusName from " ++ show e
instance ToText VolumeStatusName where
toText = \case
IoEnabled -> "io-enabled"
IoPerformance -> "io-performance"
instance ToByteString VolumeStatusName
instance ToHeader VolumeStatusName
instance ToQuery VolumeStatusName
instance FromXML VolumeStatusName where
parseXML = parseXMLText "VolumeStatusName"
data VolumeAttributeName
= AutoEnableIO -- ^ autoEnableIO
| ProductCodes -- ^ productCodes
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeAttributeName
instance FromText VolumeAttributeName where
parser = takeLowerText >>= \case
"autoenableio" -> pure AutoEnableIO
"productcodes" -> pure ProductCodes
e -> fail $
"Failure parsing VolumeAttributeName from " ++ show e
instance ToText VolumeAttributeName where
toText = \case
AutoEnableIO -> "autoEnableIO"
ProductCodes -> "productCodes"
instance ToByteString VolumeAttributeName
instance ToHeader VolumeAttributeName
instance ToQuery VolumeAttributeName
instance FromXML VolumeAttributeName where
parseXML = parseXMLText "VolumeAttributeName"
data ImportInstanceTaskDetails = ImportInstanceTaskDetails
{ _iitdDescription :: Maybe Text
, _iitdInstanceId :: Maybe Text
, _iitdPlatform :: Maybe PlatformValues
, _iitdVolumes :: List "item" ImportInstanceVolumeDetailItem
} deriving (Eq, Read, Show)
-- | 'ImportInstanceTaskDetails' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'iitdDescription' @::@ 'Maybe' 'Text'
--
-- * 'iitdInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'iitdPlatform' @::@ 'Maybe' 'PlatformValues'
--
-- * 'iitdVolumes' @::@ ['ImportInstanceVolumeDetailItem']
--
importInstanceTaskDetails :: ImportInstanceTaskDetails
importInstanceTaskDetails = ImportInstanceTaskDetails
{ _iitdVolumes = mempty
, _iitdInstanceId = Nothing
, _iitdPlatform = Nothing
, _iitdDescription = Nothing
}
iitdDescription :: Lens' ImportInstanceTaskDetails (Maybe Text)
iitdDescription = lens _iitdDescription (\s a -> s { _iitdDescription = a })
iitdInstanceId :: Lens' ImportInstanceTaskDetails (Maybe Text)
iitdInstanceId = lens _iitdInstanceId (\s a -> s { _iitdInstanceId = a })
-- | The instance operating system.
iitdPlatform :: Lens' ImportInstanceTaskDetails (Maybe PlatformValues)
iitdPlatform = lens _iitdPlatform (\s a -> s { _iitdPlatform = a })
iitdVolumes :: Lens' ImportInstanceTaskDetails [ImportInstanceVolumeDetailItem]
iitdVolumes = lens _iitdVolumes (\s a -> s { _iitdVolumes = a }) . _List
instance FromXML ImportInstanceTaskDetails where
parseXML x = ImportInstanceTaskDetails
<$> x .@? "description"
<*> x .@? "instanceId"
<*> x .@? "platform"
<*> x .@? "volumes" .!@ mempty
instance ToQuery ImportInstanceTaskDetails where
toQuery ImportInstanceTaskDetails{..} = mconcat
[ "Description" =? _iitdDescription
, "InstanceId" =? _iitdInstanceId
, "Platform" =? _iitdPlatform
, "Volumes" `toQueryList` _iitdVolumes
]
data PlacementGroup = PlacementGroup
{ _pgGroupName :: Maybe Text
, _pgState :: Maybe PlacementGroupState
, _pgStrategy :: Maybe PlacementStrategy
} deriving (Eq, Read, Show)
-- | 'PlacementGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pgGroupName' @::@ 'Maybe' 'Text'
--
-- * 'pgState' @::@ 'Maybe' 'PlacementGroupState'
--
-- * 'pgStrategy' @::@ 'Maybe' 'PlacementStrategy'
--
placementGroup :: PlacementGroup
placementGroup = PlacementGroup
{ _pgGroupName = Nothing
, _pgStrategy = Nothing
, _pgState = Nothing
}
-- | The name of the placement group.
pgGroupName :: Lens' PlacementGroup (Maybe Text)
pgGroupName = lens _pgGroupName (\s a -> s { _pgGroupName = a })
-- | The state of the placement group.
pgState :: Lens' PlacementGroup (Maybe PlacementGroupState)
pgState = lens _pgState (\s a -> s { _pgState = a })
-- | The placement strategy.
pgStrategy :: Lens' PlacementGroup (Maybe PlacementStrategy)
pgStrategy = lens _pgStrategy (\s a -> s { _pgStrategy = a })
instance FromXML PlacementGroup where
parseXML x = PlacementGroup
<$> x .@? "groupName"
<*> x .@? "state"
<*> x .@? "strategy"
instance ToQuery PlacementGroup where
toQuery PlacementGroup{..} = mconcat
[ "GroupName" =? _pgGroupName
, "State" =? _pgState
, "Strategy" =? _pgStrategy
]
data ProductCode = ProductCode
{ _pcProductCodeId :: Maybe Text
, _pcProductCodeType :: Maybe ProductCodeValues
} deriving (Eq, Read, Show)
-- | 'ProductCode' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pcProductCodeId' @::@ 'Maybe' 'Text'
--
-- * 'pcProductCodeType' @::@ 'Maybe' 'ProductCodeValues'
--
productCode :: ProductCode
productCode = ProductCode
{ _pcProductCodeId = Nothing
, _pcProductCodeType = Nothing
}
-- | The product code.
pcProductCodeId :: Lens' ProductCode (Maybe Text)
pcProductCodeId = lens _pcProductCodeId (\s a -> s { _pcProductCodeId = a })
-- | The type of product code.
pcProductCodeType :: Lens' ProductCode (Maybe ProductCodeValues)
pcProductCodeType =
lens _pcProductCodeType (\s a -> s { _pcProductCodeType = a })
instance FromXML ProductCode where
parseXML x = ProductCode
<$> x .@? "productCode"
<*> x .@? "type"
instance ToQuery ProductCode where
toQuery ProductCode{..} = mconcat
[ "ProductCode" =? _pcProductCodeId
, "Type" =? _pcProductCodeType
]
data ListingStatus
= ListingStatusActive -- ^ active
| ListingStatusCancelled -- ^ cancelled
| ListingStatusClosed -- ^ closed
| ListingStatusPending -- ^ pending
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ListingStatus
instance FromText ListingStatus where
parser = takeLowerText >>= \case
"active" -> pure ListingStatusActive
"cancelled" -> pure ListingStatusCancelled
"closed" -> pure ListingStatusClosed
"pending" -> pure ListingStatusPending
e -> fail $
"Failure parsing ListingStatus from " ++ show e
instance ToText ListingStatus where
toText = \case
ListingStatusActive -> "active"
ListingStatusCancelled -> "cancelled"
ListingStatusClosed -> "closed"
ListingStatusPending -> "pending"
instance ToByteString ListingStatus
instance ToHeader ListingStatus
instance ToQuery ListingStatus
instance FromXML ListingStatus where
parseXML = parseXMLText "ListingStatus"
newtype IpRange = IpRange
{ _irCidrIp :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'IpRange' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'irCidrIp' @::@ 'Text'
--
ipRange :: Text -- ^ 'irCidrIp'
-> IpRange
ipRange p1 = IpRange
{ _irCidrIp = p1
}
-- | The CIDR range. You can either specify a CIDR range or a source security
-- group, not both.
irCidrIp :: Lens' IpRange Text
irCidrIp = lens _irCidrIp (\s a -> s { _irCidrIp = a })
instance FromXML IpRange where
parseXML x = IpRange
<$> x .@ "cidrIp"
instance ToQuery IpRange where
toQuery IpRange{..} = mconcat
[ "CidrIp" =? _irCidrIp
]
data VolumeStatusInfoStatus
= VSISImpaired -- ^ impaired
| VSISInsufficientData -- ^ insufficient-data
| VSISOk -- ^ ok
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable VolumeStatusInfoStatus
instance FromText VolumeStatusInfoStatus where
parser = takeLowerText >>= \case
"impaired" -> pure VSISImpaired
"insufficient-data" -> pure VSISInsufficientData
"ok" -> pure VSISOk
e -> fail $
"Failure parsing VolumeStatusInfoStatus from " ++ show e
instance ToText VolumeStatusInfoStatus where
toText = \case
VSISImpaired -> "impaired"
VSISInsufficientData -> "insufficient-data"
VSISOk -> "ok"
instance ToByteString VolumeStatusInfoStatus
instance ToHeader VolumeStatusInfoStatus
instance ToQuery VolumeStatusInfoStatus
instance FromXML VolumeStatusInfoStatus where
parseXML = parseXMLText "VolumeStatusInfoStatus"
newtype AccountAttributeValue = AccountAttributeValue
{ _aavAttributeValue :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'AccountAttributeValue' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'aavAttributeValue' @::@ 'Maybe' 'Text'
--
accountAttributeValue :: AccountAttributeValue
accountAttributeValue = AccountAttributeValue
{ _aavAttributeValue = Nothing
}
-- | The value of the attribute.
aavAttributeValue :: Lens' AccountAttributeValue (Maybe Text)
aavAttributeValue =
lens _aavAttributeValue (\s a -> s { _aavAttributeValue = a })
instance FromXML AccountAttributeValue where
parseXML x = AccountAttributeValue
<$> x .@? "attributeValue"
instance ToQuery AccountAttributeValue where
toQuery AccountAttributeValue{..} = mconcat
[ "AttributeValue" =? _aavAttributeValue
]
data RIProductDescription
= RIPDLinuxUNIX -- ^ Linux/UNIX
| RIPDLinuxUNIXAmazonVPC -- ^ Linux/UNIX (Amazon VPC)
| RIPDWindows -- ^ Windows
| RIPDWindowsAmazonVPC -- ^ Windows (Amazon VPC)
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable RIProductDescription
instance FromText RIProductDescription where
parser = takeLowerText >>= \case
"linux/unix" -> pure RIPDLinuxUNIX
"linux/unix (amazon vpc)" -> pure RIPDLinuxUNIXAmazonVPC
"windows" -> pure RIPDWindows
"windows (amazon vpc)" -> pure RIPDWindowsAmazonVPC
e -> fail $
"Failure parsing RIProductDescription from " ++ show e
instance ToText RIProductDescription where
toText = \case
RIPDLinuxUNIX -> "Linux/UNIX"
RIPDLinuxUNIXAmazonVPC -> "Linux/UNIX (Amazon VPC)"
RIPDWindows -> "Windows"
RIPDWindowsAmazonVPC -> "Windows (Amazon VPC)"
instance ToByteString RIProductDescription
instance ToHeader RIProductDescription
instance ToQuery RIProductDescription
instance FromXML RIProductDescription where
parseXML = parseXMLText "RIProductDescription"
data ReservedInstancesOffering = ReservedInstancesOffering
{ _rioAvailabilityZone :: Maybe Text
, _rioCurrencyCode :: Maybe CurrencyCodeValues
, _rioDuration :: Maybe Integer
, _rioFixedPrice :: Maybe Double
, _rioInstanceTenancy :: Maybe Tenancy
, _rioInstanceType :: Maybe InstanceType
, _rioMarketplace :: Maybe Bool
, _rioOfferingType :: Maybe OfferingTypeValues
, _rioPricingDetails :: List "item" PricingDetail
, _rioProductDescription :: Maybe RIProductDescription
, _rioRecurringCharges :: List "item" RecurringCharge
, _rioReservedInstancesOfferingId :: Maybe Text
, _rioUsagePrice :: Maybe Double
} deriving (Eq, Read, Show)
-- | 'ReservedInstancesOffering' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rioAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'rioCurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues'
--
-- * 'rioDuration' @::@ 'Maybe' 'Integer'
--
-- * 'rioFixedPrice' @::@ 'Maybe' 'Double'
--
-- * 'rioInstanceTenancy' @::@ 'Maybe' 'Tenancy'
--
-- * 'rioInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'rioMarketplace' @::@ 'Maybe' 'Bool'
--
-- * 'rioOfferingType' @::@ 'Maybe' 'OfferingTypeValues'
--
-- * 'rioPricingDetails' @::@ ['PricingDetail']
--
-- * 'rioProductDescription' @::@ 'Maybe' 'RIProductDescription'
--
-- * 'rioRecurringCharges' @::@ ['RecurringCharge']
--
-- * 'rioReservedInstancesOfferingId' @::@ 'Maybe' 'Text'
--
-- * 'rioUsagePrice' @::@ 'Maybe' 'Double'
--
reservedInstancesOffering :: ReservedInstancesOffering
reservedInstancesOffering = ReservedInstancesOffering
{ _rioReservedInstancesOfferingId = Nothing
, _rioInstanceType = Nothing
, _rioAvailabilityZone = Nothing
, _rioDuration = Nothing
, _rioUsagePrice = Nothing
, _rioFixedPrice = Nothing
, _rioProductDescription = Nothing
, _rioInstanceTenancy = Nothing
, _rioCurrencyCode = Nothing
, _rioOfferingType = Nothing
, _rioRecurringCharges = mempty
, _rioMarketplace = Nothing
, _rioPricingDetails = mempty
}
-- | The Availability Zone in which the Reserved Instance can be used.
rioAvailabilityZone :: Lens' ReservedInstancesOffering (Maybe Text)
rioAvailabilityZone =
lens _rioAvailabilityZone (\s a -> s { _rioAvailabilityZone = a })
-- | The currency of the Reserved Instance offering you are purchasing. It's
-- specified using ISO 4217 standard currency codes. At this time, the only
-- supported currency is 'USD'.
rioCurrencyCode :: Lens' ReservedInstancesOffering (Maybe CurrencyCodeValues)
rioCurrencyCode = lens _rioCurrencyCode (\s a -> s { _rioCurrencyCode = a })
-- | The duration of the Reserved Instance, in seconds.
rioDuration :: Lens' ReservedInstancesOffering (Maybe Integer)
rioDuration = lens _rioDuration (\s a -> s { _rioDuration = a })
-- | The purchase price of the Reserved Instance.
rioFixedPrice :: Lens' ReservedInstancesOffering (Maybe Double)
rioFixedPrice = lens _rioFixedPrice (\s a -> s { _rioFixedPrice = a })
-- | The tenancy of the reserved instance.
rioInstanceTenancy :: Lens' ReservedInstancesOffering (Maybe Tenancy)
rioInstanceTenancy =
lens _rioInstanceTenancy (\s a -> s { _rioInstanceTenancy = a })
-- | The instance type on which the Reserved Instance can be used.
rioInstanceType :: Lens' ReservedInstancesOffering (Maybe InstanceType)
rioInstanceType = lens _rioInstanceType (\s a -> s { _rioInstanceType = a })
-- | Indicates whether the offering is available through the Reserved Instance
-- Marketplace (resale) or AWS. If it's a Reserved Instance Marketplace
-- offering, this is 'true'.
rioMarketplace :: Lens' ReservedInstancesOffering (Maybe Bool)
rioMarketplace = lens _rioMarketplace (\s a -> s { _rioMarketplace = a })
-- | The Reserved Instance offering type.
rioOfferingType :: Lens' ReservedInstancesOffering (Maybe OfferingTypeValues)
rioOfferingType = lens _rioOfferingType (\s a -> s { _rioOfferingType = a })
-- | The pricing details of the Reserved Instance offering.
rioPricingDetails :: Lens' ReservedInstancesOffering [PricingDetail]
rioPricingDetails =
lens _rioPricingDetails (\s a -> s { _rioPricingDetails = a })
. _List
-- | The Reserved Instance description.
rioProductDescription :: Lens' ReservedInstancesOffering (Maybe RIProductDescription)
rioProductDescription =
lens _rioProductDescription (\s a -> s { _rioProductDescription = a })
-- | The recurring charge tag assigned to the resource.
rioRecurringCharges :: Lens' ReservedInstancesOffering [RecurringCharge]
rioRecurringCharges =
lens _rioRecurringCharges (\s a -> s { _rioRecurringCharges = a })
. _List
-- | The ID of the Reserved Instance offering.
rioReservedInstancesOfferingId :: Lens' ReservedInstancesOffering (Maybe Text)
rioReservedInstancesOfferingId =
lens _rioReservedInstancesOfferingId
(\s a -> s { _rioReservedInstancesOfferingId = a })
-- | The usage price of the Reserved Instance, per hour.
rioUsagePrice :: Lens' ReservedInstancesOffering (Maybe Double)
rioUsagePrice = lens _rioUsagePrice (\s a -> s { _rioUsagePrice = a })
instance FromXML ReservedInstancesOffering where
parseXML x = ReservedInstancesOffering
<$> x .@? "availabilityZone"
<*> x .@? "currencyCode"
<*> x .@? "duration"
<*> x .@? "fixedPrice"
<*> x .@? "instanceTenancy"
<*> x .@? "instanceType"
<*> x .@? "marketplace"
<*> x .@? "offeringType"
<*> x .@? "pricingDetailsSet" .!@ mempty
<*> x .@? "productDescription"
<*> x .@? "recurringCharges" .!@ mempty
<*> x .@? "reservedInstancesOfferingId"
<*> x .@? "usagePrice"
instance ToQuery ReservedInstancesOffering where
toQuery ReservedInstancesOffering{..} = mconcat
[ "AvailabilityZone" =? _rioAvailabilityZone
, "CurrencyCode" =? _rioCurrencyCode
, "Duration" =? _rioDuration
, "FixedPrice" =? _rioFixedPrice
, "InstanceTenancy" =? _rioInstanceTenancy
, "InstanceType" =? _rioInstanceType
, "Marketplace" =? _rioMarketplace
, "OfferingType" =? _rioOfferingType
, "PricingDetailsSet" `toQueryList` _rioPricingDetails
, "ProductDescription" =? _rioProductDescription
, "RecurringCharges" `toQueryList` _rioRecurringCharges
, "ReservedInstancesOfferingId" =? _rioReservedInstancesOfferingId
, "UsagePrice" =? _rioUsagePrice
]
data ReservedInstances = ReservedInstances
{ _ri1AvailabilityZone :: Maybe Text
, _ri1CurrencyCode :: Maybe CurrencyCodeValues
, _ri1Duration :: Maybe Integer
, _ri1End :: Maybe ISO8601
, _ri1FixedPrice :: Maybe Double
, _ri1InstanceCount :: Maybe Int
, _ri1InstanceTenancy :: Maybe Tenancy
, _ri1InstanceType :: Maybe InstanceType
, _ri1OfferingType :: Maybe OfferingTypeValues
, _ri1ProductDescription :: Maybe RIProductDescription
, _ri1RecurringCharges :: List "item" RecurringCharge
, _ri1ReservedInstancesId :: Maybe Text
, _ri1Start :: Maybe ISO8601
, _ri1State :: Maybe ReservedInstanceState
, _ri1Tags :: List "item" Tag
, _ri1UsagePrice :: Maybe Double
} deriving (Eq, Read, Show)
-- | 'ReservedInstances' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ri1AvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'ri1CurrencyCode' @::@ 'Maybe' 'CurrencyCodeValues'
--
-- * 'ri1Duration' @::@ 'Maybe' 'Integer'
--
-- * 'ri1End' @::@ 'Maybe' 'UTCTime'
--
-- * 'ri1FixedPrice' @::@ 'Maybe' 'Double'
--
-- * 'ri1InstanceCount' @::@ 'Maybe' 'Int'
--
-- * 'ri1InstanceTenancy' @::@ 'Maybe' 'Tenancy'
--
-- * 'ri1InstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'ri1OfferingType' @::@ 'Maybe' 'OfferingTypeValues'
--
-- * 'ri1ProductDescription' @::@ 'Maybe' 'RIProductDescription'
--
-- * 'ri1RecurringCharges' @::@ ['RecurringCharge']
--
-- * 'ri1ReservedInstancesId' @::@ 'Maybe' 'Text'
--
-- * 'ri1Start' @::@ 'Maybe' 'UTCTime'
--
-- * 'ri1State' @::@ 'Maybe' 'ReservedInstanceState'
--
-- * 'ri1Tags' @::@ ['Tag']
--
-- * 'ri1UsagePrice' @::@ 'Maybe' 'Double'
--
reservedInstances :: ReservedInstances
reservedInstances = ReservedInstances
{ _ri1ReservedInstancesId = Nothing
, _ri1InstanceType = Nothing
, _ri1AvailabilityZone = Nothing
, _ri1Start = Nothing
, _ri1End = Nothing
, _ri1Duration = Nothing
, _ri1UsagePrice = Nothing
, _ri1FixedPrice = Nothing
, _ri1InstanceCount = Nothing
, _ri1ProductDescription = Nothing
, _ri1State = Nothing
, _ri1Tags = mempty
, _ri1InstanceTenancy = Nothing
, _ri1CurrencyCode = Nothing
, _ri1OfferingType = Nothing
, _ri1RecurringCharges = mempty
}
-- | The Availability Zone in which the Reserved Instance can be used.
ri1AvailabilityZone :: Lens' ReservedInstances (Maybe Text)
ri1AvailabilityZone =
lens _ri1AvailabilityZone (\s a -> s { _ri1AvailabilityZone = a })
-- | The currency of the Reserved Instance. It's specified using ISO 4217 standard
-- currency codes. At this time, the only supported currency is 'USD'.
ri1CurrencyCode :: Lens' ReservedInstances (Maybe CurrencyCodeValues)
ri1CurrencyCode = lens _ri1CurrencyCode (\s a -> s { _ri1CurrencyCode = a })
-- | The duration of the Reserved Instance, in seconds.
ri1Duration :: Lens' ReservedInstances (Maybe Integer)
ri1Duration = lens _ri1Duration (\s a -> s { _ri1Duration = a })
-- | The time when the Reserved Instance expires.
ri1End :: Lens' ReservedInstances (Maybe UTCTime)
ri1End = lens _ri1End (\s a -> s { _ri1End = a }) . mapping _Time
-- | The purchase price of the Reserved Instance.
ri1FixedPrice :: Lens' ReservedInstances (Maybe Double)
ri1FixedPrice = lens _ri1FixedPrice (\s a -> s { _ri1FixedPrice = a })
-- | The number of Reserved Instances purchased.
ri1InstanceCount :: Lens' ReservedInstances (Maybe Int)
ri1InstanceCount = lens _ri1InstanceCount (\s a -> s { _ri1InstanceCount = a })
-- | The tenancy of the reserved instance.
ri1InstanceTenancy :: Lens' ReservedInstances (Maybe Tenancy)
ri1InstanceTenancy =
lens _ri1InstanceTenancy (\s a -> s { _ri1InstanceTenancy = a })
-- | The instance type on which the Reserved Instance can be used.
ri1InstanceType :: Lens' ReservedInstances (Maybe InstanceType)
ri1InstanceType = lens _ri1InstanceType (\s a -> s { _ri1InstanceType = a })
-- | The Reserved Instance offering type.
ri1OfferingType :: Lens' ReservedInstances (Maybe OfferingTypeValues)
ri1OfferingType = lens _ri1OfferingType (\s a -> s { _ri1OfferingType = a })
-- | The Reserved Instance description.
ri1ProductDescription :: Lens' ReservedInstances (Maybe RIProductDescription)
ri1ProductDescription =
lens _ri1ProductDescription (\s a -> s { _ri1ProductDescription = a })
-- | The recurring charge tag assigned to the resource.
ri1RecurringCharges :: Lens' ReservedInstances [RecurringCharge]
ri1RecurringCharges =
lens _ri1RecurringCharges (\s a -> s { _ri1RecurringCharges = a })
. _List
-- | The ID of the Reserved Instance.
ri1ReservedInstancesId :: Lens' ReservedInstances (Maybe Text)
ri1ReservedInstancesId =
lens _ri1ReservedInstancesId (\s a -> s { _ri1ReservedInstancesId = a })
-- | The date and time the Reserved Instance started.
ri1Start :: Lens' ReservedInstances (Maybe UTCTime)
ri1Start = lens _ri1Start (\s a -> s { _ri1Start = a }) . mapping _Time
-- | The state of the Reserved Instance purchase.
ri1State :: Lens' ReservedInstances (Maybe ReservedInstanceState)
ri1State = lens _ri1State (\s a -> s { _ri1State = a })
-- | Any tags assigned to the resource.
ri1Tags :: Lens' ReservedInstances [Tag]
ri1Tags = lens _ri1Tags (\s a -> s { _ri1Tags = a }) . _List
-- | The usage price of the Reserved Instance, per hour.
ri1UsagePrice :: Lens' ReservedInstances (Maybe Double)
ri1UsagePrice = lens _ri1UsagePrice (\s a -> s { _ri1UsagePrice = a })
instance FromXML ReservedInstances where
parseXML x = ReservedInstances
<$> x .@? "availabilityZone"
<*> x .@? "currencyCode"
<*> x .@? "duration"
<*> x .@? "end"
<*> x .@? "fixedPrice"
<*> x .@? "instanceCount"
<*> x .@? "instanceTenancy"
<*> x .@? "instanceType"
<*> x .@? "offeringType"
<*> x .@? "productDescription"
<*> x .@? "recurringCharges" .!@ mempty
<*> x .@? "reservedInstancesId"
<*> x .@? "start"
<*> x .@? "state"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "usagePrice"
instance ToQuery ReservedInstances where
toQuery ReservedInstances{..} = mconcat
[ "AvailabilityZone" =? _ri1AvailabilityZone
, "CurrencyCode" =? _ri1CurrencyCode
, "Duration" =? _ri1Duration
, "End" =? _ri1End
, "FixedPrice" =? _ri1FixedPrice
, "InstanceCount" =? _ri1InstanceCount
, "InstanceTenancy" =? _ri1InstanceTenancy
, "InstanceType" =? _ri1InstanceType
, "OfferingType" =? _ri1OfferingType
, "ProductDescription" =? _ri1ProductDescription
, "RecurringCharges" `toQueryList` _ri1RecurringCharges
, "ReservedInstancesId" =? _ri1ReservedInstancesId
, "Start" =? _ri1Start
, "State" =? _ri1State
, "TagSet" `toQueryList` _ri1Tags
, "UsagePrice" =? _ri1UsagePrice
]
data DatafeedSubscriptionState
= DSSActive -- ^ Active
| DSSInactive -- ^ Inactive
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable DatafeedSubscriptionState
instance FromText DatafeedSubscriptionState where
parser = takeLowerText >>= \case
"active" -> pure DSSActive
"inactive" -> pure DSSInactive
e -> fail $
"Failure parsing DatafeedSubscriptionState from " ++ show e
instance ToText DatafeedSubscriptionState where
toText = \case
DSSActive -> "Active"
DSSInactive -> "Inactive"
instance ToByteString DatafeedSubscriptionState
instance ToHeader DatafeedSubscriptionState
instance ToQuery DatafeedSubscriptionState
instance FromXML DatafeedSubscriptionState where
parseXML = parseXMLText "DatafeedSubscriptionState"
data ExportTaskState
= ETSActive -- ^ active
| ETSCancelled -- ^ cancelled
| ETSCancelling -- ^ cancelling
| ETSCompleted -- ^ completed
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ExportTaskState
instance FromText ExportTaskState where
parser = takeLowerText >>= \case
"active" -> pure ETSActive
"cancelled" -> pure ETSCancelled
"cancelling" -> pure ETSCancelling
"completed" -> pure ETSCompleted
e -> fail $
"Failure parsing ExportTaskState from " ++ show e
instance ToText ExportTaskState where
toText = \case
ETSActive -> "active"
ETSCancelled -> "cancelled"
ETSCancelling -> "cancelling"
ETSCompleted -> "completed"
instance ToByteString ExportTaskState
instance ToHeader ExportTaskState
instance ToQuery ExportTaskState
instance FromXML ExportTaskState where
parseXML = parseXMLText "ExportTaskState"
data ProductCodeValues
= Devpay -- ^ devpay
| Marketplace -- ^ marketplace
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ProductCodeValues
instance FromText ProductCodeValues where
parser = takeLowerText >>= \case
"devpay" -> pure Devpay
"marketplace" -> pure Marketplace
e -> fail $
"Failure parsing ProductCodeValues from " ++ show e
instance ToText ProductCodeValues where
toText = \case
Devpay -> "devpay"
Marketplace -> "marketplace"
instance ToByteString ProductCodeValues
instance ToHeader ProductCodeValues
instance ToQuery ProductCodeValues
instance FromXML ProductCodeValues where
parseXML = parseXMLText "ProductCodeValues"
data VpnConnection = VpnConnection
{ _vcCustomerGatewayConfiguration :: Text
, _vcCustomerGatewayId :: Text
, _vcOptions :: Maybe VpnConnectionOptions
, _vcRoutes :: List "item" VpnStaticRoute
, _vcState :: VpnState
, _vcTags :: List "item" Tag
, _vcType :: GatewayType
, _vcVgwTelemetry :: List "item" VgwTelemetry
, _vcVpnConnectionId :: Text
, _vcVpnGatewayId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VpnConnection' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vcCustomerGatewayConfiguration' @::@ 'Text'
--
-- * 'vcCustomerGatewayId' @::@ 'Text'
--
-- * 'vcOptions' @::@ 'Maybe' 'VpnConnectionOptions'
--
-- * 'vcRoutes' @::@ ['VpnStaticRoute']
--
-- * 'vcState' @::@ 'VpnState'
--
-- * 'vcTags' @::@ ['Tag']
--
-- * 'vcType' @::@ 'GatewayType'
--
-- * 'vcVgwTelemetry' @::@ ['VgwTelemetry']
--
-- * 'vcVpnConnectionId' @::@ 'Text'
--
-- * 'vcVpnGatewayId' @::@ 'Maybe' 'Text'
--
vpnConnection :: Text -- ^ 'vcVpnConnectionId'
-> VpnState -- ^ 'vcState'
-> Text -- ^ 'vcCustomerGatewayConfiguration'
-> GatewayType -- ^ 'vcType'
-> Text -- ^ 'vcCustomerGatewayId'
-> VpnConnection
vpnConnection p1 p2 p3 p4 p5 = VpnConnection
{ _vcVpnConnectionId = p1
, _vcState = p2
, _vcCustomerGatewayConfiguration = p3
, _vcType = p4
, _vcCustomerGatewayId = p5
, _vcVpnGatewayId = Nothing
, _vcTags = mempty
, _vcVgwTelemetry = mempty
, _vcOptions = Nothing
, _vcRoutes = mempty
}
-- | The configuration information for the VPN connection's customer gateway (in
-- the native XML format). This element is always present in the 'CreateVpnConnection' response; however, it's present in the 'DescribeVpnConnections' response only
-- if the VPN connection is in the 'pending' or 'available' state.
vcCustomerGatewayConfiguration :: Lens' VpnConnection Text
vcCustomerGatewayConfiguration =
lens _vcCustomerGatewayConfiguration
(\s a -> s { _vcCustomerGatewayConfiguration = a })
-- | The ID of the customer gateway at your end of the VPN connection.
vcCustomerGatewayId :: Lens' VpnConnection Text
vcCustomerGatewayId =
lens _vcCustomerGatewayId (\s a -> s { _vcCustomerGatewayId = a })
-- | The VPN connection options.
vcOptions :: Lens' VpnConnection (Maybe VpnConnectionOptions)
vcOptions = lens _vcOptions (\s a -> s { _vcOptions = a })
-- | The static routes associated with the VPN connection.
vcRoutes :: Lens' VpnConnection [VpnStaticRoute]
vcRoutes = lens _vcRoutes (\s a -> s { _vcRoutes = a }) . _List
-- | The current state of the VPN connection.
vcState :: Lens' VpnConnection VpnState
vcState = lens _vcState (\s a -> s { _vcState = a })
-- | Any tags assigned to the VPN connection.
vcTags :: Lens' VpnConnection [Tag]
vcTags = lens _vcTags (\s a -> s { _vcTags = a }) . _List
-- | The type of VPN connection.
vcType :: Lens' VpnConnection GatewayType
vcType = lens _vcType (\s a -> s { _vcType = a })
-- | Information about the VPN tunnel.
vcVgwTelemetry :: Lens' VpnConnection [VgwTelemetry]
vcVgwTelemetry = lens _vcVgwTelemetry (\s a -> s { _vcVgwTelemetry = a }) . _List
-- | The ID of the VPN connection.
vcVpnConnectionId :: Lens' VpnConnection Text
vcVpnConnectionId =
lens _vcVpnConnectionId (\s a -> s { _vcVpnConnectionId = a })
-- | The ID of the virtual private gateway at the AWS side of the VPN connection.
vcVpnGatewayId :: Lens' VpnConnection (Maybe Text)
vcVpnGatewayId = lens _vcVpnGatewayId (\s a -> s { _vcVpnGatewayId = a })
instance FromXML VpnConnection where
parseXML x = VpnConnection
<$> x .@ "customerGatewayConfiguration"
<*> x .@ "customerGatewayId"
<*> x .@? "options"
<*> x .@? "routes" .!@ mempty
<*> x .@ "state"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "type"
<*> x .@? "vgwTelemetry" .!@ mempty
<*> x .@ "vpnConnectionId"
<*> x .@? "vpnGatewayId"
instance ToQuery VpnConnection where
toQuery VpnConnection{..} = mconcat
[ "CustomerGatewayConfiguration" =? _vcCustomerGatewayConfiguration
, "CustomerGatewayId" =? _vcCustomerGatewayId
, "Options" =? _vcOptions
, "Routes" `toQueryList` _vcRoutes
, "State" =? _vcState
, "TagSet" `toQueryList` _vcTags
, "Type" =? _vcType
, "VgwTelemetry" `toQueryList` _vcVgwTelemetry
, "VpnConnectionId" =? _vcVpnConnectionId
, "VpnGatewayId" =? _vcVpnGatewayId
]
data InstanceState = InstanceState
{ _isCode :: Int
, _isName :: InstanceStateName
} deriving (Eq, Read, Show)
-- | 'InstanceState' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'isCode' @::@ 'Int'
--
-- * 'isName' @::@ 'InstanceStateName'
--
instanceState :: Int -- ^ 'isCode'
-> InstanceStateName -- ^ 'isName'
-> InstanceState
instanceState p1 p2 = InstanceState
{ _isCode = p1
, _isName = p2
}
-- | The low byte represents the state. The high byte is an opaque internal value
-- and should be ignored.
--
-- '0' : 'pending'
--
-- '16' : 'running'
--
-- '32' : 'shutting-down'
--
-- '48' : 'terminated'
--
-- '64' : 'stopping'
--
-- '80' : 'stopped'
--
--
isCode :: Lens' InstanceState Int
isCode = lens _isCode (\s a -> s { _isCode = a })
-- | The current state of the instance.
isName :: Lens' InstanceState InstanceStateName
isName = lens _isName (\s a -> s { _isName = a })
instance FromXML InstanceState where
parseXML x = InstanceState
<$> x .@ "code"
<*> x .@ "name"
instance ToQuery InstanceState where
toQuery InstanceState{..} = mconcat
[ "Code" =? _isCode
, "Name" =? _isName
]
data Placement = Placement
{ _pAvailabilityZone :: Maybe Text
, _pGroupName :: Maybe Text
, _pTenancy :: Maybe Tenancy
} deriving (Eq, Read, Show)
-- | 'Placement' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'pGroupName' @::@ 'Maybe' 'Text'
--
-- * 'pTenancy' @::@ 'Maybe' 'Tenancy'
--
placement :: Placement
placement = Placement
{ _pAvailabilityZone = Nothing
, _pGroupName = Nothing
, _pTenancy = Nothing
}
-- | The Availability Zone of the instance.
pAvailabilityZone :: Lens' Placement (Maybe Text)
pAvailabilityZone =
lens _pAvailabilityZone (\s a -> s { _pAvailabilityZone = a })
-- | The name of the placement group the instance is in (for cluster compute
-- instances).
pGroupName :: Lens' Placement (Maybe Text)
pGroupName = lens _pGroupName (\s a -> s { _pGroupName = a })
-- | The tenancy of the instance (if the instance is running in a VPC). An
-- instance with a tenancy of 'dedicated' runs on single-tenant hardware.
pTenancy :: Lens' Placement (Maybe Tenancy)
pTenancy = lens _pTenancy (\s a -> s { _pTenancy = a })
instance FromXML Placement where
parseXML x = Placement
<$> x .@? "availabilityZone"
<*> x .@? "groupName"
<*> x .@? "tenancy"
instance ToQuery Placement where
toQuery Placement{..} = mconcat
[ "AvailabilityZone" =? _pAvailabilityZone
, "GroupName" =? _pGroupName
, "Tenancy" =? _pTenancy
]
data EventCode
= InstanceReboot -- ^ instance-reboot
| InstanceRetirement -- ^ instance-retirement
| InstanceStop -- ^ instance-stop
| SystemMaintenance -- ^ system-maintenance
| SystemReboot -- ^ system-reboot
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable EventCode
instance FromText EventCode where
parser = takeLowerText >>= \case
"instance-reboot" -> pure InstanceReboot
"instance-retirement" -> pure InstanceRetirement
"instance-stop" -> pure InstanceStop
"system-maintenance" -> pure SystemMaintenance
"system-reboot" -> pure SystemReboot
e -> fail $
"Failure parsing EventCode from " ++ show e
instance ToText EventCode where
toText = \case
InstanceReboot -> "instance-reboot"
InstanceRetirement -> "instance-retirement"
InstanceStop -> "instance-stop"
SystemMaintenance -> "system-maintenance"
SystemReboot -> "system-reboot"
instance ToByteString EventCode
instance ToHeader EventCode
instance ToQuery EventCode
instance FromXML EventCode where
parseXML = parseXMLText "EventCode"
data SpotInstanceType
= OneTime -- ^ one-time
| Persistent -- ^ persistent
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SpotInstanceType
instance FromText SpotInstanceType where
parser = takeLowerText >>= \case
"one-time" -> pure OneTime
"persistent" -> pure Persistent
e -> fail $
"Failure parsing SpotInstanceType from " ++ show e
instance ToText SpotInstanceType where
toText = \case
OneTime -> "one-time"
Persistent -> "persistent"
instance ToByteString SpotInstanceType
instance ToHeader SpotInstanceType
instance ToQuery SpotInstanceType
instance FromXML SpotInstanceType where
parseXML = parseXMLText "SpotInstanceType"
data VpcPeeringConnection = VpcPeeringConnection
{ _vpc1AccepterVpcInfo :: Maybe VpcPeeringConnectionVpcInfo
, _vpc1ExpirationTime :: Maybe ISO8601
, _vpc1RequesterVpcInfo :: Maybe VpcPeeringConnectionVpcInfo
, _vpc1Status :: Maybe VpcPeeringConnectionStateReason
, _vpc1Tags :: List "item" Tag
, _vpc1VpcPeeringConnectionId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VpcPeeringConnection' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vpc1AccepterVpcInfo' @::@ 'Maybe' 'VpcPeeringConnectionVpcInfo'
--
-- * 'vpc1ExpirationTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'vpc1RequesterVpcInfo' @::@ 'Maybe' 'VpcPeeringConnectionVpcInfo'
--
-- * 'vpc1Status' @::@ 'Maybe' 'VpcPeeringConnectionStateReason'
--
-- * 'vpc1Tags' @::@ ['Tag']
--
-- * 'vpc1VpcPeeringConnectionId' @::@ 'Maybe' 'Text'
--
vpcPeeringConnection :: VpcPeeringConnection
vpcPeeringConnection = VpcPeeringConnection
{ _vpc1AccepterVpcInfo = Nothing
, _vpc1ExpirationTime = Nothing
, _vpc1RequesterVpcInfo = Nothing
, _vpc1Status = Nothing
, _vpc1Tags = mempty
, _vpc1VpcPeeringConnectionId = Nothing
}
-- | The information of the peer VPC.
vpc1AccepterVpcInfo :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionVpcInfo)
vpc1AccepterVpcInfo =
lens _vpc1AccepterVpcInfo (\s a -> s { _vpc1AccepterVpcInfo = a })
-- | The time that an unaccepted VPC peering connection will expire.
vpc1ExpirationTime :: Lens' VpcPeeringConnection (Maybe UTCTime)
vpc1ExpirationTime =
lens _vpc1ExpirationTime (\s a -> s { _vpc1ExpirationTime = a })
. mapping _Time
-- | The information of the requester VPC.
vpc1RequesterVpcInfo :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionVpcInfo)
vpc1RequesterVpcInfo =
lens _vpc1RequesterVpcInfo (\s a -> s { _vpc1RequesterVpcInfo = a })
-- | The status of the VPC peering connection.
vpc1Status :: Lens' VpcPeeringConnection (Maybe VpcPeeringConnectionStateReason)
vpc1Status = lens _vpc1Status (\s a -> s { _vpc1Status = a })
-- | Any tags assigned to the resource.
vpc1Tags :: Lens' VpcPeeringConnection [Tag]
vpc1Tags = lens _vpc1Tags (\s a -> s { _vpc1Tags = a }) . _List
-- | The ID of the VPC peering connection.
vpc1VpcPeeringConnectionId :: Lens' VpcPeeringConnection (Maybe Text)
vpc1VpcPeeringConnectionId =
lens _vpc1VpcPeeringConnectionId
(\s a -> s { _vpc1VpcPeeringConnectionId = a })
instance FromXML VpcPeeringConnection where
parseXML x = VpcPeeringConnection
<$> x .@? "accepterVpcInfo"
<*> x .@? "expirationTime"
<*> x .@? "requesterVpcInfo"
<*> x .@? "status"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcPeeringConnectionId"
instance ToQuery VpcPeeringConnection where
toQuery VpcPeeringConnection{..} = mconcat
[ "AccepterVpcInfo" =? _vpc1AccepterVpcInfo
, "ExpirationTime" =? _vpc1ExpirationTime
, "RequesterVpcInfo" =? _vpc1RequesterVpcInfo
, "Status" =? _vpc1Status
, "TagSet" `toQueryList` _vpc1Tags
, "VpcPeeringConnectionId" =? _vpc1VpcPeeringConnectionId
]
data S3Storage = S3Storage
{ _ssAWSAccessKeyId :: Maybe Text
, _ssBucket :: Maybe Text
, _ssPrefix :: Maybe Text
, _ssUploadPolicy :: Maybe Base64
, _ssUploadPolicySignature :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'S3Storage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ssAWSAccessKeyId' @::@ 'Maybe' 'Text'
--
-- * 'ssBucket' @::@ 'Maybe' 'Text'
--
-- * 'ssPrefix' @::@ 'Maybe' 'Text'
--
-- * 'ssUploadPolicy' @::@ 'Maybe' 'Base64'
--
-- * 'ssUploadPolicySignature' @::@ 'Maybe' 'Text'
--
s3Storage :: S3Storage
s3Storage = S3Storage
{ _ssBucket = Nothing
, _ssPrefix = Nothing
, _ssAWSAccessKeyId = Nothing
, _ssUploadPolicy = Nothing
, _ssUploadPolicySignature = Nothing
}
-- | The access key ID of the owner of the bucket. Before you specify a value for
-- your access key ID, review and follow the guidance in <http://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html Best Practices forManaging AWS Access Keys>.
ssAWSAccessKeyId :: Lens' S3Storage (Maybe Text)
ssAWSAccessKeyId = lens _ssAWSAccessKeyId (\s a -> s { _ssAWSAccessKeyId = a })
-- | The bucket in which to store the AMI. You can specify a bucket that you
-- already own or a new bucket that Amazon EC2 creates on your behalf. If you
-- specify a bucket that belongs to someone else, Amazon EC2 returns an error.
ssBucket :: Lens' S3Storage (Maybe Text)
ssBucket = lens _ssBucket (\s a -> s { _ssBucket = a })
-- | The beginning of the file name of the AMI.
ssPrefix :: Lens' S3Storage (Maybe Text)
ssPrefix = lens _ssPrefix (\s a -> s { _ssPrefix = a })
-- | A Base64-encoded Amazon S3 upload policy that gives Amazon EC2 permission to
-- upload items into Amazon S3 on your behalf.
ssUploadPolicy :: Lens' S3Storage (Maybe Base64)
ssUploadPolicy = lens _ssUploadPolicy (\s a -> s { _ssUploadPolicy = a })
-- | The signature of the Base64 encoded JSON document.
ssUploadPolicySignature :: Lens' S3Storage (Maybe Text)
ssUploadPolicySignature =
lens _ssUploadPolicySignature (\s a -> s { _ssUploadPolicySignature = a })
instance FromXML S3Storage where
parseXML x = S3Storage
<$> x .@? "AWSAccessKeyId"
<*> x .@? "bucket"
<*> x .@? "prefix"
<*> x .@? "uploadPolicy"
<*> x .@? "uploadPolicySignature"
instance ToQuery S3Storage where
toQuery S3Storage{..} = mconcat
[ "AWSAccessKeyId" =? _ssAWSAccessKeyId
, "Bucket" =? _ssBucket
, "Prefix" =? _ssPrefix
, "UploadPolicy" =? _ssUploadPolicy
, "UploadPolicySignature" =? _ssUploadPolicySignature
]
data VgwTelemetry = VgwTelemetry
{ _vtAcceptedRouteCount :: Maybe Int
, _vtLastStatusChange :: Maybe ISO8601
, _vtOutsideIpAddress :: Maybe Text
, _vtStatus :: Maybe TelemetryStatus
, _vtStatusMessage :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VgwTelemetry' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vtAcceptedRouteCount' @::@ 'Maybe' 'Int'
--
-- * 'vtLastStatusChange' @::@ 'Maybe' 'UTCTime'
--
-- * 'vtOutsideIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'vtStatus' @::@ 'Maybe' 'TelemetryStatus'
--
-- * 'vtStatusMessage' @::@ 'Maybe' 'Text'
--
vgwTelemetry :: VgwTelemetry
vgwTelemetry = VgwTelemetry
{ _vtOutsideIpAddress = Nothing
, _vtStatus = Nothing
, _vtLastStatusChange = Nothing
, _vtStatusMessage = Nothing
, _vtAcceptedRouteCount = Nothing
}
-- | The number of accepted routes.
vtAcceptedRouteCount :: Lens' VgwTelemetry (Maybe Int)
vtAcceptedRouteCount =
lens _vtAcceptedRouteCount (\s a -> s { _vtAcceptedRouteCount = a })
-- | The date and time of the last change in status.
vtLastStatusChange :: Lens' VgwTelemetry (Maybe UTCTime)
vtLastStatusChange =
lens _vtLastStatusChange (\s a -> s { _vtLastStatusChange = a })
. mapping _Time
-- | The Internet-routable IP address of the virtual private gateway's outside
-- interface.
vtOutsideIpAddress :: Lens' VgwTelemetry (Maybe Text)
vtOutsideIpAddress =
lens _vtOutsideIpAddress (\s a -> s { _vtOutsideIpAddress = a })
-- | The status of the VPN tunnel.
vtStatus :: Lens' VgwTelemetry (Maybe TelemetryStatus)
vtStatus = lens _vtStatus (\s a -> s { _vtStatus = a })
-- | If an error occurs, a description of the error.
vtStatusMessage :: Lens' VgwTelemetry (Maybe Text)
vtStatusMessage = lens _vtStatusMessage (\s a -> s { _vtStatusMessage = a })
instance FromXML VgwTelemetry where
parseXML x = VgwTelemetry
<$> x .@? "acceptedRouteCount"
<*> x .@? "lastStatusChange"
<*> x .@? "outsideIpAddress"
<*> x .@? "status"
<*> x .@? "statusMessage"
instance ToQuery VgwTelemetry where
toQuery VgwTelemetry{..} = mconcat
[ "AcceptedRouteCount" =? _vtAcceptedRouteCount
, "LastStatusChange" =? _vtLastStatusChange
, "OutsideIpAddress" =? _vtOutsideIpAddress
, "Status" =? _vtStatus
, "StatusMessage" =? _vtStatusMessage
]
data VpnStaticRoute = VpnStaticRoute
{ _vsrDestinationCidrBlock :: Maybe Text
, _vsrSource :: Maybe VpnStaticRouteSource
, _vsrState :: Maybe VpnState
} deriving (Eq, Read, Show)
-- | 'VpnStaticRoute' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vsrDestinationCidrBlock' @::@ 'Maybe' 'Text'
--
-- * 'vsrSource' @::@ 'Maybe' 'VpnStaticRouteSource'
--
-- * 'vsrState' @::@ 'Maybe' 'VpnState'
--
vpnStaticRoute :: VpnStaticRoute
vpnStaticRoute = VpnStaticRoute
{ _vsrDestinationCidrBlock = Nothing
, _vsrSource = Nothing
, _vsrState = Nothing
}
-- | The CIDR block associated with the local subnet of the customer data center.
vsrDestinationCidrBlock :: Lens' VpnStaticRoute (Maybe Text)
vsrDestinationCidrBlock =
lens _vsrDestinationCidrBlock (\s a -> s { _vsrDestinationCidrBlock = a })
-- | Indicates how the routes were provided.
vsrSource :: Lens' VpnStaticRoute (Maybe VpnStaticRouteSource)
vsrSource = lens _vsrSource (\s a -> s { _vsrSource = a })
-- | The current state of the static route.
vsrState :: Lens' VpnStaticRoute (Maybe VpnState)
vsrState = lens _vsrState (\s a -> s { _vsrState = a })
instance FromXML VpnStaticRoute where
parseXML x = VpnStaticRoute
<$> x .@? "destinationCidrBlock"
<*> x .@? "source"
<*> x .@? "state"
instance ToQuery VpnStaticRoute where
toQuery VpnStaticRoute{..} = mconcat
[ "DestinationCidrBlock" =? _vsrDestinationCidrBlock
, "Source" =? _vsrSource
, "State" =? _vsrState
]
data InstanceStateName
= ISNPending -- ^ pending
| ISNRunning -- ^ running
| ISNShuttingDown -- ^ shutting-down
| ISNStopped -- ^ stopped
| ISNStopping -- ^ stopping
| ISNTerminated -- ^ terminated
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable InstanceStateName
instance FromText InstanceStateName where
parser = takeLowerText >>= \case
"pending" -> pure ISNPending
"running" -> pure ISNRunning
"shutting-down" -> pure ISNShuttingDown
"stopped" -> pure ISNStopped
"stopping" -> pure ISNStopping
"terminated" -> pure ISNTerminated
e -> fail $
"Failure parsing InstanceStateName from " ++ show e
instance ToText InstanceStateName where
toText = \case
ISNPending -> "pending"
ISNRunning -> "running"
ISNShuttingDown -> "shutting-down"
ISNStopped -> "stopped"
ISNStopping -> "stopping"
ISNTerminated -> "terminated"
instance ToByteString InstanceStateName
instance ToHeader InstanceStateName
instance ToQuery InstanceStateName
instance FromXML InstanceStateName where
parseXML = parseXMLText "InstanceStateName"
data Instance = Instance
{ _i1AmiLaunchIndex :: Int
, _i1Architecture :: ArchitectureValues
, _i1BlockDeviceMappings :: List "item" InstanceBlockDeviceMapping
, _i1ClientToken :: Maybe Text
, _i1EbsOptimized :: Bool
, _i1Hypervisor :: HypervisorType
, _i1IamInstanceProfile :: Maybe IamInstanceProfile
, _i1ImageId :: Text
, _i1InstanceId :: Text
, _i1InstanceLifecycle :: Maybe InstanceLifecycleType
, _i1InstanceType :: InstanceType
, _i1KernelId :: Maybe Text
, _i1KeyName :: Maybe Text
, _i1LaunchTime :: ISO8601
, _i1Monitoring :: Monitoring
, _i1NetworkInterfaces :: List "item" InstanceNetworkInterface
, _i1Placement :: Placement
, _i1Platform :: Maybe PlatformValues
, _i1PrivateDnsName :: Maybe Text
, _i1PrivateIpAddress :: Maybe Text
, _i1ProductCodes :: List "item" ProductCode
, _i1PublicDnsName :: Maybe Text
, _i1PublicIpAddress :: Maybe Text
, _i1RamdiskId :: Maybe Text
, _i1RootDeviceName :: Maybe Text
, _i1RootDeviceType :: DeviceType
, _i1SecurityGroups :: List "item" GroupIdentifier
, _i1SourceDestCheck :: Maybe Bool
, _i1SpotInstanceRequestId :: Maybe Text
, _i1SriovNetSupport :: Maybe Text
, _i1State :: InstanceState
, _i1StateReason :: Maybe StateReason
, _i1StateTransitionReason :: Maybe Text
, _i1SubnetId :: Maybe Text
, _i1Tags :: List "item" Tag
, _i1VirtualizationType :: VirtualizationType
, _i1VpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'Instance' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'i1AmiLaunchIndex' @::@ 'Int'
--
-- * 'i1Architecture' @::@ 'ArchitectureValues'
--
-- * 'i1BlockDeviceMappings' @::@ ['InstanceBlockDeviceMapping']
--
-- * 'i1ClientToken' @::@ 'Maybe' 'Text'
--
-- * 'i1EbsOptimized' @::@ 'Bool'
--
-- * 'i1Hypervisor' @::@ 'HypervisorType'
--
-- * 'i1IamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfile'
--
-- * 'i1ImageId' @::@ 'Text'
--
-- * 'i1InstanceId' @::@ 'Text'
--
-- * 'i1InstanceLifecycle' @::@ 'Maybe' 'InstanceLifecycleType'
--
-- * 'i1InstanceType' @::@ 'InstanceType'
--
-- * 'i1KernelId' @::@ 'Maybe' 'Text'
--
-- * 'i1KeyName' @::@ 'Maybe' 'Text'
--
-- * 'i1LaunchTime' @::@ 'UTCTime'
--
-- * 'i1Monitoring' @::@ 'Monitoring'
--
-- * 'i1NetworkInterfaces' @::@ ['InstanceNetworkInterface']
--
-- * 'i1Placement' @::@ 'Placement'
--
-- * 'i1Platform' @::@ 'Maybe' 'PlatformValues'
--
-- * 'i1PrivateDnsName' @::@ 'Maybe' 'Text'
--
-- * 'i1PrivateIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'i1ProductCodes' @::@ ['ProductCode']
--
-- * 'i1PublicDnsName' @::@ 'Maybe' 'Text'
--
-- * 'i1PublicIpAddress' @::@ 'Maybe' 'Text'
--
-- * 'i1RamdiskId' @::@ 'Maybe' 'Text'
--
-- * 'i1RootDeviceName' @::@ 'Maybe' 'Text'
--
-- * 'i1RootDeviceType' @::@ 'DeviceType'
--
-- * 'i1SecurityGroups' @::@ ['GroupIdentifier']
--
-- * 'i1SourceDestCheck' @::@ 'Maybe' 'Bool'
--
-- * 'i1SpotInstanceRequestId' @::@ 'Maybe' 'Text'
--
-- * 'i1SriovNetSupport' @::@ 'Maybe' 'Text'
--
-- * 'i1State' @::@ 'InstanceState'
--
-- * 'i1StateReason' @::@ 'Maybe' 'StateReason'
--
-- * 'i1StateTransitionReason' @::@ 'Maybe' 'Text'
--
-- * 'i1SubnetId' @::@ 'Maybe' 'Text'
--
-- * 'i1Tags' @::@ ['Tag']
--
-- * 'i1VirtualizationType' @::@ 'VirtualizationType'
--
-- * 'i1VpcId' @::@ 'Maybe' 'Text'
--
instance' :: Text -- ^ 'i1InstanceId'
-> Text -- ^ 'i1ImageId'
-> InstanceState -- ^ 'i1State'
-> Int -- ^ 'i1AmiLaunchIndex'
-> InstanceType -- ^ 'i1InstanceType'
-> UTCTime -- ^ 'i1LaunchTime'
-> Placement -- ^ 'i1Placement'
-> Monitoring -- ^ 'i1Monitoring'
-> ArchitectureValues -- ^ 'i1Architecture'
-> DeviceType -- ^ 'i1RootDeviceType'
-> VirtualizationType -- ^ 'i1VirtualizationType'
-> HypervisorType -- ^ 'i1Hypervisor'
-> Bool -- ^ 'i1EbsOptimized'
-> Instance
instance' p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 = Instance
{ _i1InstanceId = p1
, _i1ImageId = p2
, _i1State = p3
, _i1AmiLaunchIndex = p4
, _i1InstanceType = p5
, _i1LaunchTime = withIso _Time (const id) p6
, _i1Placement = p7
, _i1Monitoring = p8
, _i1Architecture = p9
, _i1RootDeviceType = p10
, _i1VirtualizationType = p11
, _i1Hypervisor = p12
, _i1EbsOptimized = p13
, _i1PrivateDnsName = Nothing
, _i1PublicDnsName = Nothing
, _i1StateTransitionReason = Nothing
, _i1KeyName = Nothing
, _i1ProductCodes = mempty
, _i1KernelId = Nothing
, _i1RamdiskId = Nothing
, _i1Platform = Nothing
, _i1SubnetId = Nothing
, _i1VpcId = Nothing
, _i1PrivateIpAddress = Nothing
, _i1PublicIpAddress = Nothing
, _i1StateReason = Nothing
, _i1RootDeviceName = Nothing
, _i1BlockDeviceMappings = mempty
, _i1InstanceLifecycle = Nothing
, _i1SpotInstanceRequestId = Nothing
, _i1ClientToken = Nothing
, _i1Tags = mempty
, _i1SecurityGroups = mempty
, _i1SourceDestCheck = Nothing
, _i1NetworkInterfaces = mempty
, _i1IamInstanceProfile = Nothing
, _i1SriovNetSupport = Nothing
}
-- | The AMI launch index, which can be used to find this instance in the launch
-- group.
i1AmiLaunchIndex :: Lens' Instance Int
i1AmiLaunchIndex = lens _i1AmiLaunchIndex (\s a -> s { _i1AmiLaunchIndex = a })
-- | The architecture of the image.
i1Architecture :: Lens' Instance ArchitectureValues
i1Architecture = lens _i1Architecture (\s a -> s { _i1Architecture = a })
-- | Any block device mapping entries for the instance.
i1BlockDeviceMappings :: Lens' Instance [InstanceBlockDeviceMapping]
i1BlockDeviceMappings =
lens _i1BlockDeviceMappings (\s a -> s { _i1BlockDeviceMappings = a })
. _List
-- | The idempotency token you provided when you launched the instance.
i1ClientToken :: Lens' Instance (Maybe Text)
i1ClientToken = lens _i1ClientToken (\s a -> s { _i1ClientToken = a })
-- | Indicates whether the instance is optimized for EBS I/O. This optimization
-- provides dedicated throughput to Amazon EBS and an optimized configuration
-- stack to provide optimal I/O performance. This optimization isn't available
-- with all instance types. Additional usage charges apply when using an EBS
-- Optimized instance.
i1EbsOptimized :: Lens' Instance Bool
i1EbsOptimized = lens _i1EbsOptimized (\s a -> s { _i1EbsOptimized = a })
-- | The hypervisor type of the instance.
i1Hypervisor :: Lens' Instance HypervisorType
i1Hypervisor = lens _i1Hypervisor (\s a -> s { _i1Hypervisor = a })
-- | The IAM instance profile associated with the instance.
i1IamInstanceProfile :: Lens' Instance (Maybe IamInstanceProfile)
i1IamInstanceProfile =
lens _i1IamInstanceProfile (\s a -> s { _i1IamInstanceProfile = a })
-- | The ID of the AMI used to launch the instance.
i1ImageId :: Lens' Instance Text
i1ImageId = lens _i1ImageId (\s a -> s { _i1ImageId = a })
-- | The ID of the instance.
i1InstanceId :: Lens' Instance Text
i1InstanceId = lens _i1InstanceId (\s a -> s { _i1InstanceId = a })
-- | Indicates whether this is a Spot Instance.
i1InstanceLifecycle :: Lens' Instance (Maybe InstanceLifecycleType)
i1InstanceLifecycle =
lens _i1InstanceLifecycle (\s a -> s { _i1InstanceLifecycle = a })
-- | The instance type.
i1InstanceType :: Lens' Instance InstanceType
i1InstanceType = lens _i1InstanceType (\s a -> s { _i1InstanceType = a })
-- | The kernel associated with this instance.
i1KernelId :: Lens' Instance (Maybe Text)
i1KernelId = lens _i1KernelId (\s a -> s { _i1KernelId = a })
-- | The name of the key pair, if this instance was launched with an associated
-- key pair.
i1KeyName :: Lens' Instance (Maybe Text)
i1KeyName = lens _i1KeyName (\s a -> s { _i1KeyName = a })
-- | The time the instance was launched.
i1LaunchTime :: Lens' Instance UTCTime
i1LaunchTime = lens _i1LaunchTime (\s a -> s { _i1LaunchTime = a }) . _Time
-- | The monitoring information for the instance.
i1Monitoring :: Lens' Instance Monitoring
i1Monitoring = lens _i1Monitoring (\s a -> s { _i1Monitoring = a })
-- | [EC2-VPC] One or more network interfaces for the instance.
i1NetworkInterfaces :: Lens' Instance [InstanceNetworkInterface]
i1NetworkInterfaces =
lens _i1NetworkInterfaces (\s a -> s { _i1NetworkInterfaces = a })
. _List
-- | The location where the instance launched.
i1Placement :: Lens' Instance Placement
i1Placement = lens _i1Placement (\s a -> s { _i1Placement = a })
-- | The value is 'Windows' for Windows instances; otherwise blank.
i1Platform :: Lens' Instance (Maybe PlatformValues)
i1Platform = lens _i1Platform (\s a -> s { _i1Platform = a })
-- | The private DNS name assigned to the instance. This DNS name can only be used
-- inside the Amazon EC2 network. This name is not available until the instance
-- enters the 'running' state.
i1PrivateDnsName :: Lens' Instance (Maybe Text)
i1PrivateDnsName = lens _i1PrivateDnsName (\s a -> s { _i1PrivateDnsName = a })
-- | The private IP address assigned to the instance.
i1PrivateIpAddress :: Lens' Instance (Maybe Text)
i1PrivateIpAddress =
lens _i1PrivateIpAddress (\s a -> s { _i1PrivateIpAddress = a })
-- | The product codes attached to this instance.
i1ProductCodes :: Lens' Instance [ProductCode]
i1ProductCodes = lens _i1ProductCodes (\s a -> s { _i1ProductCodes = a }) . _List
-- | The public DNS name assigned to the instance. This name is not available
-- until the instance enters the 'running' state.
i1PublicDnsName :: Lens' Instance (Maybe Text)
i1PublicDnsName = lens _i1PublicDnsName (\s a -> s { _i1PublicDnsName = a })
-- | The public IP address assigned to the instance.
i1PublicIpAddress :: Lens' Instance (Maybe Text)
i1PublicIpAddress =
lens _i1PublicIpAddress (\s a -> s { _i1PublicIpAddress = a })
-- | The RAM disk associated with this instance.
i1RamdiskId :: Lens' Instance (Maybe Text)
i1RamdiskId = lens _i1RamdiskId (\s a -> s { _i1RamdiskId = a })
-- | The root device name (for example, '/dev/sda1' or '/dev/xvda').
i1RootDeviceName :: Lens' Instance (Maybe Text)
i1RootDeviceName = lens _i1RootDeviceName (\s a -> s { _i1RootDeviceName = a })
-- | The root device type used by the AMI. The AMI can use an Amazon EBS volume or
-- an instance store volume.
i1RootDeviceType :: Lens' Instance DeviceType
i1RootDeviceType = lens _i1RootDeviceType (\s a -> s { _i1RootDeviceType = a })
-- | One or more security groups for the instance.
i1SecurityGroups :: Lens' Instance [GroupIdentifier]
i1SecurityGroups = lens _i1SecurityGroups (\s a -> s { _i1SecurityGroups = a }) . _List
-- | Specifies whether to enable an instance launched in a VPC to perform NAT.
-- This controls whether source/destination checking is enabled on the instance.
-- A value of 'true' means checking is enabled, and 'false' means checking is
-- disabled. The value must be 'false' for the instance to perform NAT. For more
-- information, see <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html NAT Instances> in the /Amazon Virtual Private Cloud User Guide/.
i1SourceDestCheck :: Lens' Instance (Maybe Bool)
i1SourceDestCheck =
lens _i1SourceDestCheck (\s a -> s { _i1SourceDestCheck = a })
-- | The ID of the Spot Instance request.
i1SpotInstanceRequestId :: Lens' Instance (Maybe Text)
i1SpotInstanceRequestId =
lens _i1SpotInstanceRequestId (\s a -> s { _i1SpotInstanceRequestId = a })
-- | Specifies whether enhanced networking is enabled.
i1SriovNetSupport :: Lens' Instance (Maybe Text)
i1SriovNetSupport =
lens _i1SriovNetSupport (\s a -> s { _i1SriovNetSupport = a })
-- | The current state of the instance.
i1State :: Lens' Instance InstanceState
i1State = lens _i1State (\s a -> s { _i1State = a })
-- | The reason for the most recent state transition.
i1StateReason :: Lens' Instance (Maybe StateReason)
i1StateReason = lens _i1StateReason (\s a -> s { _i1StateReason = a })
-- | The reason for the most recent state transition. This might be an empty
-- string.
i1StateTransitionReason :: Lens' Instance (Maybe Text)
i1StateTransitionReason =
lens _i1StateTransitionReason (\s a -> s { _i1StateTransitionReason = a })
-- | The ID of the subnet in which the instance is running.
i1SubnetId :: Lens' Instance (Maybe Text)
i1SubnetId = lens _i1SubnetId (\s a -> s { _i1SubnetId = a })
-- | Any tags assigned to the instance.
i1Tags :: Lens' Instance [Tag]
i1Tags = lens _i1Tags (\s a -> s { _i1Tags = a }) . _List
-- | The virtualization type of the instance.
i1VirtualizationType :: Lens' Instance VirtualizationType
i1VirtualizationType =
lens _i1VirtualizationType (\s a -> s { _i1VirtualizationType = a })
-- | The ID of the VPC in which the instance is running.
i1VpcId :: Lens' Instance (Maybe Text)
i1VpcId = lens _i1VpcId (\s a -> s { _i1VpcId = a })
instance FromXML Instance where
parseXML x = Instance
<$> x .@ "amiLaunchIndex"
<*> x .@ "architecture"
<*> x .@? "blockDeviceMapping" .!@ mempty
<*> x .@? "clientToken"
<*> x .@ "ebsOptimized"
<*> x .@ "hypervisor"
<*> x .@? "iamInstanceProfile"
<*> x .@ "imageId"
<*> x .@ "instanceId"
<*> x .@? "instanceLifecycle"
<*> x .@ "instanceType"
<*> x .@? "kernelId"
<*> x .@? "keyName"
<*> x .@ "launchTime"
<*> x .@ "monitoring"
<*> x .@? "networkInterfaceSet" .!@ mempty
<*> x .@ "placement"
<*> x .@? "platform"
<*> x .@? "privateDnsName"
<*> x .@? "privateIpAddress"
<*> x .@? "productCodes" .!@ mempty
<*> x .@? "dnsName"
<*> x .@? "ipAddress"
<*> x .@? "ramdiskId"
<*> x .@? "rootDeviceName"
<*> x .@ "rootDeviceType"
<*> x .@? "groupSet" .!@ mempty
<*> x .@? "sourceDestCheck"
<*> x .@? "spotInstanceRequestId"
<*> x .@? "sriovNetSupport"
<*> x .@ "instanceState"
<*> x .@? "stateReason"
<*> x .@? "reason"
<*> x .@? "subnetId"
<*> x .@? "tagSet" .!@ mempty
<*> x .@ "virtualizationType"
<*> x .@? "vpcId"
instance ToQuery Instance where
toQuery Instance{..} = mconcat
[ "AmiLaunchIndex" =? _i1AmiLaunchIndex
, "Architecture" =? _i1Architecture
, "BlockDeviceMapping" `toQueryList` _i1BlockDeviceMappings
, "ClientToken" =? _i1ClientToken
, "EbsOptimized" =? _i1EbsOptimized
, "Hypervisor" =? _i1Hypervisor
, "IamInstanceProfile" =? _i1IamInstanceProfile
, "ImageId" =? _i1ImageId
, "InstanceId" =? _i1InstanceId
, "InstanceLifecycle" =? _i1InstanceLifecycle
, "InstanceType" =? _i1InstanceType
, "KernelId" =? _i1KernelId
, "KeyName" =? _i1KeyName
, "LaunchTime" =? _i1LaunchTime
, "Monitoring" =? _i1Monitoring
, "NetworkInterfaceSet" `toQueryList` _i1NetworkInterfaces
, "Placement" =? _i1Placement
, "Platform" =? _i1Platform
, "PrivateDnsName" =? _i1PrivateDnsName
, "PrivateIpAddress" =? _i1PrivateIpAddress
, "ProductCodes" `toQueryList` _i1ProductCodes
, "DnsName" =? _i1PublicDnsName
, "IpAddress" =? _i1PublicIpAddress
, "RamdiskId" =? _i1RamdiskId
, "RootDeviceName" =? _i1RootDeviceName
, "RootDeviceType" =? _i1RootDeviceType
, "GroupSet" `toQueryList` _i1SecurityGroups
, "SourceDestCheck" =? _i1SourceDestCheck
, "SpotInstanceRequestId" =? _i1SpotInstanceRequestId
, "SriovNetSupport" =? _i1SriovNetSupport
, "InstanceState" =? _i1State
, "StateReason" =? _i1StateReason
, "Reason" =? _i1StateTransitionReason
, "SubnetId" =? _i1SubnetId
, "TagSet" `toQueryList` _i1Tags
, "VirtualizationType" =? _i1VirtualizationType
, "VpcId" =? _i1VpcId
]
data ExportTask = ExportTask
{ _etDescription :: Text
, _etExportTaskId :: Text
, _etExportToS3Task :: ExportToS3Task
, _etInstanceExportDetails :: InstanceExportDetails
, _etState :: ExportTaskState
, _etStatusMessage :: Text
} deriving (Eq, Read, Show)
-- | 'ExportTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'etDescription' @::@ 'Text'
--
-- * 'etExportTaskId' @::@ 'Text'
--
-- * 'etExportToS3Task' @::@ 'ExportToS3Task'
--
-- * 'etInstanceExportDetails' @::@ 'InstanceExportDetails'
--
-- * 'etState' @::@ 'ExportTaskState'
--
-- * 'etStatusMessage' @::@ 'Text'
--
exportTask :: Text -- ^ 'etExportTaskId'
-> Text -- ^ 'etDescription'
-> ExportTaskState -- ^ 'etState'
-> Text -- ^ 'etStatusMessage'
-> InstanceExportDetails -- ^ 'etInstanceExportDetails'
-> ExportToS3Task -- ^ 'etExportToS3Task'
-> ExportTask
exportTask p1 p2 p3 p4 p5 p6 = ExportTask
{ _etExportTaskId = p1
, _etDescription = p2
, _etState = p3
, _etStatusMessage = p4
, _etInstanceExportDetails = p5
, _etExportToS3Task = p6
}
-- | A description of the resource being exported.
etDescription :: Lens' ExportTask Text
etDescription = lens _etDescription (\s a -> s { _etDescription = a })
-- | The ID of the export task.
etExportTaskId :: Lens' ExportTask Text
etExportTaskId = lens _etExportTaskId (\s a -> s { _etExportTaskId = a })
etExportToS3Task :: Lens' ExportTask ExportToS3Task
etExportToS3Task = lens _etExportToS3Task (\s a -> s { _etExportToS3Task = a })
-- | The instance being exported.
etInstanceExportDetails :: Lens' ExportTask InstanceExportDetails
etInstanceExportDetails =
lens _etInstanceExportDetails (\s a -> s { _etInstanceExportDetails = a })
-- | The state of the conversion task.
etState :: Lens' ExportTask ExportTaskState
etState = lens _etState (\s a -> s { _etState = a })
-- | The status message related to the export task.
etStatusMessage :: Lens' ExportTask Text
etStatusMessage = lens _etStatusMessage (\s a -> s { _etStatusMessage = a })
instance FromXML ExportTask where
parseXML x = ExportTask
<$> x .@ "description"
<*> x .@ "exportTaskId"
<*> x .@ "exportToS3"
<*> x .@ "instanceExport"
<*> x .@ "state"
<*> x .@ "statusMessage"
instance ToQuery ExportTask where
toQuery ExportTask{..} = mconcat
[ "Description" =? _etDescription
, "ExportTaskId" =? _etExportTaskId
, "ExportToS3" =? _etExportToS3Task
, "InstanceExport" =? _etInstanceExportDetails
, "State" =? _etState
, "StatusMessage" =? _etStatusMessage
]
data ResetImageAttributeName
= RIANLaunchPermission -- ^ launchPermission
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ResetImageAttributeName
instance FromText ResetImageAttributeName where
parser = takeLowerText >>= \case
"launchpermission" -> pure RIANLaunchPermission
e -> fail $
"Failure parsing ResetImageAttributeName from " ++ show e
instance ToText ResetImageAttributeName where
toText RIANLaunchPermission = "launchPermission"
instance ToByteString ResetImageAttributeName
instance ToHeader ResetImageAttributeName
instance ToQuery ResetImageAttributeName
instance FromXML ResetImageAttributeName where
parseXML = parseXMLText "ResetImageAttributeName"
data RequestSpotLaunchSpecification = RequestSpotLaunchSpecification
{ _rslsAddressingType :: Maybe Text
, _rslsBlockDeviceMappings :: List "item" BlockDeviceMapping
, _rslsEbsOptimized :: Maybe Bool
, _rslsIamInstanceProfile :: Maybe IamInstanceProfileSpecification
, _rslsImageId :: Maybe Text
, _rslsInstanceType :: Maybe InstanceType
, _rslsKernelId :: Maybe Text
, _rslsKeyName :: Maybe Text
, _rslsMonitoring :: Maybe RunInstancesMonitoringEnabled
, _rslsNetworkInterfaces :: List "item" InstanceNetworkInterfaceSpecification
, _rslsPlacement :: Maybe SpotPlacement
, _rslsRamdiskId :: Maybe Text
, _rslsSecurityGroupIds :: List "item" Text
, _rslsSecurityGroups :: List "item" Text
, _rslsSubnetId :: Maybe Text
, _rslsUserData :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'RequestSpotLaunchSpecification' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rslsAddressingType' @::@ 'Maybe' 'Text'
--
-- * 'rslsBlockDeviceMappings' @::@ ['BlockDeviceMapping']
--
-- * 'rslsEbsOptimized' @::@ 'Maybe' 'Bool'
--
-- * 'rslsIamInstanceProfile' @::@ 'Maybe' 'IamInstanceProfileSpecification'
--
-- * 'rslsImageId' @::@ 'Maybe' 'Text'
--
-- * 'rslsInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'rslsKernelId' @::@ 'Maybe' 'Text'
--
-- * 'rslsKeyName' @::@ 'Maybe' 'Text'
--
-- * 'rslsMonitoring' @::@ 'Maybe' 'RunInstancesMonitoringEnabled'
--
-- * 'rslsNetworkInterfaces' @::@ ['InstanceNetworkInterfaceSpecification']
--
-- * 'rslsPlacement' @::@ 'Maybe' 'SpotPlacement'
--
-- * 'rslsRamdiskId' @::@ 'Maybe' 'Text'
--
-- * 'rslsSecurityGroupIds' @::@ ['Text']
--
-- * 'rslsSecurityGroups' @::@ ['Text']
--
-- * 'rslsSubnetId' @::@ 'Maybe' 'Text'
--
-- * 'rslsUserData' @::@ 'Maybe' 'Text'
--
requestSpotLaunchSpecification :: RequestSpotLaunchSpecification
requestSpotLaunchSpecification = RequestSpotLaunchSpecification
{ _rslsImageId = Nothing
, _rslsKeyName = Nothing
, _rslsSecurityGroups = mempty
, _rslsUserData = Nothing
, _rslsAddressingType = Nothing
, _rslsInstanceType = Nothing
, _rslsPlacement = Nothing
, _rslsKernelId = Nothing
, _rslsRamdiskId = Nothing
, _rslsBlockDeviceMappings = mempty
, _rslsSubnetId = Nothing
, _rslsNetworkInterfaces = mempty
, _rslsIamInstanceProfile = Nothing
, _rslsEbsOptimized = Nothing
, _rslsMonitoring = Nothing
, _rslsSecurityGroupIds = mempty
}
-- | Deprecated.
rslsAddressingType :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsAddressingType =
lens _rslsAddressingType (\s a -> s { _rslsAddressingType = a })
-- | One or more block device mapping entries.
rslsBlockDeviceMappings :: Lens' RequestSpotLaunchSpecification [BlockDeviceMapping]
rslsBlockDeviceMappings =
lens _rslsBlockDeviceMappings (\s a -> s { _rslsBlockDeviceMappings = a })
. _List
-- | Indicates whether the instance is optimized for EBS I/O. This optimization
-- provides dedicated throughput to Amazon EBS and an optimized configuration
-- stack to provide optimal EBS I/O performance. This optimization isn't
-- available with all instance types. Additional usage charges apply when using
-- an EBS Optimized instance.
--
-- Default: 'false'
rslsEbsOptimized :: Lens' RequestSpotLaunchSpecification (Maybe Bool)
rslsEbsOptimized = lens _rslsEbsOptimized (\s a -> s { _rslsEbsOptimized = a })
-- | The IAM instance profile.
rslsIamInstanceProfile :: Lens' RequestSpotLaunchSpecification (Maybe IamInstanceProfileSpecification)
rslsIamInstanceProfile =
lens _rslsIamInstanceProfile (\s a -> s { _rslsIamInstanceProfile = a })
-- | The ID of the AMI.
rslsImageId :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsImageId = lens _rslsImageId (\s a -> s { _rslsImageId = a })
-- | The instance type.
rslsInstanceType :: Lens' RequestSpotLaunchSpecification (Maybe InstanceType)
rslsInstanceType = lens _rslsInstanceType (\s a -> s { _rslsInstanceType = a })
-- | The ID of the kernel.
rslsKernelId :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsKernelId = lens _rslsKernelId (\s a -> s { _rslsKernelId = a })
-- | The name of the key pair.
rslsKeyName :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsKeyName = lens _rslsKeyName (\s a -> s { _rslsKeyName = a })
rslsMonitoring :: Lens' RequestSpotLaunchSpecification (Maybe RunInstancesMonitoringEnabled)
rslsMonitoring = lens _rslsMonitoring (\s a -> s { _rslsMonitoring = a })
-- | One or more network interfaces.
rslsNetworkInterfaces :: Lens' RequestSpotLaunchSpecification [InstanceNetworkInterfaceSpecification]
rslsNetworkInterfaces =
lens _rslsNetworkInterfaces (\s a -> s { _rslsNetworkInterfaces = a })
. _List
-- | The placement information for the instance.
rslsPlacement :: Lens' RequestSpotLaunchSpecification (Maybe SpotPlacement)
rslsPlacement = lens _rslsPlacement (\s a -> s { _rslsPlacement = a })
-- | The ID of the RAM disk.
rslsRamdiskId :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsRamdiskId = lens _rslsRamdiskId (\s a -> s { _rslsRamdiskId = a })
rslsSecurityGroupIds :: Lens' RequestSpotLaunchSpecification [Text]
rslsSecurityGroupIds =
lens _rslsSecurityGroupIds (\s a -> s { _rslsSecurityGroupIds = a })
. _List
rslsSecurityGroups :: Lens' RequestSpotLaunchSpecification [Text]
rslsSecurityGroups =
lens _rslsSecurityGroups (\s a -> s { _rslsSecurityGroups = a })
. _List
-- | The ID of the subnet in which to launch the instance.
rslsSubnetId :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsSubnetId = lens _rslsSubnetId (\s a -> s { _rslsSubnetId = a })
-- | The Base64-encoded MIME user data to make available to the instances.
rslsUserData :: Lens' RequestSpotLaunchSpecification (Maybe Text)
rslsUserData = lens _rslsUserData (\s a -> s { _rslsUserData = a })
instance FromXML RequestSpotLaunchSpecification where
parseXML x = RequestSpotLaunchSpecification
<$> x .@? "addressingType"
<*> x .@? "blockDeviceMapping" .!@ mempty
<*> x .@? "ebsOptimized"
<*> x .@? "iamInstanceProfile"
<*> x .@? "imageId"
<*> x .@? "instanceType"
<*> x .@? "kernelId"
<*> x .@? "keyName"
<*> x .@? "monitoring"
<*> x .@? "NetworkInterface" .!@ mempty
<*> x .@? "placement"
<*> x .@? "ramdiskId"
<*> x .@? "SecurityGroupId" .!@ mempty
<*> x .@? "SecurityGroup" .!@ mempty
<*> x .@? "subnetId"
<*> x .@? "userData"
instance ToQuery RequestSpotLaunchSpecification where
toQuery RequestSpotLaunchSpecification{..} = mconcat
[ "AddressingType" =? _rslsAddressingType
, "BlockDeviceMapping" `toQueryList` _rslsBlockDeviceMappings
, "EbsOptimized" =? _rslsEbsOptimized
, "IamInstanceProfile" =? _rslsIamInstanceProfile
, "ImageId" =? _rslsImageId
, "InstanceType" =? _rslsInstanceType
, "KernelId" =? _rslsKernelId
, "KeyName" =? _rslsKeyName
, "Monitoring" =? _rslsMonitoring
, "NetworkInterface" `toQueryList` _rslsNetworkInterfaces
, "Placement" =? _rslsPlacement
, "RamdiskId" =? _rslsRamdiskId
, "SecurityGroupId" `toQueryList` _rslsSecurityGroupIds
, "SecurityGroup" `toQueryList` _rslsSecurityGroups
, "SubnetId" =? _rslsSubnetId
, "UserData" =? _rslsUserData
]
newtype VolumeDetail = VolumeDetail
{ _vdSize :: Integer
} deriving (Eq, Ord, Read, Show, Enum, Num, Integral, Real)
-- | 'VolumeDetail' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vdSize' @::@ 'Integer'
--
volumeDetail :: Integer -- ^ 'vdSize'
-> VolumeDetail
volumeDetail p1 = VolumeDetail
{ _vdSize = p1
}
-- | The size of the volume, in GiB.
vdSize :: Lens' VolumeDetail Integer
vdSize = lens _vdSize (\s a -> s { _vdSize = a })
instance FromXML VolumeDetail where
parseXML x = VolumeDetail
<$> x .@ "size"
instance ToQuery VolumeDetail where
toQuery VolumeDetail{..} = mconcat
[ "Size" =? _vdSize
]
data PricingDetail = PricingDetail
{ _pdCount :: Maybe Int
, _pdPrice :: Maybe Double
} deriving (Eq, Ord, Read, Show)
-- | 'PricingDetail' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pdCount' @::@ 'Maybe' 'Int'
--
-- * 'pdPrice' @::@ 'Maybe' 'Double'
--
pricingDetail :: PricingDetail
pricingDetail = PricingDetail
{ _pdPrice = Nothing
, _pdCount = Nothing
}
-- | The number of instances available for the price.
pdCount :: Lens' PricingDetail (Maybe Int)
pdCount = lens _pdCount (\s a -> s { _pdCount = a })
-- | The price per instance.
pdPrice :: Lens' PricingDetail (Maybe Double)
pdPrice = lens _pdPrice (\s a -> s { _pdPrice = a })
instance FromXML PricingDetail where
parseXML x = PricingDetail
<$> x .@? "count"
<*> x .@? "price"
instance ToQuery PricingDetail where
toQuery PricingDetail{..} = mconcat
[ "Count" =? _pdCount
, "Price" =? _pdPrice
]
data NetworkInterfacePrivateIpAddress = NetworkInterfacePrivateIpAddress
{ _nipiaAssociation :: Maybe NetworkInterfaceAssociation
, _nipiaPrimary :: Maybe Bool
, _nipiaPrivateDnsName :: Maybe Text
, _nipiaPrivateIpAddress :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'NetworkInterfacePrivateIpAddress' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'nipiaAssociation' @::@ 'Maybe' 'NetworkInterfaceAssociation'
--
-- * 'nipiaPrimary' @::@ 'Maybe' 'Bool'
--
-- * 'nipiaPrivateDnsName' @::@ 'Maybe' 'Text'
--
-- * 'nipiaPrivateIpAddress' @::@ 'Maybe' 'Text'
--
networkInterfacePrivateIpAddress :: NetworkInterfacePrivateIpAddress
networkInterfacePrivateIpAddress = NetworkInterfacePrivateIpAddress
{ _nipiaPrivateIpAddress = Nothing
, _nipiaPrivateDnsName = Nothing
, _nipiaPrimary = Nothing
, _nipiaAssociation = Nothing
}
-- | The association information for an Elastic IP address associated with the
-- network interface.
nipiaAssociation :: Lens' NetworkInterfacePrivateIpAddress (Maybe NetworkInterfaceAssociation)
nipiaAssociation = lens _nipiaAssociation (\s a -> s { _nipiaAssociation = a })
-- | Indicates whether this IP address is the primary private IP address of the
-- network interface.
nipiaPrimary :: Lens' NetworkInterfacePrivateIpAddress (Maybe Bool)
nipiaPrimary = lens _nipiaPrimary (\s a -> s { _nipiaPrimary = a })
-- | The private DNS name.
nipiaPrivateDnsName :: Lens' NetworkInterfacePrivateIpAddress (Maybe Text)
nipiaPrivateDnsName =
lens _nipiaPrivateDnsName (\s a -> s { _nipiaPrivateDnsName = a })
-- | The private IP address.
nipiaPrivateIpAddress :: Lens' NetworkInterfacePrivateIpAddress (Maybe Text)
nipiaPrivateIpAddress =
lens _nipiaPrivateIpAddress (\s a -> s { _nipiaPrivateIpAddress = a })
instance FromXML NetworkInterfacePrivateIpAddress where
parseXML x = NetworkInterfacePrivateIpAddress
<$> x .@? "association"
<*> x .@? "primary"
<*> x .@? "privateDnsName"
<*> x .@? "privateIpAddress"
instance ToQuery NetworkInterfacePrivateIpAddress where
toQuery NetworkInterfacePrivateIpAddress{..} = mconcat
[ "Association" =? _nipiaAssociation
, "Primary" =? _nipiaPrimary
, "PrivateDnsName" =? _nipiaPrivateDnsName
, "PrivateIpAddress" =? _nipiaPrivateIpAddress
]
data DiskImageFormat
= Raw -- ^ RAW
| Vhd -- ^ VHD
| Vmdk -- ^ VMDK
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable DiskImageFormat
instance FromText DiskImageFormat where
parser = takeLowerText >>= \case
"raw" -> pure Raw
"vhd" -> pure Vhd
"vmdk" -> pure Vmdk
e -> fail $
"Failure parsing DiskImageFormat from " ++ show e
instance ToText DiskImageFormat where
toText = \case
Raw -> "RAW"
Vhd -> "VHD"
Vmdk -> "VMDK"
instance ToByteString DiskImageFormat
instance ToHeader DiskImageFormat
instance ToQuery DiskImageFormat
instance FromXML DiskImageFormat where
parseXML = parseXMLText "DiskImageFormat"
data BundleTaskError = BundleTaskError
{ _bteCode :: Maybe Text
, _bteMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'BundleTaskError' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'bteCode' @::@ 'Maybe' 'Text'
--
-- * 'bteMessage' @::@ 'Maybe' 'Text'
--
bundleTaskError :: BundleTaskError
bundleTaskError = BundleTaskError
{ _bteCode = Nothing
, _bteMessage = Nothing
}
-- | The error code.
bteCode :: Lens' BundleTaskError (Maybe Text)
bteCode = lens _bteCode (\s a -> s { _bteCode = a })
-- | The error message.
bteMessage :: Lens' BundleTaskError (Maybe Text)
bteMessage = lens _bteMessage (\s a -> s { _bteMessage = a })
instance FromXML BundleTaskError where
parseXML x = BundleTaskError
<$> x .@? "code"
<*> x .@? "message"
instance ToQuery BundleTaskError where
toQuery BundleTaskError{..} = mconcat
[ "Code" =? _bteCode
, "Message" =? _bteMessage
]
data VpcClassicLink = VpcClassicLink
{ _vclClassicLinkEnabled :: Maybe Bool
, _vclTags :: List "item" Tag
, _vclVpcId :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'VpcClassicLink' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vclClassicLinkEnabled' @::@ 'Maybe' 'Bool'
--
-- * 'vclTags' @::@ ['Tag']
--
-- * 'vclVpcId' @::@ 'Maybe' 'Text'
--
vpcClassicLink :: VpcClassicLink
vpcClassicLink = VpcClassicLink
{ _vclVpcId = Nothing
, _vclClassicLinkEnabled = Nothing
, _vclTags = mempty
}
-- | Indicates whether the VPC is enabled for ClassicLink.
vclClassicLinkEnabled :: Lens' VpcClassicLink (Maybe Bool)
vclClassicLinkEnabled =
lens _vclClassicLinkEnabled (\s a -> s { _vclClassicLinkEnabled = a })
-- | Any tags assigned to the VPC.
vclTags :: Lens' VpcClassicLink [Tag]
vclTags = lens _vclTags (\s a -> s { _vclTags = a }) . _List
-- | The ID of the VPC.
vclVpcId :: Lens' VpcClassicLink (Maybe Text)
vclVpcId = lens _vclVpcId (\s a -> s { _vclVpcId = a })
instance FromXML VpcClassicLink where
parseXML x = VpcClassicLink
<$> x .@? "classicLinkEnabled"
<*> x .@? "tagSet" .!@ mempty
<*> x .@? "vpcId"
instance ToQuery VpcClassicLink where
toQuery VpcClassicLink{..} = mconcat
[ "ClassicLinkEnabled" =? _vclClassicLinkEnabled
, "TagSet" `toQueryList` _vclTags
, "VpcId" =? _vclVpcId
]
data VolumeStatusItem = VolumeStatusItem
{ _vsiActions :: List "item" VolumeStatusAction
, _vsiAvailabilityZone :: Maybe Text
, _vsiEvents :: List "item" VolumeStatusEvent
, _vsiVolumeId :: Maybe Text
, _vsiVolumeStatus :: Maybe VolumeStatusInfo
} deriving (Eq, Read, Show)
-- | 'VolumeStatusItem' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'vsiActions' @::@ ['VolumeStatusAction']
--
-- * 'vsiAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'vsiEvents' @::@ ['VolumeStatusEvent']
--
-- * 'vsiVolumeId' @::@ 'Maybe' 'Text'
--
-- * 'vsiVolumeStatus' @::@ 'Maybe' 'VolumeStatusInfo'
--
volumeStatusItem :: VolumeStatusItem
volumeStatusItem = VolumeStatusItem
{ _vsiVolumeId = Nothing
, _vsiAvailabilityZone = Nothing
, _vsiVolumeStatus = Nothing
, _vsiEvents = mempty
, _vsiActions = mempty
}
-- | The details of the operation.
vsiActions :: Lens' VolumeStatusItem [VolumeStatusAction]
vsiActions = lens _vsiActions (\s a -> s { _vsiActions = a }) . _List
-- | The Availability Zone of the volume.
vsiAvailabilityZone :: Lens' VolumeStatusItem (Maybe Text)
vsiAvailabilityZone =
lens _vsiAvailabilityZone (\s a -> s { _vsiAvailabilityZone = a })
-- | A list of events associated with the volume.
vsiEvents :: Lens' VolumeStatusItem [VolumeStatusEvent]
vsiEvents = lens _vsiEvents (\s a -> s { _vsiEvents = a }) . _List
-- | The volume ID.
vsiVolumeId :: Lens' VolumeStatusItem (Maybe Text)
vsiVolumeId = lens _vsiVolumeId (\s a -> s { _vsiVolumeId = a })
-- | The volume status.
vsiVolumeStatus :: Lens' VolumeStatusItem (Maybe VolumeStatusInfo)
vsiVolumeStatus = lens _vsiVolumeStatus (\s a -> s { _vsiVolumeStatus = a })
instance FromXML VolumeStatusItem where
parseXML x = VolumeStatusItem
<$> x .@? "actionsSet" .!@ mempty
<*> x .@? "availabilityZone"
<*> x .@? "eventsSet" .!@ mempty
<*> x .@? "volumeId"
<*> x .@? "volumeStatus"
instance ToQuery VolumeStatusItem where
toQuery VolumeStatusItem{..} = mconcat
[ "ActionsSet" `toQueryList` _vsiActions
, "AvailabilityZone" =? _vsiAvailabilityZone
, "EventsSet" `toQueryList` _vsiEvents
, "VolumeId" =? _vsiVolumeId
, "VolumeStatus" =? _vsiVolumeStatus
]
|
kim/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/Types.hs
|
Haskell
|
mpl-2.0
| 431,589
|
use std::fmt;
/// How the [`Example`](../block/struct.Example.html) will be printed by the [`Logger`](../logger/index.html).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ExampleLabel {
It,
Example,
Then,
}
impl fmt::Display for ExampleLabel {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ExampleLabel::It => write!(f, "It"),
&ExampleLabel::Example => write!(f, "Example"),
&ExampleLabel::Then => write!(f, "Then"),
}
}
}
/// A [`Header`](trait.Header.html) with label and name of an [`Example`](../block/struct.Example.html).
#[derive(Clone, PartialEq, Eq, Debug, new)]
pub struct ExampleHeader {
pub label: ExampleLabel,
pub name: &'static str,
}
#[cfg(test)]
impl Default for ExampleHeader {
/// Used for testing
fn default() -> Self {
ExampleHeader::new(ExampleLabel::It, "example")
}
}
impl fmt::Display for ExampleHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {:?}", self.label, self.name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn label_fmt() {
fn subject(label: ExampleLabel) -> String {
format!("{}", label)
};
assert_eq!(subject(ExampleLabel::Example), "Example".to_owned());
assert_eq!(subject(ExampleLabel::It), "It".to_owned());
assert_eq!(subject(ExampleLabel::Then), "Then".to_owned());
}
#[test]
fn header_fmt() {
fn subject(label: ExampleLabel) -> String {
format!("{}", ExampleHeader::new(label, "Test"))
};
assert_eq!(
subject(ExampleLabel::Example),
"Example \"Test\"".to_owned()
);
assert_eq!(subject(ExampleLabel::It), "It \"Test\"".to_owned());
assert_eq!(subject(ExampleLabel::Then), "Then \"Test\"".to_owned());
}
}
|
mackwic/rspec
|
src/header/example.rs
|
Rust
|
mpl-2.0
| 1,905
|
require 'test_helper'
class ApplicationSettingTest < ActiveSupport::TestCase
teardown do
ApplicationSetting.update_settings ApplicationSetting.defaults
ApplicationSetting.apply!
end
describe "class methods" do
describe "::update_settings" do
it "should update only known params" do
ApplicationSetting.update_settings({'foo' => "asdf"})
assert_nil ApplicationSetting['foo']
end
it "should transform devise.expire_password_after to days when > 0" do
ApplicationSetting.update_settings({'devise.expire_password_after' => 3})
assert_equal 3.days, ApplicationSetting['devise.expire_password_after']
end
it "should set devise.expire_password_after to false when 0 is specified" do
ApplicationSetting.update_settings({'devise.expire_password_after' => 0})
assert_equal false, ApplicationSetting['devise.expire_password_after']
end
it "should transform devise.timeout_in to minutes when > 0" do
ApplicationSetting.update_settings({'devise.timeout_in' => 3})
assert_equal 3.minutes, ApplicationSetting['devise.timeout_in']
end
it "should set devise.timeout_in to nil when 0 is specified" do
ApplicationSetting.update_settings({'devise.timeout_in' => 0})
assert_nil ApplicationSetting['devise.timeout_in']
end
it "should not change unspecified settings" do
ApplicationSetting['devise.timeout_in'] = 3
ApplicationSetting.update_settings({'devise.expire_password_after' => 3})
assert_equal 3, ApplicationSetting['devise.timeout_in']
end
end
describe "::apply!" do
it "should apply all currently saved settings to the application" do
Devise.maximum_attempts = 99
Devise.password_archiving_count = 99
Devise.expire_password_after = 99
Devise.timeout_in = 99
ApplicationSetting['devise.maximum_attempts'] = 1
ApplicationSetting['devise.password_archiving_count'] = 2
ApplicationSetting['devise.expire_password_after'] = 3
ApplicationSetting['devise.timeout_in'] = 4
ApplicationSetting.apply!
assert_equal 1, Devise.maximum_attempts
assert_equal 2, Devise.password_archiving_count
assert_equal 3, Devise.expire_password_after
assert_equal 4, Devise.timeout_in
end
end
end
end
|
rideconnection/clearinghouse
|
test/unit/application_setting_test.rb
|
Ruby
|
agpl-3.0
| 2,462
|
# -*- coding: utf-8 -*-
# (c) 2015 Incaser Informatica S.L. - Sergio Teruel
# (c) 2015 Incaser Informatica S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
from openerp.tools.float_utils import float_round
import decimal
tipo_articulo = {'product': 'M', 'consu': 'M', 'service': 'I'}
codigo_empresa = 1
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
sagelc_export = fields.Boolean(string='Exported', default=False)
sagelc_code = fields.Char(string='SageLC Code', size=15)
def sanitize_arg(self, val):
if isinstance(val, decimal.Decimal):
return eval(str(val)) / 10000000000.0
else:
return val
@api.multi
def export_records(self):
if self[0].type == 'out_invoice':
self.export_records_customer()
else:
self.export_records_supplier()
@api.multi
def export_records_customer(self):
db_obj = self.env['base.external.dbsource']
db_sage = db_obj.search([('name', '=', 'Logic')])
for invoice in self:
dic_equiv = {}
sql = 'SELECT * FROM CabeceraAlbaranCliente WHERE 1=?'
cab_cols = db_sage.execute(sql, (2), True)['cols']
sql = 'SELECT * FROM LineasAlbaranCliente WHERE 1=?'
lin_cols = db_sage.execute(sql, (2), True)['cols']
sql = 'SELECT * FROM Clientes WHERE CodigoEmpresa=? AND CodigoCliente=?'
clientes = db_sage.execute(sql, (codigo_empresa, invoice.partner_id.sagelc_customer_ref))
cli = clientes[0]
for pos in range(len(cli)):
col = cli.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(cli[pos])
sql = 'SELECT * FROM ClientesConta WHERE CodigoEmpresa=? AND CodigoCuenta=?'
clientes_conta = db_sage.execute(sql, (codigo_empresa, cli.CodigoContable))
cli_conta = clientes_conta[0]
for pos in range(len(cli_conta)):
col = cli_conta.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(cli_conta[pos])
sql = 'SELECT * FROM ClientesProveedores WHERE SiglaNacion=? AND CifDni=?'
clientes_prov = db_sage.execute(sql, (cli.SiglaNacion, cli.CifDni))
cli_prov = clientes_prov[0]
for pos in range(len(cli_prov)):
col = cli_prov.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(cli_prov[pos])
dic_man = {
'[CodigoEmpresa]': codigo_empresa,
'[EjercicioAlbaran]': invoice.date_invoice[:4],
'[SerieAlbaran]': 'OD',
'[NumeroAlbaran]': invoice.id,
'[IdDelegacion]': 'CAS',
'[CodigoCliente]': invoice.partner_id.sagelc_customer_ref,
'[FechaAlbaran]': invoice.date_invoice,
'[NumeroLineas]': len(invoice.invoice_line),
}
dic_equiv.update(dic_man)
print(dic_equiv)
key_list = dic_equiv.keys()
params = '?,' * len(dic_equiv)
params = params[:-1]
sql = 'INSERT INTO CabeceraAlbaranCliente (%s) VALUES (%s)' % (
', '.join(key_list), params)
param_list = tuple([dic_equiv[key] for key in key_list])
db_sage.execute_void(sql, param_list)
vals = {'sagelc_export': True}
invoice.write(vals)
for line in invoice.invoice_line:
dic_equiv = {
'[CodigoEmpresa]': codigo_empresa,
'[EjercicioAlbaran]': invoice.date_invoice[:4],
'[SerieAlbaran]': 'OD',
'[NumeroAlbaran]': invoice.id,
'[Orden]': line.sequence,
'[FechaAlbaran]': invoice.date_invoice,
'[CodigoArticulo]': line.product_id.sagelc_code,
'[CodigoAlmacen]': '1',
'[DescripcionArticulo]':
line.product_id.name and
line.product_id.name[:40] or '',
'[DescripcionLinea]':
line.name and line.name.replace('\n', '\r\n') or '',
'[FactorConversion_]': 1,
'[AcumulaEstadistica_]': -1,
'[CodigoTransaccion]': 1,
'[GrupoIva]': 1,
'[CodigoIva]': 21,
'[UnidadesServidas]': line.quantity,
'[Unidades]': line.quantity,
'[Unidades2_]': line.quantity,
'[Precio]': line.price_unit,
'[PrecioRebaje]': line.price_unit,
'[PrecioCoste]': line.product_id.standard_price,
'[%Descuento]': line.discount,
'[%Iva]': 21,
'[TipoArticulo]': tipo_articulo[line.product_id.type],
}
print(dic_equiv)
key_list = dic_equiv.keys()
params = '?,' * len(dic_equiv)
params = params[:-1]
sql = 'INSERT INTO LineasAlbaranCliente (%s) VALUES (%s)' % (
', '.join(key_list), params)
param_list = tuple([dic_equiv[key] for key in key_list])
db_sage.execute_void(sql, param_list)
@api.multi
def export_records_supplier(self):
db_obj = self.env['base.external.dbsource']
db_sage = db_obj.search([('name', '=', 'Logic')])
codigo_empresa = 1
for invoice in self:
dic_equiv = {}
sql = 'SELECT * FROM CabeceraAlbaranProveedor WHERE 1=?'
cab_cols = db_sage.execute(sql, (2), True)['cols']
sql = 'SELECT * FROM LineasAlbaranProveedor WHERE 1=?'
lin_cols = db_sage.execute(sql, (2), True)['cols']
sql = 'SELECT * FROM Proveedores WHERE CodigoEmpresa=? AND CodigoProveedor=?'
proveedores = db_sage.execute(sql, (codigo_empresa, invoice.partner_id.sagelc_supplier_ref))
prov = proveedores[0]
for pos in range(len(prov)):
col = prov.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(prov[pos])
sql = 'SELECT * FROM ClientesConta WHERE CodigoEmpresa=? AND CodigoCuenta=?'
clientes_conta = db_sage.execute(sql, (codigo_empresa, prov.CodigoContable))
cli_conta = clientes_conta[0]
for pos in range(len(cli_conta)):
col = cli_conta.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(cli_conta[pos])
sql = 'SELECT * FROM ClientesProveedores WHERE SiglaNacion=? AND CifDni=?'
clientes_prov = db_sage.execute(sql, (prov.SiglaNacion, prov.CifDni))
cli_prov = clientes_prov[0]
for pos in range(len(cli_prov)):
col = cli_prov.cursor_description[pos][0]
if col in cab_cols:
dic_equiv['[%s]' % col] = self.sanitize_arg(cli_prov[pos])
dic_man = {
'[CodigoEmpresa]': codigo_empresa,
'[EjercicioAlbaran]': invoice.date_invoice[:4],
'[SerieAlbaran]': 'OD',
'[NumeroAlbaran]': invoice.id,
'[IdDelegacion]': 'CAS',
'[CodigoProveedor]': invoice.partner_id.sagelc_supplier_ref,
'[FechaAlbaran]': invoice.date_invoice,
'[NumeroLineas]': len(invoice.invoice_line),
}
dic_equiv.update(dic_man)
print(dic_equiv)
key_list = dic_equiv.keys()
params = '?,' * len(dic_equiv)
params = params[:-1]
sql = 'INSERT INTO CabeceraAlbaranProveedor (%s) VALUES (%s)' % (', '.join(key_list), params)
param_list = tuple([dic_equiv[key] for key in key_list])
db_sage.execute_void(sql, param_list)
vals = {'sagelc_export': True}
invoice.write(vals)
for line in invoice.invoice_line:
dic_equiv = {
'[CodigoEmpresa]': codigo_empresa,
'[EjercicioAlbaran]': invoice.date_invoice[:4],
'[SerieAlbaran]': 'OD',
'[NumeroAlbaran]': invoice.id,
'[Orden]': line.sequence,
'[FechaAlbaran]': invoice.date_invoice,
'[CodigoArticulo]': line.product_id.sagelc_code,
'[CodigoAlmacen]': '1',
'[DescripcionArticulo]': line.product_id.name,
'[DescripcionLinea]': line.name and line.name.replace('\n', '\r\n') or '',
'[FactorConversion_]': 1,
'[AcumulaEstadistica_]': -1,
'[CodigoTransaccion]': 1,
'[GrupoIva]': 1,
'[CodigoIva]': 21,
'[UnidadesRecibidas]': line.quantity,
'[Unidades]': line.quantity,
'[Unidades2_]': line.quantity,
'[Precio]': line.price_unit,
'[PrecioRebaje]': line.price_unit,
'[%Descuento]': line.discount,
'[%Iva]': 21,
'[TipoArticulo]': tipo_articulo[line.product_id.type],
}
print(dic_equiv)
key_list = dic_equiv.keys()
params = '?,' * len(dic_equiv)
params = params[:-1]
sql = 'INSERT INTO LineasAlbaranProveedor (%s) VALUES (%s)' % (', '.join(key_list), params)
param_list = tuple([dic_equiv[key] for key in key_list])
db_sage.execute_void(sql, param_list)
|
incaser/incaser-odoo-addons
|
export_sagelc/models/account_invoice.py
|
Python
|
agpl-3.0
| 10,115
|
/**
*/
package com.euclideanspace.casl.editor;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Var Decl</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.euclideanspace.casl.editor.VarDecl#getVar <em>Var</em>}</li>
* <li>{@link com.euclideanspace.casl.editor.VarDecl#getVar2 <em>Var2</em>}</li>
* <li>{@link com.euclideanspace.casl.editor.VarDecl#getSort <em>Sort</em>}</li>
* </ul>
* </p>
*
* @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl()
* @model
* @generated
*/
public interface VarDecl extends EObject
{
/**
* Returns the value of the '<em><b>Var</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Var</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Var</em>' containment reference.
* @see #setVar(Var)
* @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Var()
* @model containment="true"
* @generated
*/
Var getVar();
/**
* Sets the value of the '{@link com.euclideanspace.casl.editor.VarDecl#getVar <em>Var</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Var</em>' containment reference.
* @see #getVar()
* @generated
*/
void setVar(Var value);
/**
* Returns the value of the '<em><b>Var2</b></em>' containment reference list.
* The list contents are of type {@link com.euclideanspace.casl.editor.Var}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Var2</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Var2</em>' containment reference list.
* @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Var2()
* @model containment="true"
* @generated
*/
EList<Var> getVar2();
/**
* Returns the value of the '<em><b>Sort</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Sort</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Sort</em>' containment reference.
* @see #setSort(Sort)
* @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Sort()
* @model containment="true"
* @generated
*/
Sort getSort();
/**
* Sets the value of the '{@link com.euclideanspace.casl.editor.VarDecl#getSort <em>Sort</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Sort</em>' containment reference.
* @see #getSort()
* @generated
*/
void setSort(Sort value);
} // VarDecl
|
martinbaker/caslEdit
|
com.euclideanspace.casl/src-gen/com/euclideanspace/casl/editor/VarDecl.java
|
Java
|
agpl-3.0
| 3,054
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2018 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.compiler;
import java.io.IOException;
import java.io.Reader;
import org.voltdb.utils.InMemoryJarfile;
/**
* Abstract base for readers used during catalog compile or upgrade.
*/
public abstract class VoltCompilerReader extends Reader
{
public abstract String getName();
public abstract String getPath();
public abstract void putInJar(InMemoryJarfile jarFile, String name) throws IOException;
}
|
simonzhangsm/voltdb
|
src/frontend/org/voltdb/compiler/VoltCompilerReader.java
|
Java
|
agpl-3.0
| 1,169
|
---
typ: úplné znění předpisu
stav: historický
název: pravidla hospodaření
zkratka: PraH
původce: republikový výbor
předpis: prah/2014-08-02
platnost: 2014-08-02
účinnost: 2014-08-07
zmocnění: čl. 9 odst. 5 písm. c) stanov
kategorie: hospodaření
síla: vnitřní předpis vydaný republikovým výborem
formát: markdown
---
## Pravidla hospodaření
### Obecná ustanovení
#### § 1 Účel předpisu
Pravidla hospodaření stanoví způsob, kterým orgány strany průhledně, hospodárně a odpovědně používají majetek strany k politické činnosti a činnosti s ní související.
#### § 2 Dobrovolnictví
(1) Organizační složky zajišťují plnění svých úkolů přednostně dobrovolníky. Není-li s členem nebo příznivcem ujednána úplata s písemným potvrzením objednávky, jde o plnění dobrovolnické a bezúplatné.
(2) Pokud to orgán strany uzná za potřebné, může rozhodnout o tom, že svým členům nebo dobrovolníkům uhradí cestovné nebo nabídne drobné občerstvení, pokud jde o řádně svolané zasedání nebo jinou akci orgánu strany. Podmínkou je, že se člen nebo dobrovolník akce v potřebném rozsahu zúčastnil.
#### § 3 Placené úkoly
(1) Nelze-li důležitý úkol v požadované kvalitě zajistit pomocí dobrovolníků, organizační složka na něj vypíše odměnu nebo ho jinak zajistí aspoň částečně dobrovolnicky, případně za jiných výhodnějších podmínek, anebo za obvyklou cenu.
(2) Odměnu úkoly za řádně plněné při výkonu funkce v orgánu strany lze ujednat jen předem, a to v písemné smlouvě o výkonu funkce. Při uzavření smlouvy o výkonu funkce jedná za stranu nadřízený orgán orgánu strany, ve kterém je odměňovaný.
#### § 4 Hospodář
(1) **Hospodář** je člověk, který stojí v čele organizační složky, zástupce nebo jiný člen, kterého organizační složka určila hospodářem.
(2) Hospodář v mezích působnosti organizační složky, případně též v mezích jí zvlášť určených,
a) vykonává jejím jménem oprávnění při správě věcí (§ 9),
b) činí objednávky, uzavírá smlouvy a jinak právně jedná ve věci schválených záměrů (§ 11),
c) podává žádosti o proplacení z bankovního účtu (§ 14).
(3) Hospodář a ten, kdo se podílí na rozhodování o hospodaření strany, má postupovat hospodárně, s nezbytnou loajalitou, v souladu s vnitřními předpisy i s potřebnými znalostmi a pečlivostí. Pečlivě a s potřebnými znalostmi jedná ten, kdo při rozhodování mohl v dobré víře rozumně předpokládat, že jedná informovaně a v obhajitelném zájmu strany.
#### § 5 Zakázaná právní jednání
Zakazuje se
a) hospodařit s majetkem strany v rozporu s politikou strany,
b) objednávat občerstvení na večírek a jiné nepřiměřené občerstvení, nemravné služby, alkohol a jiné psychotropní látky, ledaže se cena zaplatí z prostředků na to darovaných dárcem nebo určených celostátním fórem,
c) slibovat třetí osobě za její protiplnění politický prospěch, kterým není naplňována politika strany,
d) zastupovat stranu ve vlastní věci nebo jiném případě střetu zájmu strany s osobním zájmem, aniž by byl jednající v dané věci nahrazen,
e) vynakládat prostředky na zjevně zbytečně nákladné alternativy (např. na taxislužbu nebo leteckou přepravu, pokud pro ně není důvod),
f) zavazovat stranu k dlouhodobému opakovanému plnění bez možnosti výpovědi nebo takovému plnění, pro které nelze v rozpočtu nebo rozpočtovém výhledu očekávat prostředky,
g) zřídit k věci v majetku strany zástavní nebo předkupní právo,
h) zatížit věc v majetku strany věcným břemenem v rozsahu větším, než je nezbytně nutné pro rozumné uspořádání vztahů.
#### § 6 Výběrová řízení
Na zakázku s celkovými náklady nad 50 000 Kč musí orgán strany vypsat veřejné výběrové řízení ve dvou fázích:
1. V **zadávací fázi** zveřejní hospodář orgánu strany zadání, které obsahuje požadavky na nabídky a způsob výběru vítěze takovým způsobem, aby kritériím hodnocení mohli uchazeči přizpůsobit své nabídky. Zpravidla také aspoň tři dodavatele osloví nebo zjistí jejich nabídky. Proti zadání lze podat podnět k nápravě nadřízenému orgánu, ledaže výběrové řízení probíhá za standardních podmínek, které nadřízený orgán schválil.
2. V **hodnotící fázi** vybere hodnotitel vítěze z nabídek, které obdrží. Nestačí-li hodnocení podle nabídkové ceny, hodnotící komise musí být sestavena nejméně ze tří odborníků způsobem schváleným v zadávací fázi. Rozhodnutí o hodnocení lze přezkoumat na základě stížnosti,[^rr] která nemá odkladný účinek.
[^rr]: § 2 rozhodčího řádu.
#### § 7 Nabytí věci
Strana smí nabýt věc, pokud
a) zcizitel věci potřebným způsobem uvedl svou totožnost,[^identifikace]
b) bezúplatné plnění není zakázáno[^zakazani-darci] a
c) republikové předsednictvo se záměrem předem souhlasilo a uzavřelo s dárcem písemnou darovací smlouvu s úředně ověřenými podpisy,[^darovaci-smlouvy] pokud má strana bezúplatně nabýt od jednoho dárce v jednom roce majetek nad 50 000 Kč.
[^identifikace]: § 18 odst. 1 písm. d) zákona č. 424/1991 Sb., o sdružování v politických stranách a v politických hnutích, ve znění pozdějších předpisů.
[^zakazani-darci]: § 19 zákona č. 424/1991 Sb., o sdružování v politických stranách a v politických hnutích, ve znění pozdějších předpisů.
[^darovaci-smlouvy]: § 18 odst. 3 zákona č. 424/1991 Sb., o sdružování v politických stranách a v politických hnutích, ve znění pozdějších předpisů.
#### § 8 Účel věci
(1) Věc může být závazně určena pro některý účel, případně také k užívání určitým orgánem nebo organizační jednotkou strany. Věc s určeným účelem je zakázáno zcizit za jiným účelem, dokud účelové určení trvá.
(2) Účelové určení vzniká, pokud tak stanoví předpis[^ropr] nebo v souladu s ním právní jednání, které stranu zavazuje.[^zavazek] Účel peněz v rozpočtové položce se stanoví podle rozpočtu schváleného v souladu s jiným předpisem.
(3) Pokud pro trvalou překážku nelze věc použít k určenému účelu, rozhodne její správce, že se použije k podobnému účelu, nebo účelové určení zruší a použije ji k plnění svých úkolů. Účel věci může republikový výbor také změnit, nemůže-li strana jinak splnit splatný závazek a přislíbí-li současně, že k původnímu účelu určí náhradní věc, jakmile to bude možné.
[^ropr]: § 3 rozpočtových pravidel.
[^zavazek]: Účelově určený dar, závěť.
#### § 9 Správa věci
(1) Věc spravuje[^sprava-veci] organizační složka, která ji za stranu obdržela, případně která má plnit úkoly, k nimž je věc určená nebo potřebná. V pochybnostech rozhoduje o správě nejblíže společné předsednictvo.
(2) Jen správce věci je oprávněn ji za stanovených podmínek zcizit nebo po dohodě převést správu na jinou organizační složku. Správce věci spravuje rovněž příslušenství věci.
(3) S věcí správce hospodaří s péčí řádného hospodáře, s přihlédnutím k jejímu účelu, politice strany a společenské odpovědnosti strany. Pokud to není na újmu této péči, lze s věcí hospodařit i jinak.
[^sprava-veci]: § 1400 a násl. občanského zákoníku.
#### § 10 Záměr a jeho celkové náklady
(1) **Záměr** je souhrn závazků v jedné rozpočtové jednotce[^rozpoctova-jednotka], které spolu věcně a časově úzce souvisí (např. koupě nebo prodej věci s příslušenstvím, organizace akce nebo turné, objednávka série plakátů a vylepení, koupě raznice a matrice na odznaky, počítač s monitorem a jeho příslušenství). Za záměr se považuje i opomenutí, které má za následek promlčení dluhu nebo jiné náklady.
(2) **Celkové náklady záměru** jsou vyjádřeny peněžitou hodnotou[^hodnota] nákladů, které lze v rozpočtové jednotce důvodně očekávat v souvislosti se záměrem, a to včetně rezervy na nečekané výdaje. Celkové náklady záměru se posuzují nezávisle na počtu účetních případů, do kterých byl záměr rozdělen. V případě výpůjčky, pronájmu, pachtu či věcného břemena k věci strany zahrnují náklady záměru též tržní odměnu, která je za užívání obvyklá.
[^hodnota]: § 492 zákona č. 89/2012 Sb., občanský zákoník.
[^rozpoctova-jednotka]: § 6 odst. 3 rozpočtových pravidel.
#### § 11 Schvalování záměru
(1) Ještě před objednávkou, uzavřením smlouvy, veřejným vyhlášením výběrového řízení nebo jiným vznikem závazku musí hospodář
a) odhadnout celkové náklady záměru,
b) zajistit v rozpočtu potřebné prostředky na záměr (z výdajové rozpočtové položky spravované jím samotným nebo jiným hospodářem s jeho souhlasem),
c) zajistit udělení a vyhlášení souhlasů jiných orgánů strany, pokud jsou potřeba.
(2) Záměr rozpočtové jednotky, jehož celkové náklady mají přesáhnout
a) prahovou hodnotu 5 000 Kč, je podmíněn souhlasem příslušného předsednictva,
b) prahovou hodnotu 50 000 Kč, je podmíněn souhlasem příslušného schvalujícího orgánu.[^schvalujici-organ]
(3) Prahovou hodnotu pro svůj souhlas může příslušný orgán usnesením snížit, a to jak pro jednotlivé případy, tak obecně.
(4) Souhlas se záměrem vyslovuje příslušný orgán usnesením, které obsahuje dostupné informace o záměru a výši jím odsouhlasených nákladů záměru. Do této výše jsou jím odsouhlasena všechna právní jednání.
(5) Dodatečné rozšíření záměru je podmíněno souhlasem příslušného orgánu, jen pokud jím neodsouhlasené náklady na tento záměr přesáhnou prahovou hodnotu pro souhlas.
[^schvalujici-organ]: § 6 odst. 3 rozpočtových pravidel.
#### § 12 Průhlednost hospodaření
Na webu strany se zveřejňují
a) faktury, objednávky a doklady na výdaje,
b) výroční finanční zprávy,
c) účetní výkazy podle zákona o účetnictví,
d) rozpočty a jejich plnění včetně žádostí o proplacení,
e) veškeré písemné smlouvy,
f) soupis věcí, které spravuje každá organizační složka, s jejich hodnotou a místem výskytu,
g) seznam transparentních bankovních účtů,
h) seznam jiných finančních účtů s přehledem transakcí na nich.
#### § 13 Účetní doklady
Hospodář je povinen každý výdaj řádně doložit ve stanovené lhůtě dokladem podle zákona.[^zou] Strana není zavázána uhradit náklady schváleného výdaje, pokud doklad neobdrží ani v dodatečně určené lhůtě.
[^zou]: Zákon č. 563/1991 Sb., o účetnictví, ve znění pozdějších předpisů.
### Hospodaření s penězi
#### § 14 Bankovní účty
(1) Strana hospodaří elektronicky. Veškeré peníze strany jsou výlučně na transparentních bankovních účtech strany ve správě finančního odboru. Bankovní účty strany zveřejňuje banka na své internetové stránce.
(2) Předseda strany zřídí k bankovnímu účtu správcovská oprávnění jen vedoucímu finančního odboru nebo jím pověřenému členu finančního odboru.
(3) Osoba, která má získat správcovská oprávnění k bankovnímu účtu, se musí straně předem písemně zavázat ke hmotné odpovědnosti za svěřené peníze na bankovním účtu.
#### § 15 Struktura bankovních účtů
(1) Pokud není stanoveno jinak, používá se hlavní účet strany. Ostatní účty se vedou u stejné banky jako hlavní účet strany. Okruh osob spravujících účet a rozsah jejich oprávnění se volí tak, aby bylo omezeno nebezpečí zneužití.
(2) Republikové předsednictvo může rozhodnout o zřízení spořícího nebo dočasného účelového bankovního účtu, s výjimkou bankovního účtu oblastního sdružení.
#### § 16 Žádost o proplacení
(1) Finanční odbor převádí peníze z bankovního účtu na žádost o proplacení podanou jejich hospodářem.
(2) Žádost musí obsahovat informaci o druhu výdaje podle zákonného třídění,[^trideni] jakož i jiné třídění stanovené finančním odborem.
(3) Před vyplácením rozhodnutím o žádosti finanční odbor zkoumá, zda výdaj odpovídá pravidlům hospodaření, zejména
a) zda byl výdaj schválen hospodářem organizační složky, která odpovídá za výdajovou rozpočtovou položku, ze které má být výdaj proplacen,[^ropr-odpovednost]
b) zda je výdaj součástí záměru, který mají odsouhlasit další orgány, případně zda je připojen jejich souhlas,
c) zda byla registrována výdajová rozpočtová položka, z níž má být výdaj proplacen, zda je v ní dostatek peněz pro proplacení a zda výdaj odpovídá určení rozpočtové položky,
d) zda byl výdaj hodnověrně doložen, pokud je proplácen zpětně,
e) zda je na bankovních účtech dostatek prostředků pro proplacení výdaje.
(4) Finanční odbor zamítne žádost, která je v rozporu s pravidly hospodaření. Jinak finanční odbor žádosti vyhoví a žádost proplatí zpětně nebo dopředu na účet příjemce bez zbytečného odkladu.
(5) Při vnitřních převodech mezi organizačními složkami se postupuje přiměřeně jako u žádosti o proplacení.
[^ropr-odpovednost]: § 8 odst. 1 písm. c) rozpočtových pravidel.
[^trideni]: § 18 odst. 1 písm. c) zákona č. 424/1991 Sb., o politických stranách a politických hnutích, ve znění pozdějších předpisů.
#### § 17 Domněnka komisionáře
(1) Pokud není příjemce uvedený v žádosti o proplacení přímým dodavatelem a není ujednáno jinak, považuje se příjemce za komisionáře, se kterým strana uzavřela bezúplatnou komisionářskou smlouvu podle obsahu žádosti.[^komisionar]
(2) Komisionář je povinen převést nabytý majetek na stranu a přiložit k žádosti o proplacení pokud možno účetní doklady, které mu vystavil přímý dodavatel.
[^komisionar]: § 2455 a násl. zákona č. 89/2012 Sb., občanský zákoník.
### Hospodaření s jinými věcmi
#### § 18 Předání hmotných věcí
Kdo pro stranu hodlá nabýt věc, která má hodnotu nad 5 000 Kč a není určena ke spotřebě, zařadí ji do soupisu věcí a odevzdá ji do správy příslušné organizační složce. Věc strana nabývá předáním příslušné organizační složce.
#### § 19 Licence
Členská díla[^zam-dilo] a díla vytvořená dobrovolníkem pro Českou pirátskou stranu jsou dostupná pod veřejnou nevýhradní licenci [CC-BY-SA verze 4](http://creativecommons.org/licenses/by-sa/4.0/). Není-li ujednáno jinak, poskytnutím díla straně dobrovolník uděluje tuto licenci. Strana může užívat nehmotný statek pro své propagační účely, a to i bez jména autora, je-li to při užití obvyklé.
[^zam-dilo]: § 58 odst. 10 zákona č. 121/2000 Sb., autorský zákon, ve znění pozdějších předpisů.
## Závěrečná ustanovení
#### § 20 Obchodní společnost
Strana může založit obchodní společnost nebo družstvo nebo se účastnit jako společník nebo člen na již založené obchodní společnosti nebo družstvu za podmínek stanovených zákonem,[^korporace] pokud republikový výbor vysloví předem souhlas se smlouvou, kterou mají být ujednány vztahy s touto obchodní společností nebo družstvem.
[^korporace]: § 17 odst. 3 zákona č. 424/1991 Sb., o sdružování v politických stranách a v politických hnutích, ve znění pozdějších předpisů.
#### § 21 Hospodaření s vkladem
Pokud strana vloží majetek do koalice, obchodní společnosti nebo družstva nebo jinak sdruží či vyčlení majetek k určitému účelu, musí aspoň co do vkladu strany předem smluvně zajistit hospodaření s péčí řádného hospodáře (§ 4), vyloučit zakázaná jednání (§ 5), zajistit průhlednost hospodaření (§ 12), jakož i možnost kontroly kontrolními orgány strany.
#### § 22 Sankce zastavení peněz
Porušuje-li organizační složka i přes upozornění pravidla hospodaření, finanční odbor jí rozhodnutím zakáže podávat žádosti o proplacení, dokud porušení nenapraví a neuhradí případnou škodu. Nestane-li se tak do dvou měsíců, vyšle finanční odbor do organizační složky svého člena, který smí učinit veškeré kroky nutné k nápravě.
#### § 23 Prováděcí předpisy
Tento předpis provede finanční odbor: Vyhláškou stanoví zejména
a) variabilní symboly pro všechny příchozí platby na účet,
b) lhůtu pro doložení transakce dokladem,
c) lhůty pro zpětné proplacení a ohlášku,
d) výši náhrady za cesty autem.
|
pirati-cz/sbirka
|
predpisy/prah/2014-08-02.md
|
Markdown
|
agpl-3.0
| 17,138
|
/**
* Revenue Settlement and Sharing System GE
* Copyright (C) 2011-2014, Javier Lucio - lucio@tid.es
* Telefonica Investigacion y Desarrollo, S.A.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package es.tid.fiware.rss.dao.impl.test;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import es.tid.fiware.rss.common.test.DatabaseLoader;
import es.tid.fiware.rss.dao.impl.CountryDaoImpl;
import es.tid.fiware.rss.model.BmCountry;
/**
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:database.xml" })
public class CountryDaoImplTest {
/**
* DAO for country.
*/
@Autowired
private CountryDaoImpl countryDAO;
/**
* Properties for database connection.
*/
@Autowired
private DatabaseLoader databaseLoader;
@Autowired
@Qualifier("transactionManager")
private HibernateTransactionManager transactionManager;
/**
* Method to insert data before test.
*
* @throws Exception
* from db
*/
@Before
public void setUp() throws Exception {
databaseLoader.cleanInsert("dbunit/CREATE_DATATEST_TRANSACTIONS.xml", true);
}
/**
* @throws Exception
*/
@After
public void tearDown() throws Exception {
databaseLoader.deleteAll("dbunit/CREATE_DATATEST_TRANSACTIONS.xml", true);
}
/**
* Test method for {@link es.tid.fiware.rss.dao.impl.CountryDaoImpl#getByIso3166Code(java.lang.String)}.
*/
@Test
public void test10GetByIso3166Code() {
// Call method to test
BmCountry c = countryDAO.getByIso3166Code("ES");
// Check result
Assert.assertNotNull("BmCountry is null", c);
Assert.assertTrue("ID not equeal", c.getNuCountryId() == 1);
Assert.assertTrue("ITU T 212 not equeal", c.getTxItuT212Code().compareTo("214") == 0);
Assert.assertTrue("ISO 3166 code not equeal", c.getTxIso3166Code().compareTo("ES") == 0);
Assert.assertTrue("Currency not equeal", c.getBmCurrency().getNuCurrencyId() == 1);
Assert.assertTrue("Language not equeal", c.getBmLanguage().getNuLanguageId() == 1);
}
/**
* Test method for {@link es.tid.fiware.rss.dao.impl.CountryDaoImpl#getByItuT212Code(java.lang.String)}.
*/
@Test
public void test20GetByItuT212Code() {
// Call method to test
BmCountry c = countryDAO.getByItuT212Code("214");
// Check result
Assert.assertNotNull("BmCountry is null", c);
Assert.assertTrue("ID not equeal", c.getNuCountryId() == 1);
Assert.assertTrue("ITU T 212 not equeal", c.getTxItuT212Code().compareTo("214") == 0);
Assert.assertTrue("ISO 3166 code not equeal", c.getTxIso3166Code().compareTo("ES") == 0);
Assert.assertTrue("Currency not equeal", c.getBmCurrency().getNuCurrencyId() == 1);
Assert.assertTrue("Language not equeal", c.getBmLanguage().getNuLanguageId() == 1);
}
}
|
telefonicaid/fiware-rss
|
rss-core/rss-dao/src/test/java/es/tid/fiware/rss/dao/impl/test/CountryDaoImplTest.java
|
Java
|
agpl-3.0
| 4,005
|
/*
* Ktunaxa Referral Management System.
*
* Copyright (C) see version control system
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ktunaxa.referral.server.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.inmemory.ConfigConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* In memory service for testing.
*
* @author Jan De Moerloose
*
*/
public class InMemoryCmisService extends CmisServiceImpl {
private final Logger log = LoggerFactory.getLogger(InMemoryCmisService.class);
@Autowired
private CmisConfig config;
private Repository repository;
private Map<String, String> parameter = new HashMap<String, String>();
private Session session;
@PostConstruct
public synchronized void initialize() {
config = new CmisConfig();
config.setFolder("Ktunaxa");
config.setUrl("d/");
config.setUrlBrowse("d/");
parameter.put(SessionParameter.BINDING_TYPE, BindingType.LOCAL.value());
// Session locale.
parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "");
parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "nl");
parameter.put(SessionParameter.LOCALE_VARIANT, "BE");
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS,
"org.apache.chemistry.opencmis.client.runtime.repository.ObjectFactoryImpl");
parameter.put(SessionParameter.LOCAL_FACTORY,
"org.apache.chemistry.opencmis.inmemory.server.InMemoryServiceFactoryImpl");
parameter.put(SessionParameter.REPOSITORY_ID, "Main Repository");
parameter.put(ConfigConstants.REPOSITORY_ID, "Main Repository");
// This supposes only one repository is available at the URL.
}
public synchronized Session createSession() {
if (session == null) {
checkRepository();
session = repository.createSession();
}
return session;
}
private synchronized void checkRepository() {
if (repository == null) {
SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
try {
repository = sessionFactory.getRepositories(parameter).get(0);
} catch (Exception e) {
log.error("Error: Initialize CmisService failed: " + e.getMessage(), e);
}
}
}
public synchronized String getBaseUrl() {
return super.getBaseUrl();
}
public synchronized Folder getWorkingFolder() throws IOException {
return super.getWorkingFolder();
}
public synchronized String getDownloadUrl(Document document) {
return getDocumentUrl(document, "save");
}
public synchronized String getDisplayUrl(Document document) {
return getDocumentUrl(document, "open");
}
private synchronized String getDocumentUrl(Document document, String type) {
String docId = document.getId();
return config.getUrlBrowse() + "cmis/" + document.getContentStreamFileName() + "?id=" + docId + "&type=" + type;
}
public synchronized Document saveOrUpdate(String documentName, String mimeType, InputStream in, long contentLength,
String... folderNames) throws IOException {
return super.saveOrUpdate(documentName, mimeType, in, contentLength, folderNames);
}
public synchronized Document create(String documentName, String mimeType, InputStream in, long contentLength,
String... folderNames) throws IOException {
return super.create(documentName, mimeType, in, contentLength, folderNames);
}
protected synchronized Document create(String documentName, String mimeType, InputStream in, long contentLength,
boolean canUpdate, String... folderNames) throws IOException {
return super.create(documentName, mimeType, in, contentLength, canUpdate, folderNames);
}
public synchronized Document read(String documentName) throws IOException {
return super.read(documentName);
}
public synchronized void update(String documentName, String mimeType, InputStream in) throws IOException {
super.update(documentName, mimeType, in);
}
public synchronized void delete(String documentName) throws IOException {
super.delete(documentName);
}
}
|
ktunaxa/rms
|
map/src/main/java/org/ktunaxa/referral/server/service/InMemoryCmisService.java
|
Java
|
agpl-3.0
| 5,229
|
from .sources import TestSources
__all__ = ["TestSources"]
|
kaini/newslist
|
server/newslist/tests/__init__.py
|
Python
|
agpl-3.0
| 60
|
/*
All emon_widgets code is released under the GNU General Public License v3.
See COPYRIGHT.txt and LICENSE.txt.
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
Author: Trystan Lea: trystan.lea@googlemail.com
If you have any questions please get in touch, try the forums here:
http://openenergymonitor.org/emon/forum
*/
function vis_widgetlist(){
var widgets = {
"realtime":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","colour","initzoom"],
"optionstype":["feedid","colour_picker","dropbox"],
"optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Zoom")],
"optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Default visible window interval")],
"optionsdata": [ , , [["1", "1 "+_Tr("minute")],["5", "5 "+_Tr("minutes")],["15", "15 "+_Tr("minutes")],["30", "30 "+_Tr("minutes")],["60", "1 "+ _Tr("hour")]] ],
"html":""
},
"rawdata":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","colour","units","dp","scale","fill","initzoom"],
"optionstype":["feedid","colour_picker","value","value","value","value","dropbox"],
"optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("Fill"),_Tr("Zoom")],
"optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Fill value"),_Tr("Default visible window interval")],
"optionsdata": [ , , , , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ],
"html":""
},
"bargraph":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","colour","interval","units","dp","scale","delta"],
"optionstype":["feedid","colour_picker","value","value","value","value","boolean"],
"optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Interval"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("delta")],
"optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Interval (seconds)-you can set \"d\" for day, \"m\" for month, or \"y\" for year"),_Tr("Units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Show difference between each bar")],
"html":""
},
"timestoredaily":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","units","initzoom"],
"optionstype":["feedid","value","dropbox"],
"optionsname":[_Tr("Feed"),_Tr("Units"),_Tr("Zoom")],
"optionshint":[_Tr("Feed source"),_Tr("Units to show"),_Tr("Default visible window interval")],
"optionsdata": [ , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ],
"html":""
},
"zoom":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["power","kwhd","currency","currency_after_val","pricekwh","delta"],
"optionstype":["feedid","feedid","value","value","value","boolean"],
"optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("Currency"),_Tr("Currency position"),_Tr("Kwh price"),_Tr("delta")],
"optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Currency to show"),_Tr("0 = before value, 1 = after value"),_Tr("Set kwh price"),_Tr("Show difference between each bar")],
"html":""
},
"simplezoom":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["power","kwhd","delta"],
"optionstype":["feedid","feedid","boolean"],
"optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("delta")],
"optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Show difference between each bar")],
"html":""
},
"histgraph":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid"],
"optionstype":["feedid"],
"optionsname":[_Tr("Feed")],
"optionshint":[_Tr("Feed source")],
"html":""
},
"threshold":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","thresholdA","thresholdB","initzoom"],
"optionstype":["feedid","value","value","dropbox"],
"optionsname":[_Tr("Feed"),_Tr("Threshold A"),_Tr("Threshold B"),_Tr("Zoom")],
"optionshint":[_Tr("Feed source"),_Tr("Threshold A used"),_Tr("Threshold B used"),_Tr("Default visible window interval")],
"optionsdata": [ , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ],
"html":""
},
"orderthreshold":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","power","thresholdA","thresholdB"],
"optionstype":["feedid","feedid","value","value"],
"optionsname":[_Tr("Feed"),_Tr("Power"),_Tr("Threshold A"),_Tr("Threshold B")],
"optionshint":[_Tr("Feed source"),_Tr("Power"),_Tr("Threshold A used"),_Tr("Threshold B used")],
"html":""
},
"orderbars":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","delta"],
"optionstype":["feedid","boolean"],
"optionsname":[_Tr("Feed"),_Tr("delta")],
"optionshint":[_Tr("Feed source"),_Tr("Show difference between each bar")],
"html":""
},
"stacked":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["bottom","top","colourt","colourb","delta"],
"optionstype":["feedid","feedid","colour_picker","colour_picker","boolean"],
"optionsname":[_Tr("Bottom"),_Tr("Top"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("delta")],
"optionshint":[_Tr("Bottom feed value"),_Tr("Top feed value"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("Show difference between each bar")],
"html":""
},
"stackedsolar":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["solar","consumption","delta"],
"optionstype":["feedid","feedid","boolean"],
"optionsname":[_Tr("Solar"),_Tr("Consumption"),_Tr("delta")],
"optionshint":[_Tr("Solar feed value"),_Tr("Consumption feed value"),_Tr("Show difference between each bar")],
"html":""
},
"smoothie":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","ufac"],
"optionstype":["feedid","value"],
"optionsname":[_Tr("Feed"),_Tr("Ufac")],
"optionshint":[_Tr("Feed source"),_Tr("Ufac value")],
"html":""
},
"multigraph":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["mid"],
"optionstype":["dropbox"],
"optionsname":[_Tr("Multigraph")],
"optionshint":[_Tr("Managed on Visualization module")],
"optionsdata":[multigraphsDropBoxOptions], // Gets multigraphs from vis_widget.php multigraphsDropBoxOptions variable
"html":""
},
"timecompare":
{
"offsetx":0,"offsety":0,"width":400,"height":300,
"menu":"Visualisations",
"options":["feedid","fill","depth","npoints","initzoom"],
"optionstype":["feedid","value","value","value","dropbox"],
"optionsname":[_Tr("Feed"),_Tr("Fill"),_Tr("Depth"),_Tr("Data points"),_Tr("Zoom")],
"optionshint":[_Tr("Feed source"),_Tr("Fill under line"),_Tr("Number of lines"),_Tr("Default: 800"),_Tr("Default visible window interval")],
"optionsdata": [ , , , , [["8", "8 " + _Tr("Hours")],["24", _Tr("Day")],["168", _Tr("Week")],["672", _Tr("Month")],["8760", _Tr("Year")]] ],
"html":""
}
}
return widgets;
}
function vis_init(){
vis_draw();
}
function vis_draw(){
var vislist = vis_widgetlist();
var visclasslist = '';
for (z in vislist) { visclasslist += '.'+z+','; }
visclasslist = visclasslist.slice(0, -1);
$(visclasslist).each(function(){
var id = $(this).attr("id");
var feed = $(this).attr("feed") || 0;
var width = $(this).width();
var height = $(this).height();
var apikey_string = "";
if (apikey) apikey_string = "&apikey="+apikey;
if (!$(this).html() || reloadiframe==id || reloadiframe==-1 || apikey){
var attrstring = "";
var target = $(this).get(0);
var l = target.attributes.length;
for (var i=0; i<l; i++){
var attr = target.attributes[i].name;
if (attr!="id" && attr!="class" && attr!="style"){
attrstring += "&"+attr+"="+target.attributes[i].value;
}
}
pathfix=path.substr(path.indexOf('://')+3); // remove protocol
pathfix=pathfix.substr(pathfix.indexOf('/')); // remove hostname
$(this).html('<iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string+'"></iframe>');
console.log('--> new relative url for iframe of '+ $(this).attr("class") + ': '+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string);
}
var iframe = $(this).children('iframe');
iframe.width(width);
iframe.height(height);
});
reloadiframe = 0;
}
function vis_slowupdate() {}
function vis_fastupdate() {}
|
thaipowertech/emoncms
|
Modules/vis/widget/vis_render.js
|
JavaScript
|
agpl-3.0
| 9,506
|
<?php
/*
* @author Anakeen
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
* @package FDL
*/
/**
* Modify family preferences
*
* @author Anakeen 2007
* @version $Id: generic_modprefs.php,v 1.2 2007/05/04 16:11:40 eric Exp $
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
* @package FDL
* @subpackage
*/
/**
*/
include_once ("FDL/Class.Doc.php");
include_once ("GENERIC/generic_util.php");
function generic_modprefs(&$action)
{
$famid = GetHttpVars("famid"); // family id
$dirid = GetHttpVars("dirid"); // last searched
$dispo = GetHttpVars("dispo"); // last searched
$letters = GetHttpVars("letters"); // want tab letters
$inherit = GetHttpVars("inherit"); // search in inherit
$dbaccess = $action->getParam("FREEDOM_DB");
$fdoc = new_doc($dbaccess, $famid);
if (!$fdoc->isAlive()) {
$action->exitError(sprintf(_("Family (#%s) not exists") , $famid));
}
switch ($dispo) {
case 1:
$split = 'V';
$visu = 'abstract';
break;
case 2:
$split = 'H';
$visu = 'column';
break;
case 3:
$split = 'V';
$visu = 'column';
break;
case 4:
$split = 'H';
$visu = 'abstract';
break;
}
if ($dispo > 0) {
setSplitMode($action, $famid, $split);
setViewMode($action, $famid, $visu);
}
if ($letters == 1) setTabLetter($action, $famid, 'Y');
else setTabLetter($action, $famid, 'N');
if ($inherit == 1) setInherit($action, $famid, 'Y');
else setInherit($action, $famid, 'N');
$action->lay->set("famtitle", $fdoc->title);
$action->lay->set("famid", $famid);
$action->lay->set("dirid", $dirid);
redirect($action, "GENERIC", "GENERIC_TAB&tab=0&dirid=$dirid&famid=$famid", $action->GetParam("CORE_STANDURL"));
}
?>
|
Eric-Brison/dynacase-core
|
Action/Generic/generic_modprefs.php
|
PHP
|
agpl-3.0
| 2,008
|
/**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.example;
import java.util.Iterator;
/**
* Iterates over either only the regular attribute, only the special attributes, or over all all
* attributes.
*
* @author Ingo Mierswa
*/
public class AttributeIterator implements Iterator<Attribute> {
private Iterator<AttributeRole> parent;
private int type = Attributes.REGULAR;
private Attribute current = null;
private boolean hasNextInvoked = false;
private AttributeRole currentRole = null;
public AttributeIterator(Iterator<AttributeRole> parent, int type) {
this.parent = parent;
this.type = type;
}
@Override
public boolean hasNext() {
this.hasNextInvoked = true;
if (!parent.hasNext() && currentRole == null) {
current = null;
return false;
} else {
AttributeRole role;
if (currentRole == null) {
role = parent.next();
} else {
role = currentRole;
}
switch (type) {
case Attributes.REGULAR:
if (!role.isSpecial()) {
current = role.getAttribute();
currentRole = role;
return true;
} else {
return hasNext();
}
case Attributes.SPECIAL:
if (role.isSpecial()) {
current = role.getAttribute();
currentRole = role;
return true;
} else {
return hasNext();
}
case Attributes.ALL:
current = role.getAttribute();
currentRole = role;
return true;
default:
current = null;
return false;
}
}
}
@Override
public Attribute next() {
if (!this.hasNextInvoked) {
hasNext();
}
this.hasNextInvoked = false;
this.currentRole = null;
return current;
}
@Override
public void remove() {
parent.remove();
this.currentRole = null;
this.hasNextInvoked = false;
}
}
|
rapidminer/rapidminer-studio
|
src/main/java/com/rapidminer/example/AttributeIterator.java
|
Java
|
agpl-3.0
| 2,654
|
/*********************************************************************************
*
* This file is part of ZelosOnline.
*
* ZelosOnline is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* ZelosOnline is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013 Rafael Dominguez (npcdoom)
*
*********************************************************************************/
#ifndef __ZELOS_GATEWAYD_SERVER_PACKET_H__
#define __ZELOS_GATEWAYD_SERVER_PACKET_H__
#include <map>
#include <boost/shared_ptr.hpp>
#include "news.h"
#include "shard.h"
class OPacket;
namespace srv_pkt
{
void WriteNews (OPacket *pkt, const std::map<uint32_t,Notice> &news);
void WriteShards (OPacket *pkt, const std::string &name, const uint8_t global_version,
const std::map<uint16_t,Shard> &servers, const bool state);
void C5 (OPacket *pkt);
}
#endif // __ZELOS_GATEWAYD_SERVER_PACKET_H__
|
npcdoom/ZelosOnline
|
gatewayd/server/packet.h
|
C
|
agpl-3.0
| 1,464
|
/*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.contribution.attachment.util;
import org.silverpeas.core.admin.component.model.SilverpeasComponent;
import org.silverpeas.core.util.ResourceLocator;
import org.silverpeas.core.util.SettingBundle;
import org.silverpeas.core.util.StringUtil;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Handled the settings around the attachments.
* @author Yohann Chastagnier
*/
public class AttachmentSettings {
public static final int DEFAULT_REORDER_START = 1;
public static final int YOUNGEST_TO_OLDEST_MANUAL_REORDER_START = 200000;
public static final int YOUNGEST_TO_OLDEST_MANUAL_REORDER_THRESHOLD = 100000;
private static SettingBundle settings =
ResourceLocator.getSettingBundle("org.silverpeas.util.attachment.Attachment");
private AttachmentSettings() {
throw new IllegalStateException("Utility class");
}
/**
* Gets the delay in percent after which an alert MUST be sent to the owner in order to remind
* it to release the reserved file.
* @return an integer representing a percentage, -1 means no value.
*/
public static int getDelayInPercentAfterWhichReservedFileAlertMustBeSent() {
return settings.getInteger("DelayReservedFile", -1);
}
/**
* Indicates the order the methods in charge of returning list of documents must apply.
* @return false to list from oldest to youngest, true to list from the youngest to the oldest.
*/
public static boolean listFromYoungestToOldestAdd() {
final int order = settings.getInteger("attachment.list.order", 1);
return order < 0;
}
/**
* Indicates if metadata of a file, if any, can be used to fill data (title & description) of an
* attachment. (defined in properties by attachment.data.fromMetadata)
* @return true if they must be used, false otherwise.
*/
public static boolean isUseFileMetadataForAttachmentDataEnabled() {
return settings.getBoolean("attachment.data.fromMetadata", false);
}
/**
* Gets the stream of component name for which the the displaying as content is enabled.
* @return {@link Stream} of component name as {@link String}.
*/
public static Stream<String> displayableAsContentComponentNames() {
return Stream
.of(settings.getString("attachmentsAsContent.component.names", StringUtil.EMPTY).split("[ ,;]"))
.map(String::trim);
}
/**
* Gets the default value of the JCR flag which indicates if a document is displayable as content.
* @return true of displayable as content, false otherwise.
*/
public static boolean defaultValueOfDisplayableAsContentBehavior() {
return settings.getBoolean("attachmentsAsContent.default.value", true);
}
/**
* Indicates if the displaying as content is enabled for a component instance represented by
* the given identifier.
* @param componentInstanceId identifier of a component instance.
* @return true if activated, false otherwise.
*/
public static boolean isDisplayableAsContentForComponentInstanceId(
final String componentInstanceId) {
return displayableAsContentComponentNames()
.map(c -> {
final Optional<SilverpeasComponent> component = SilverpeasComponent.getByInstanceId(componentInstanceId);
return component.isPresent() && component.get().getName().equalsIgnoreCase(c.trim());
})
.filter(b -> b)
.findFirst()
.orElse(false);
}
/**
* Gets the default value of the JCR flag which indicates if a document is editable simultaneously.
* @return true if editable simultaneously, false otherwise.
*/
public static boolean defaultValueOfEditableSimultaneously() {
return settings.getBoolean("attachment.onlineEditing.simultaneously.default", true);
}
}
|
SilverDav/Silverpeas-Core
|
core-library/src/main/java/org/silverpeas/core/contribution/attachment/util/AttachmentSettings.java
|
Java
|
agpl-3.0
| 4,900
|
from django.apps import AppConfig
class ClassifConfig(AppConfig):
name = 'classif'
|
bricaud/wevia
|
classif/apps.py
|
Python
|
agpl-3.0
| 89
|
const passport = require('../helpers/auth/passport_factory');
const logger = require('../../lib/logger');
const adminChecker = require('../helpers/auth/request_admin_checker');
const oauthConfig = require('../../config/oauth/oauth_config.js');
module.exports.logout = function(req, res) {
req.logout();
res.status(200).json({});
};
module.exports.loginTwitter = function(req, res, next) {
passport.authenticate('twitter')(req, res, next);
};
module.exports.loginInstagram = function(req, res, next) {
passport.authenticate('instagram', {scope: 'basic', failWithError: true})(req, res, next);
};
module.exports.loginFacebook = function(req, res, next) {
passport.authenticate('facebook', {scope: 'email', session:false})(req, res, next);
};
module.exports.loginGoogle = function(req, res, next) {
passport.authenticate('google', { scope: ['email'] })(req, res, next);
};
module.exports.loginCallbackTwitter = function(req, res) {
passport.authenticate('twitter')(req, res, function(err) {
if (err) {
logger.error('Error logging in with twitter:' + err);
res.status(403).json({'message': err});
return;
}
res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin'));
});
};
module.exports.loginCallbackFacebook = function(req, res) {
passport.authenticate('facebook')(req, res, function(err){
if (err) {
logger.error('Error logging in with facebook:' + err);
res.status(403).json({'message': err});
return;
}
res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin'));
});
};
module.exports.loginCallbackGoogle = function(req, res) {
passport.authenticate('google')(req, res, function(err){
if (err) {
logger.error('Error logging in with google:' + err);
res.status(403).json({'message': err});
return;
}
res.redirect(oauthConfig.get('redirectURLOnSuccessfulLogin'));
});
};
module.exports.getAccountPermissions = function(req, res) {
if (!adminChecker.isLoggedIn(req)) {
res.status(403).json({'message': 'Not logged in'});
return;
}
if (adminChecker.isRequestDirectoryAdmin(req)) {
res.status(200).json({'directoryAdmin': true});
return;
}
let enterprisePermissions = adminChecker.getAuthenticatedEnterprisesByRequest(req);
res.status(200).json(
{
'directoryAdmin': false,
'authenticatedEnterprises': enterprisePermissions
}
);
};
|
cised-ca/social-enterprise-directory
|
api/controllers/account_controller.js
|
JavaScript
|
agpl-3.0
| 2,409
|
---
layout: post
title: CC at OSCON, Eric Steuer on Slideshare
date: 2007-07-30 16:28:12.000000000 -04:00
categories:
- Weblog
tags: []
status: publish
type: post
published: true
meta: {}
author:
login: cameron
email: webmaster+cameron@creativecommons.org
display_name: Cameron Parkins
first_name: Cameron
last_name: Parkins
---
<p>We had a great time at <a href="http://conferences.oreillynet.com/os2007/">OSCON</a> last week - <a href="http://conferences.oreillynet.com/cs/os2007/view/e_sess/14608">Nathan Yergler</a>, CTO, and <a href="http://conferences.oreillynet.com/cs/os2007/view/e_sess/14607">Jon Phillips</a>, Business + Community Developer, gave two presentations on CC and the open source community while Mozilla and CC held a party to the jams of the one and only <a href="http://www.menomena.com/">Menomena</a>. Although somewhat delayed, here is a nice digital trail of our escapades:</p>
<ul>
<li>Nathan Yergler - <a href="http://www.slideshare.net/nyergler/integrating-cc-licensing-with-applications/">Integrating CC Licensing with Applications</a> (via <a href="http://www.slideshare.net/">slideshare.net</a>)</li>
<li>Jon Phillips - <a href="http://www.slideshare.net/rejon/refining-copyright-oscon-2007/">Refining Copyright Oscon 2007</a></li>
<li>Mozilla/CC Party - <a href="http://www.flickr.com/photos/9345516@N06/sets/72157601022823190/">Photos</a> (via <a href="http://flickr.com/">flickr</a>)</li>
</ul>
<p>In other CC news, Eric Steuer, Creative Director, posted two of his most recent presentations on slideshare.net as well - check them out <a href="http://www.slideshare.net/ericcc/creative-commons-presentation-for-the-july-11-2007-yahoo-creative-talk-pdf-format/">here</a> and <a href="http://www.slideshare.net/ericcc/creative-commons-presentation-for-the-2007-stanford-professional-publishing-course-pdf-format/">here</a> (<em><strong>UPDATE:</strong> These links now link to the correct presentations</em>).</p>
|
creativecommons/www2015
|
_source/_posts/2007-07-30-cc-at-oscon-eric-steuer-on-slideshare.html
|
HTML
|
agpl-3.0
| 1,957
|
/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.70
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#ifndef PRNG_SETUP_H
#define PRNG_SETUP_H
#include "MersenneTwister.h"
#include "BasicTypes.h" //For uint/ulong
class Reader;
namespace config_setup
{
struct RestartSettings;
struct PRNGKind;
}
namespace prng_setup
{
struct PRNGInitData {
PRNGInitData() : loadArray(NULL) {}
//WARNING/NOTE: Object is passed off, NOT deleted.
~PRNGInitData(void)
{
delete[] loadArray;
}
//Init from file.
void Init(Reader & prngSeed, const ulong resStep);
//Init from unsigned integer seed.
void Init(const uint seed)
{
prng = new MTRand((MTRand::uint32)(seed));
}
//Init pure random.
void Init(void)
{
prng = new MTRand();
}
void HandleError(std::string const& mode);
MTRand * prng;
private:
//Goto correct step in seed dump file.
void Goto(Reader & prngSeed, const ulong resStep);
//Read in saved seed;
void Read(Reader & prngSeed);
MTRand::uint32 * loadArray;
};
}
class PRNGSetup
{
public:
prng_setup::PRNGInitData prngMaker;
void Init(config_setup::RestartSettings const& restart,
config_setup::PRNGKind const& genConf,
std::string const& name);
static const std::string seedFileAlias;
};
#endif /*PRNG_SETUP_H*/
|
GOMC-WSU/GOMC
|
src/PRNGSetup.h
|
C
|
agpl-3.0
| 1,587
|
/* by @darthvid@niu.moe, (c) 2017 */
/* grid area */
/* "clear fix", is this really needed? */
.grid:after {
content: '';
display: block;
clear: both;
}
.grid-NSFW {
border: dashed #009999;
color: #009999;
text-align: center;
vertical-align: middle;
}
img:hover {
box-shadow: 0 0 5px 5px #b6b5b4;
}
/* header area */
.button-group {
float: left;
}
.editbox {
margin-bottom: 5px;
}
.inputInstance {
float: left;
color: gray;
}
.navLinks {
float: right;
}
#headerleft {
float: left;
margin-right: 5px;
}
#ebinstancebar {
float: left;
}
#headerright {
float: right;
margin-left: 5px;
}
#version {
float: right;
color: white;
}
#headerbar:after {
content: '';
display: block;
clear: both;
}
#btnIsPolling {
width: 40px;
}
#btnNSFW {
width: 100px;
}
#btnLocal {
width: 130px;
}
/* image zoom modal */
.modal {
display: none;
margin: auto;
z-index: 1;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.61);
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
padding-top: 60px;
/*
overflow: auto;
*/
}
.modal-content {
margin: auto;
display: block;
z-index: 2;
}
#imgZoom:hover {
box-shadow: none;
}
#txtModal {
text-align: center;
padding-top: 5px;
height: 150px;
}
.modal-content,
#txtModal {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
@-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
.closeX {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.closeX:hover,
.closeX:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* generic body */
body {
background-color: black;
}
a:link {
text-decoration: none;
color: white;
}
a:visited {
text-decoration: none;
color: white;
}
a:hover {
text-decoration: underline;
color: gray;
}
a:active {
text-decoration: underline;
color: gray;
}
|
tehdarthvid/tusktowall
|
css/style.css
|
CSS
|
agpl-3.0
| 2,072
|
<?php
/**
* Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file. */
namespace Test\Files;
use OC\Cache\CappedMemoryCache;
use OC\Files\Cache\Watcher;
use OC\Files\Filesystem;
use OC\Files\Storage\Common;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Temporary;
use OC\Files\View;
use OCP\Files\FileInfo;
use OCP\Lock\ILockingProvider;
use OCP\Util;
use Test\TestCase;
class TemporaryNoTouch extends Temporary {
public function touch($path, $mtime = null) {
return false;
}
}
class TemporaryNoCross extends Temporary {
public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
return Common::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
}
public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
return Common::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
}
}
class TemporaryNoLocal extends Temporary {
public function instanceOfStorage($className) {
if ($className === '\OC\Files\Storage\Local') {
return false;
} else {
return parent::instanceOfStorage($className);
}
}
}
/**
* Class ViewTest
*
* @group DB
*
* @package Test\Files
*/
class ViewTest extends TestCase {
/**
* @var \OC\Files\Storage\Storage[] $storages
*/
private $storages = [];
/**
* @var string
*/
private $user;
/**
* @var \OCP\IUser
*/
private $userObject;
/**
* @var \OCP\IGroup
*/
private $groupObject;
/** @var \OC\Files\Storage\Storage */
private $tempStorage;
protected function setUp() {
parent::setUp();
\OC_Hook::clear();
\OC_User::clearBackends();
\OC_User::useBackend(new \Test\Util\User\Dummy());
//login
$userManager = \OC::$server->getUserManager();
$groupManager = \OC::$server->getGroupManager();
$this->user = 'test';
$this->userObject = $userManager->createUser('test', 'test');
$this->groupObject = $groupManager->createGroup('group1');
$this->groupObject->addUser($this->userObject);
$this->loginAsUser($this->user);
// clear mounts but somehow keep the root storage
// that was initialized above...
Filesystem::clearMounts();
$this->tempStorage = null;
}
protected function tearDown() {
\OC_User::setUserId($this->user);
foreach ($this->storages as $storage) {
$cache = $storage->getCache();
$ids = $cache->getAll();
$cache->clear();
}
if ($this->tempStorage) {
system('rm -rf ' . escapeshellarg($this->tempStorage->getDataDir()));
}
$this->logout();
$this->userObject->delete();
$this->groupObject->delete();
$mountProviderCollection = \OC::$server->getMountProviderCollection();
TestCase::invokePrivate($mountProviderCollection, 'providers', [[]]);
parent::tearDown();
}
/**
* @medium
*/
public function testCacheAPI() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
$root = $this->getUniqueID('/');
Filesystem::mount($storage1, [], $root . '/');
Filesystem::mount($storage2, [], $root . '/substorage');
Filesystem::mount($storage3, [], $root . '/folder/anotherstorage');
$textSize = strlen("dummy file data\n");
$imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo.png');
$storageSize = $textSize * 2 + $imageSize;
$storageInfo = $storage3->getCache()->get('');
$this->assertEquals($storageSize, $storageInfo['size']);
$rootView = new View($root);
$cachedData = $rootView->getFileInfo('/foo.txt');
$this->assertEquals($textSize, $cachedData['size']);
$this->assertEquals('text/plain', $cachedData['mimetype']);
$this->assertNotEquals(-1, $cachedData['permissions']);
$cachedData = $rootView->getFileInfo('/');
$this->assertEquals($storageSize * 3, $cachedData['size']);
$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
// get cached data excluding mount points
$cachedData = $rootView->getFileInfo('/', false);
$this->assertEquals($storageSize, $cachedData['size']);
$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
$cachedData = $rootView->getFileInfo('/folder');
$this->assertEquals($storageSize + $textSize, $cachedData['size']);
$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
$folderData = $rootView->getDirectoryContent('/');
/**
* expected entries:
* folder
* foo.png
* foo.txt
* substorage
*/
$this->assertEquals(4, count($folderData));
$this->assertEquals('folder', $folderData[0]['name']);
$this->assertEquals('foo.png', $folderData[1]['name']);
$this->assertEquals('foo.txt', $folderData[2]['name']);
$this->assertEquals('substorage', $folderData[3]['name']);
$this->assertEquals($storageSize + $textSize, $folderData[0]['size']);
$this->assertEquals($imageSize, $folderData[1]['size']);
$this->assertEquals($textSize, $folderData[2]['size']);
$this->assertEquals($storageSize, $folderData[3]['size']);
$folderData = $rootView->getDirectoryContent('/substorage');
/**
* expected entries:
* folder
* foo.png
* foo.txt
*/
$this->assertEquals(3, count($folderData));
$this->assertEquals('folder', $folderData[0]['name']);
$this->assertEquals('foo.png', $folderData[1]['name']);
$this->assertEquals('foo.txt', $folderData[2]['name']);
$folderView = new View($root . '/folder');
$this->assertEquals($rootView->getFileInfo('/folder'), $folderView->getFileInfo('/'));
$cachedData = $rootView->getFileInfo('/foo.txt');
$this->assertFalse($cachedData['encrypted']);
$id = $rootView->putFileInfo('/foo.txt', ['encrypted' => true]);
$cachedData = $rootView->getFileInfo('/foo.txt');
$this->assertTrue($cachedData['encrypted']);
$this->assertEquals($cachedData['fileid'], $id);
$this->assertFalse($rootView->getFileInfo('/non/existing'));
$this->assertEquals([], $rootView->getDirectoryContent('/non/existing'));
}
/**
* @medium
*/
public function testGetPath() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
Filesystem::mount($storage3, [], '/folder/anotherstorage');
$rootView = new View('');
$cachedData = $rootView->getFileInfo('/foo.txt');
/** @var int $id1 */
$id1 = $cachedData['fileid'];
$this->assertEquals('/foo.txt', $rootView->getPath($id1));
$cachedData = $rootView->getFileInfo('/substorage/foo.txt');
/** @var int $id2 */
$id2 = $cachedData['fileid'];
$this->assertEquals('/substorage/foo.txt', $rootView->getPath($id2));
$folderView = new View('/substorage');
$this->assertEquals('/foo.txt', $folderView->getPath($id2));
}
/**
* @expectedException \OCP\Files\NotFoundException
*/
function testGetPathNotExisting() {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$rootView = new View('');
$cachedData = $rootView->getFileInfo('/foo.txt');
/** @var int $id1 */
$id1 = $cachedData['fileid'];
$folderView = new View('/substorage');
$this->assertNull($folderView->getPath($id1));
}
/**
* @medium
*/
public function testMountPointOverwrite() {
$storage1 = $this->getTestStorage(false);
$storage2 = $this->getTestStorage();
$storage1->mkdir('substorage');
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$rootView = new View('');
$folderContent = $rootView->getDirectoryContent('/');
$this->assertEquals(4, count($folderContent));
}
public function sharingDisabledPermissionProvider() {
return [
['no', '', true],
['yes', 'group1', false],
];
}
/**
* @dataProvider sharingDisabledPermissionProvider
*/
public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable) {
// Reset sharing disabled for users cache
$this->invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
$appConfig = \OC::$server->getAppConfig();
$oldExcludeGroupsFlag = $appConfig->getValue('core', 'shareapi_exclude_groups', 'no');
$oldExcludeGroupsList = $appConfig->getValue('core', 'shareapi_exclude_groups_list', '');
$appConfig->setValue('core', 'shareapi_exclude_groups', $excludeGroups);
$appConfig->setValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList);
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/mount');
$view = new View('/');
$folderContent = $view->getDirectoryContent('');
$this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
$folderContent = $view->getDirectoryContent('mount');
$this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
$appConfig->setValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag);
$appConfig->setValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList);
// Reset sharing disabled for users cache
$this->invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
}
public function testCacheIncompleteFolder() {
$storage1 = $this->getTestStorage(false);
Filesystem::clearMounts();
Filesystem::mount($storage1, [], '/incomplete');
$rootView = new View('/incomplete');
$entries = $rootView->getDirectoryContent('/');
$this->assertEquals(3, count($entries));
// /folder will already be in the cache but not scanned
$entries = $rootView->getDirectoryContent('/folder');
$this->assertEquals(1, count($entries));
}
public function testAutoScan() {
$storage1 = $this->getTestStorage(false);
$storage2 = $this->getTestStorage(false);
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$textSize = strlen("dummy file data\n");
$rootView = new View('');
$cachedData = $rootView->getFileInfo('/');
$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
$this->assertEquals(-1, $cachedData['size']);
$folderData = $rootView->getDirectoryContent('/substorage/folder');
$this->assertEquals('text/plain', $folderData[0]['mimetype']);
$this->assertEquals($textSize, $folderData[0]['size']);
}
/**
* @medium
*/
public function testSearch() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$storage3 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
Filesystem::mount($storage3, [], '/folder/anotherstorage');
$rootView = new View('');
$results = $rootView->search('foo');
$this->assertEquals(6, count($results));
$paths = [];
foreach ($results as $result) {
$this->assertEquals($result['path'], Filesystem::normalizePath($result['path']));
$paths[] = $result['path'];
}
$this->assertContains('/foo.txt', $paths);
$this->assertContains('/foo.png', $paths);
$this->assertContains('/substorage/foo.txt', $paths);
$this->assertContains('/substorage/foo.png', $paths);
$this->assertContains('/folder/anotherstorage/foo.txt', $paths);
$this->assertContains('/folder/anotherstorage/foo.png', $paths);
$folderView = new View('/folder');
$results = $folderView->search('bar');
$this->assertEquals(2, count($results));
$paths = [];
foreach ($results as $result) {
$paths[] = $result['path'];
}
$this->assertContains('/anotherstorage/folder/bar.txt', $paths);
$this->assertContains('/bar.txt', $paths);
$results = $folderView->search('foo');
$this->assertEquals(2, count($results));
$paths = [];
foreach ($results as $result) {
$paths[] = $result['path'];
}
$this->assertContains('/anotherstorage/foo.txt', $paths);
$this->assertContains('/anotherstorage/foo.png', $paths);
$this->assertEquals(6, count($rootView->searchByMime('text')));
$this->assertEquals(3, count($folderView->searchByMime('text')));
}
/**
* @medium
*/
public function testWatcher() {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$storage1->getWatcher()->setPolicy(Watcher::CHECK_ALWAYS);
$rootView = new View('');
$cachedData = $rootView->getFileInfo('foo.txt');
$this->assertEquals(16, $cachedData['size']);
$rootView->putFileInfo('foo.txt', ['storage_mtime' => 10]);
$storage1->file_put_contents('foo.txt', 'foo');
clearstatcache();
$cachedData = $rootView->getFileInfo('foo.txt');
$this->assertEquals(3, $cachedData['size']);
}
/**
* @medium
*/
public function testCopyBetweenStorageNoCross() {
$storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
$storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
$this->copyBetweenStorages($storage1, $storage2);
}
/**
* @medium
*/
public function testCopyBetweenStorageCross() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$this->copyBetweenStorages($storage1, $storage2);
}
/**
* @medium
*/
public function testCopyBetweenStorageCrossNonLocal() {
$storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
$storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
$this->copyBetweenStorages($storage1, $storage2);
}
function copyBetweenStorages($storage1, $storage2) {
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$rootView = new View('');
$rootView->mkdir('substorage/emptyfolder');
$rootView->copy('substorage', 'anotherfolder');
$this->assertTrue($rootView->is_dir('/anotherfolder'));
$this->assertTrue($rootView->is_dir('/substorage'));
$this->assertTrue($rootView->is_dir('/anotherfolder/emptyfolder'));
$this->assertTrue($rootView->is_dir('/substorage/emptyfolder'));
$this->assertTrue($rootView->file_exists('/anotherfolder/foo.txt'));
$this->assertTrue($rootView->file_exists('/anotherfolder/foo.png'));
$this->assertTrue($rootView->file_exists('/anotherfolder/folder/bar.txt'));
$this->assertTrue($rootView->file_exists('/substorage/foo.txt'));
$this->assertTrue($rootView->file_exists('/substorage/foo.png'));
$this->assertTrue($rootView->file_exists('/substorage/folder/bar.txt'));
}
/**
* @medium
*/
public function testMoveBetweenStorageNoCross() {
$storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
$storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
$this->moveBetweenStorages($storage1, $storage2);
}
/**
* @medium
*/
public function testMoveBetweenStorageCross() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$this->moveBetweenStorages($storage1, $storage2);
}
/**
* @medium
*/
public function testMoveBetweenStorageCrossNonLocal() {
$storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
$storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
$this->moveBetweenStorages($storage1, $storage2);
}
function moveBetweenStorages($storage1, $storage2) {
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$rootView = new View('');
$rootView->rename('foo.txt', 'substorage/folder/foo.txt');
$this->assertFalse($rootView->file_exists('foo.txt'));
$this->assertTrue($rootView->file_exists('substorage/folder/foo.txt'));
$rootView->rename('substorage/folder', 'anotherfolder');
$this->assertFalse($rootView->is_dir('substorage/folder'));
$this->assertTrue($rootView->file_exists('anotherfolder/foo.txt'));
$this->assertTrue($rootView->file_exists('anotherfolder/bar.txt'));
}
/**
* @medium
*/
public function testUnlink() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$rootView = new View('');
$rootView->file_put_contents('/foo.txt', 'asd');
$rootView->file_put_contents('/substorage/bar.txt', 'asd');
$this->assertTrue($rootView->file_exists('foo.txt'));
$this->assertTrue($rootView->file_exists('substorage/bar.txt'));
$this->assertTrue($rootView->unlink('foo.txt'));
$this->assertTrue($rootView->unlink('substorage/bar.txt'));
$this->assertFalse($rootView->file_exists('foo.txt'));
$this->assertFalse($rootView->file_exists('substorage/bar.txt'));
}
/**
* @medium
*/
public function testUnlinkRootMustFail() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], '/substorage');
$rootView = new View('');
$rootView->file_put_contents('/foo.txt', 'asd');
$rootView->file_put_contents('/substorage/bar.txt', 'asd');
$this->assertFalse($rootView->unlink(''));
$this->assertFalse($rootView->unlink('/'));
$this->assertFalse($rootView->unlink('substorage'));
$this->assertFalse($rootView->unlink('/substorage'));
}
/**
* @medium
*/
public function testTouch() {
$storage = $this->getTestStorage(true, '\Test\Files\TemporaryNoTouch');
Filesystem::mount($storage, [], '/');
$rootView = new View('');
$oldCachedData = $rootView->getFileInfo('foo.txt');
$rootView->touch('foo.txt', 500);
$cachedData = $rootView->getFileInfo('foo.txt');
$this->assertEquals(500, $cachedData['mtime']);
$this->assertEquals($oldCachedData['storage_mtime'], $cachedData['storage_mtime']);
$rootView->putFileInfo('foo.txt', ['storage_mtime' => 1000]); //make sure the watcher detects the change
$rootView->file_put_contents('foo.txt', 'asd');
$cachedData = $rootView->getFileInfo('foo.txt');
$this->assertGreaterThanOrEqual($oldCachedData['mtime'], $cachedData['mtime']);
$this->assertEquals($cachedData['storage_mtime'], $cachedData['mtime']);
}
/**
* @medium
*/
public function testViewHooks() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], $defaultRoot . '/substorage');
\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
$rootView = new View('');
$subView = new View($defaultRoot . '/substorage');
$this->hookPath = null;
$rootView->file_put_contents('/foo.txt', 'asd');
$this->assertNull($this->hookPath);
$subView->file_put_contents('/foo.txt', 'asd');
$this->assertEquals('/substorage/foo.txt', $this->hookPath);
}
private $hookPath;
public function dummyHook($params) {
$this->hookPath = $params['path'];
}
public function testSearchNotOutsideView() {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$storage1->rename('folder', 'foo');
$scanner = $storage1->getScanner();
$scanner->scan('');
$view = new View('/foo');
$result = $view->search('.txt');
$this->assertCount(1, $result);
}
/**
* @param bool $scan
* @param string $class
* @return \OC\Files\Storage\Storage
*/
private function getTestStorage($scan = true, $class = '\OC\Files\Storage\Temporary') {
/**
* @var \OC\Files\Storage\Storage $storage
*/
$storage = new $class([]);
$textData = "dummy file data\n";
$imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo.png');
$storage->mkdir('folder');
$storage->file_put_contents('foo.txt', $textData);
$storage->file_put_contents('foo.png', $imgData);
$storage->file_put_contents('folder/bar.txt', $textData);
if ($scan) {
$scanner = $storage->getScanner();
$scanner->scan('');
}
$this->storages[] = $storage;
return $storage;
}
/**
* @medium
*/
public function testViewHooksIfRootStartsTheSame() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], $defaultRoot . '_substorage');
\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
$subView = new View($defaultRoot . '_substorage');
$this->hookPath = null;
$subView->file_put_contents('/foo.txt', 'asd');
$this->assertNull($this->hookPath);
}
private $hookWritePath;
private $hookCreatePath;
private $hookUpdatePath;
public function dummyHookWrite($params) {
$this->hookWritePath = $params['path'];
}
public function dummyHookUpdate($params) {
$this->hookUpdatePath = $params['path'];
}
public function dummyHookCreate($params) {
$this->hookCreatePath = $params['path'];
}
public function testEditNoCreateHook() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
$defaultRoot = Filesystem::getRoot();
Filesystem::mount($storage1, [], '/');
Filesystem::mount($storage2, [], $defaultRoot);
\OC_Hook::connect('OC_Filesystem', 'post_create', $this, 'dummyHookCreate');
\OC_Hook::connect('OC_Filesystem', 'post_update', $this, 'dummyHookUpdate');
\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHookWrite');
$view = new View($defaultRoot);
$this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;
$view->file_put_contents('/asd.txt', 'foo');
$this->assertEquals('/asd.txt', $this->hookCreatePath);
$this->assertNull($this->hookUpdatePath);
$this->assertEquals('/asd.txt', $this->hookWritePath);
$this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;
$view->file_put_contents('/asd.txt', 'foo');
$this->assertNull($this->hookCreatePath);
$this->assertEquals('/asd.txt', $this->hookUpdatePath);
$this->assertEquals('/asd.txt', $this->hookWritePath);
\OC_Hook::clear('OC_Filesystem', 'post_create');
\OC_Hook::clear('OC_Filesystem', 'post_update');
\OC_Hook::clear('OC_Filesystem', 'post_write');
}
/**
* @dataProvider resolvePathTestProvider
*/
public function testResolvePath($expected, $pathToTest) {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
$view = new View('');
$result = $view->resolvePath($pathToTest);
$this->assertEquals($expected, $result[1]);
$exists = $view->file_exists($pathToTest);
$this->assertTrue($exists);
$exists = $view->file_exists($result[1]);
$this->assertTrue($exists);
}
function resolvePathTestProvider() {
return [
['foo.txt', 'foo.txt'],
['foo.txt', '/foo.txt'],
['folder', 'folder'],
['folder', '/folder'],
['folder', 'folder/'],
['folder', '/folder/'],
['folder/bar.txt', 'folder/bar.txt'],
['folder/bar.txt', '/folder/bar.txt'],
['', ''],
['', '/'],
];
}
public function testUTF8Names() {
$names = ['虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'];
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$rootView = new View('');
foreach ($names as $name) {
$rootView->file_put_contents('/' . $name, 'dummy content');
}
$list = $rootView->getDirectoryContent('/');
$this->assertCount(count($names), $list);
foreach ($list as $item) {
$this->assertContains($item['name'], $names);
}
$cache = $storage->getCache();
$scanner = $storage->getScanner();
$scanner->scan('');
$list = $cache->getFolderContents('');
$this->assertCount(count($names), $list);
foreach ($list as $item) {
$this->assertContains($item['name'], $names);
}
}
public function xtestLongPath() {
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$rootView = new View('');
$longPath = '';
$ds = DIRECTORY_SEPARATOR;
/*
* 4096 is the maximum path length in file_cache.path in *nix
*/
$folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
$tmpdirLength = strlen(\OC::$server->getTempManager()->getTemporaryFolder());
$depth = ((4000 - $tmpdirLength) / 57);
foreach (range(0, $depth - 1) as $i) {
$longPath .= $ds . $folderName;
$result = $rootView->mkdir($longPath);
$this->assertTrue($result, "mkdir failed on $i - path length: " . strlen($longPath));
$result = $rootView->file_put_contents($longPath . "{$ds}test.txt", 'lorem');
$this->assertEquals(5, $result, "file_put_contents failed on $i");
$this->assertTrue($rootView->file_exists($longPath));
$this->assertTrue($rootView->file_exists($longPath . "{$ds}test.txt"));
}
$cache = $storage->getCache();
$scanner = $storage->getScanner();
$scanner->scan('');
$longPath = $folderName;
foreach (range(0, $depth - 1) as $i) {
$cachedFolder = $cache->get($longPath);
$this->assertTrue(is_array($cachedFolder), "No cache entry for folder at $i");
$this->assertEquals($folderName, $cachedFolder['name'], "Wrong cache entry for folder at $i");
$cachedFile = $cache->get($longPath . '/test.txt');
$this->assertTrue(is_array($cachedFile), "No cache entry for file at $i");
$this->assertEquals('test.txt', $cachedFile['name'], "Wrong cache entry for file at $i");
$longPath .= $ds . $folderName;
}
}
public function testTouchNotSupported() {
$storage = new TemporaryNoTouch([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
$past = time() - 100;
$storage->file_put_contents('test', 'foobar');
$scanner->scan('');
$view = new View('');
$info = $view->getFileInfo('/test/test');
$view->touch('/test/test', $past);
$scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG);
$info2 = $view->getFileInfo('/test/test');
$this->assertSame($info['etag'], $info2['etag']);
}
public function testWatcherEtagCrossStorage() {
$storage1 = new Temporary([]);
$storage2 = new Temporary([]);
$scanner1 = $storage1->getScanner();
$scanner2 = $storage2->getScanner();
$storage1->mkdir('sub');
Filesystem::mount($storage1, [], '/test/');
Filesystem::mount($storage2, [], '/test/sub/storage');
$past = time() - 100;
$storage2->file_put_contents('test.txt', 'foobar');
$scanner1->scan('');
$scanner2->scan('');
$view = new View('');
$storage2->getWatcher('')->setPolicy(Watcher::CHECK_ALWAYS);
$oldFileInfo = $view->getFileInfo('/test/sub/storage/test.txt');
$oldFolderInfo = $view->getFileInfo('/test');
$storage2->getCache()->update($oldFileInfo->getId(), [
'storage_mtime' => $past
]);
$view->getFileInfo('/test/sub/storage/test.txt');
$newFolderInfo = $view->getFileInfo('/test');
$this->assertNotEquals($newFolderInfo->getEtag(), $oldFolderInfo->getEtag());
}
/**
* @dataProvider absolutePathProvider
*/
public function testGetAbsolutePath($expectedPath, $relativePath) {
$view = new View('/files');
$this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
}
public function testPartFileInfo() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
$storage->file_put_contents('test.part', 'foobar');
$scanner->scan('');
$view = new View('/test');
$info = $view->getFileInfo('test.part');
$this->assertInstanceOf('\OCP\Files\FileInfo', $info);
$this->assertNull($info->getId());
$this->assertEquals(6, $info->getSize());
}
function absolutePathProvider() {
return [
['/files/', ''],
['/files/0', '0'],
['/files/false', 'false'],
['/files/true', 'true'],
['/files/', '/'],
['/files/test', 'test'],
['/files/test', '/test'],
];
}
/**
* @dataProvider chrootRelativePathProvider
*/
function testChrootGetRelativePath($root, $absolutePath, $expectedPath) {
$view = new View('/files');
$view->chroot($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
}
public function chrootRelativePathProvider() {
return $this->relativePathProvider('/');
}
/**
* @dataProvider initRelativePathProvider
*/
public function testInitGetRelativePath($root, $absolutePath, $expectedPath) {
$view = new View($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
}
public function initRelativePathProvider() {
return $this->relativePathProvider(null);
}
public function relativePathProvider($missingRootExpectedPath) {
return [
// No root - returns the path
['', '/files', '/files'],
['', '/files/', '/files/'],
// Root equals path - /
['/files/', '/files/', '/'],
['/files/', '/files', '/'],
['/files', '/files/', '/'],
['/files', '/files', '/'],
// False negatives: chroot fixes those by adding the leading slash.
// But setting them up with this root (instead of chroot($root))
// will fail them, although they should be the same.
// TODO init should be fixed, so it also adds the leading slash
['files/', '/files/', $missingRootExpectedPath],
['files', '/files/', $missingRootExpectedPath],
['files/', '/files', $missingRootExpectedPath],
['files', '/files', $missingRootExpectedPath],
// False negatives: Paths provided to the method should have a leading slash
// TODO input should be checked to have a leading slash
['/files/', 'files/', null],
['/files', 'files/', null],
['/files/', 'files', null],
['/files', 'files', null],
// with trailing slashes
['/files/', '/files/0', '0'],
['/files/', '/files/false', 'false'],
['/files/', '/files/true', 'true'],
['/files/', '/files/test', 'test'],
['/files/', '/files/test/foo', 'test/foo'],
// without trailing slashes
// TODO false expectation: Should match "with trailing slashes"
['/files', '/files/0', '/0'],
['/files', '/files/false', '/false'],
['/files', '/files/true', '/true'],
['/files', '/files/test', '/test'],
['/files', '/files/test/foo', '/test/foo'],
// leading slashes
['/files/', '/files_trashbin/', null],
['/files', '/files_trashbin/', null],
['/files/', '/files_trashbin', null],
['/files', '/files_trashbin', null],
// no leading slashes
['files/', 'files_trashbin/', null],
['files', 'files_trashbin/', null],
['files/', 'files_trashbin', null],
['files', 'files_trashbin', null],
// mixed leading slashes
['files/', '/files_trashbin/', null],
['/files/', 'files_trashbin/', null],
['files', '/files_trashbin/', null],
['/files', 'files_trashbin/', null],
['files/', '/files_trashbin', null],
['/files/', 'files_trashbin', null],
['files', '/files_trashbin', null],
['/files', 'files_trashbin', null],
['files', 'files_trashbin/test', null],
['/files', '/files_trashbin/test', null],
['/files', 'files_trashbin/test', null],
];
}
public function testFileView() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
Filesystem::mount($storage, [], '/test/');
$scanner->scan('');
$view = new View('/test/foo.txt');
$this->assertEquals('bar', $view->file_get_contents(''));
$fh = tmpfile();
fwrite($fh, 'foo');
rewind($fh);
$view->file_put_contents('', $fh);
$this->assertEquals('foo', $view->file_get_contents(''));
}
/**
* @dataProvider tooLongPathDataProvider
* @expectedException \OCP\Files\InvalidPathException
*/
public function testTooLongPath($operation, $param0 = null) {
$longPath = '';
// 4000 is the maximum path length in file_cache.path
$folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
$depth = (4000 / 57);
foreach (range(0, $depth + 1) as $i) {
$longPath .= '/' . $folderName;
}
$storage = new Temporary([]);
$this->tempStorage = $storage; // for later hard cleanup
Filesystem::mount($storage, [], '/');
$rootView = new View('');
if ($param0 === '@0') {
$param0 = $longPath;
}
if ($operation === 'hash') {
$param0 = $longPath;
$longPath = 'md5';
}
call_user_func([$rootView, $operation], $longPath, $param0);
}
public function tooLongPathDataProvider() {
return [
['getAbsolutePath'],
['getRelativePath'],
['getMountPoint'],
['resolvePath'],
['getLocalFile'],
['getLocalFolder'],
['mkdir'],
['rmdir'],
['opendir'],
['is_dir'],
['is_file'],
['stat'],
['filetype'],
['filesize'],
['readfile'],
['isCreatable'],
['isReadable'],
['isUpdatable'],
['isDeletable'],
['isSharable'],
['file_exists'],
['filemtime'],
['touch'],
['file_get_contents'],
['unlink'],
['deleteAll'],
['toTmpFile'],
['getMimeType'],
['free_space'],
['getFileInfo'],
['getDirectoryContent'],
['getOwner'],
['getETag'],
['file_put_contents', 'ipsum'],
['rename', '@0'],
['copy', '@0'],
['fopen', 'r'],
['fromTmpFile', '@0'],
['hash'],
['hasUpdated', 0],
['putFileInfo', []],
];
}
public function testRenameCrossStoragePreserveMtime() {
$storage1 = new Temporary([]);
$storage2 = new Temporary([]);
$scanner1 = $storage1->getScanner();
$scanner2 = $storage2->getScanner();
$storage1->mkdir('sub');
$storage1->mkdir('foo');
$storage1->file_put_contents('foo.txt', 'asd');
$storage1->file_put_contents('foo/bar.txt', 'asd');
Filesystem::mount($storage1, [], '/test/');
Filesystem::mount($storage2, [], '/test/sub/storage');
$view = new View('');
$time = time() - 200;
$view->touch('/test/foo.txt', $time);
$view->touch('/test/foo', $time);
$view->touch('/test/foo/bar.txt', $time);
$view->rename('/test/foo.txt', '/test/sub/storage/foo.txt');
$this->assertEquals($time, $view->filemtime('/test/sub/storage/foo.txt'));
$view->rename('/test/foo', '/test/sub/storage/foo');
$this->assertEquals($time, $view->filemtime('/test/sub/storage/foo/bar.txt'));
}
public function testRenameFailDeleteTargetKeepSource() {
$this->doTestCopyRenameFail('rename');
}
public function testCopyFailDeleteTargetKeepSource() {
$this->doTestCopyRenameFail('copy');
}
private function doTestCopyRenameFail($operation) {
$storage1 = new Temporary([]);
/** @var \PHPUnit_Framework_MockObject_MockObject | Temporary $storage2 */
$storage2 = $this->getMockBuilder('\Test\Files\TemporaryNoCross')
->setConstructorArgs([[]])
->setMethods(['fopen'])
->getMock();
$storage2->expects($this->any())
->method('fopen')
->will($this->returnCallback(function ($path, $mode) use ($storage2) {
/** @var \PHPUnit_Framework_MockObject_MockObject | Temporary $storage2 */
$source = fopen($storage2->getSourcePath($path), $mode);
return \OC\Files\Stream\Quota::wrap($source, 9);
}));
$storage1->mkdir('sub');
$storage1->file_put_contents('foo.txt', '0123456789ABCDEFGH');
$storage1->mkdir('dirtomove');
$storage1->file_put_contents('dirtomove/indir1.txt', '0123456'); // fits
$storage1->file_put_contents('dirtomove/indir2.txt', '0123456789ABCDEFGH'); // doesn't fit
$storage2->file_put_contents('existing.txt', '0123');
$storage1->getScanner()->scan('');
$storage2->getScanner()->scan('');
Filesystem::mount($storage1, [], '/test/');
Filesystem::mount($storage2, [], '/test/sub/storage');
// move file
$view = new View('');
$this->assertTrue($storage1->file_exists('foo.txt'));
$this->assertFalse($storage2->file_exists('foo.txt'));
$this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/foo.txt'));
$this->assertFalse($storage2->file_exists('foo.txt'));
$this->assertFalse($storage2->getCache()->get('foo.txt'));
$this->assertTrue($storage1->file_exists('foo.txt'));
// if target exists, it will be deleted too
$this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/existing.txt'));
$this->assertFalse($storage2->file_exists('existing.txt'));
$this->assertFalse($storage2->getCache()->get('existing.txt'));
$this->assertTrue($storage1->file_exists('foo.txt'));
// move folder
$this->assertFalse($view->$operation('/test/dirtomove/', '/test/sub/storage/dirtomove/'));
// since the move failed, the full source tree is kept
$this->assertTrue($storage1->file_exists('dirtomove/indir1.txt'));
$this->assertTrue($storage1->file_exists('dirtomove/indir2.txt'));
// second file not moved/copied
$this->assertFalse($storage2->file_exists('dirtomove/indir2.txt'));
$this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
}
public function testDeleteFailKeepCache() {
/**
* @var \PHPUnit_Framework_MockObject_MockObject | Temporary $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setConstructorArgs([[]])
->setMethods(['unlink'])
->getMock();
$storage->expects($this->once())
->method('unlink')
->will($this->returnValue(false));
$scanner = $storage->getScanner();
$cache = $storage->getCache();
$storage->file_put_contents('foo.txt', 'asd');
$scanner->scan('');
Filesystem::mount($storage, [], '/test/');
$view = new View('/test');
$this->assertFalse($view->unlink('foo.txt'));
$this->assertTrue($cache->inCache('foo.txt'));
}
function directoryTraversalProvider() {
return [
['../test/'],
['..\\test\\my/../folder'],
['/test/my/../foo\\'],
];
}
/**
* @dataProvider directoryTraversalProvider
* @expectedException \Exception
* @param string $root
*/
public function testConstructDirectoryTraversalException($root) {
new View($root);
}
public function testRenameOverWrite() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->mkdir('sub');
$storage->mkdir('foo');
$storage->file_put_contents('foo.txt', 'asd');
$storage->file_put_contents('foo/bar.txt', 'asd');
$scanner->scan('');
Filesystem::mount($storage, [], '/test/');
$view = new View('');
$this->assertTrue($view->rename('/test/foo.txt', '/test/foo/bar.txt'));
}
public function testSetMountOptionsInStorage() {
$mount = new MountPoint('\OC\Files\Storage\Temporary', '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
Filesystem::getMountManager()->addMount($mount);
/** @var \OC\Files\Storage\Common $storage */
$storage = $mount->getStorage();
$this->assertEquals($storage->getMountOption('foo'), 'bar');
}
public function testSetMountOptionsWatcherPolicy() {
$mount = new MountPoint('\OC\Files\Storage\Temporary', '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
Filesystem::getMountManager()->addMount($mount);
/** @var \OC\Files\Storage\Common $storage */
$storage = $mount->getStorage();
$watcher = $storage->getWatcher();
$this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
}
public function testGetAbsolutePathOnNull() {
$view = new View();
$this->assertNull($view->getAbsolutePath(null));
}
public function testGetRelativePathOnNull() {
$view = new View();
$this->assertNull($view->getRelativePath(null));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testNullAsRoot() {
new View(null);
}
/**
* e.g. reading from a folder that's being renamed
*
* @expectedException \OCP\Lock\LockedException
*
* @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
public function testReadFromWriteLockedPath($rootPath, $pathPrefix) {
$rootPath = str_replace('{folder}', 'files', $rootPath);
$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
$view = new View($rootPath);
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
$view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED);
}
/**
* Reading from a files_encryption folder that's being renamed
*
* @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix) {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
$view = new View($rootPath);
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED));
}
/**
* e.g. writing a file that's being downloaded
*
* @expectedException \OCP\Lock\LockedException
*
* @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
public function testWriteToReadLockedFile($rootPath, $pathPrefix) {
$rootPath = str_replace('{folder}', 'files', $rootPath);
$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
$view = new View($rootPath);
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
$view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE);
}
/**
* Writing a file that's being downloaded
*
* @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
public function testWriteToReadUnlockableFile($rootPath, $pathPrefix) {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
$view = new View($rootPath);
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
}
/**
* Test that locks are on mount point paths instead of mount root
*/
public function testLockLocalMountPointPathInsteadOfStorageRoot() {
$lockingProvider = \OC::$server->getLockingProvider();
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$mountedStorage = new Temporary([]);
Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
$this->assertTrue(
$view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, true),
'Can lock mount point'
);
// no exception here because storage root was not locked
$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
$thrown = false;
try {
$storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
} catch (\OCP\Lock\LockedException $e) {
$thrown = true;
}
$this->assertTrue($thrown, 'Mount point path was locked on root storage');
$lockingProvider->releaseAll();
}
/**
* Test that locks are on mount point paths and also mount root when requested
*/
public function testLockStorageRootButNotLocalMountPoint() {
$lockingProvider = \OC::$server->getLockingProvider();
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$mountedStorage = new Temporary([]);
Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
$this->assertTrue(
$view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, false),
'Can lock mount point'
);
$thrown = false;
try {
$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
} catch (\OCP\Lock\LockedException $e) {
$thrown = true;
}
$this->assertTrue($thrown, 'Mount point storage root was locked on original storage');
// local mount point was not locked
$storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
$lockingProvider->releaseAll();
}
/**
* Test that locks are on mount point paths and also mount root when requested
*/
public function testLockMountPointPathFailReleasesBoth() {
$lockingProvider = \OC::$server->getLockingProvider();
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$mountedStorage = new Temporary([]);
Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint.txt');
// this would happen if someone is writing on the mount point
$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
$thrown = false;
try {
// this actually acquires two locks, one on the mount point and one on the storage root,
// but the one on the storage root will fail
$view->lockFile('/mountpoint.txt', ILockingProvider::LOCK_SHARED);
} catch (\OCP\Lock\LockedException $e) {
$thrown = true;
}
$this->assertTrue($thrown, 'Cannot acquire shared lock because storage root is already locked');
// from here we expect that the lock on the local mount point was released properly
// so acquiring an exclusive lock will succeed
$storage->acquireLock('/testuser/files/mountpoint.txt', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
$lockingProvider->releaseAll();
}
public function dataLockPaths() {
return [
['/testuser/{folder}', ''],
['/testuser', '/{folder}'],
['', '/testuser/{folder}'],
];
}
public function pathRelativeToFilesProvider() {
return [
['admin/files', ''],
['admin/files/x', 'x'],
['/admin/files', ''],
['/admin/files/sub', 'sub'],
['/admin/files/sub/', 'sub'],
['/admin/files/sub/sub2', 'sub/sub2'],
['//admin//files/sub//sub2', 'sub/sub2'],
];
}
/**
* @dataProvider pathRelativeToFilesProvider
*/
public function testGetPathRelativeToFiles($path, $expectedPath) {
$view = new View();
$this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
}
public function pathRelativeToFilesProviderExceptionCases() {
return [
[''],
['x'],
['files'],
['/files'],
['/admin/files_versions/abc'],
];
}
/**
* @dataProvider pathRelativeToFilesProviderExceptionCases
* @expectedException \InvalidArgumentException
*/
public function testGetPathRelativeToFilesWithInvalidArgument($path) {
$view = new View();
$view->getPathRelativeToFiles($path);
}
public function testChangeLock() {
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
$view->lockFile('/test/sub', ILockingProvider::LOCK_SHARED);
$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
$view->changeLock('//test/sub', ILockingProvider::LOCK_EXCLUSIVE);
$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
$view->changeLock('test/sub', ILockingProvider::LOCK_SHARED);
$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
$view->unlockFile('/test/sub/', ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
}
public function hookPathProvider() {
return [
['/foo/files', '/foo', true],
['/foo/files/bar', '/foo', true],
['/foo', '/foo', false],
['/foo', '/files/foo', true],
['/foo', 'filesfoo', false],
['', '/foo/files', true],
['', '/foo/files/bar.txt', true]
];
}
/**
* @dataProvider hookPathProvider
* @param $root
* @param $path
* @param $shouldEmit
*/
public function testHookPaths($root, $path, $shouldEmit) {
$filesystemReflection = new \ReflectionClass('\OC\Files\Filesystem');
$defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
$defaultRootValue->setAccessible(true);
$oldRoot = $defaultRootValue->getValue();
$defaultView = new View('/foo/files');
$defaultRootValue->setValue($defaultView);
$view = new View($root);
$result = $this->invokePrivate($view, 'shouldEmitHooks', [$path]);
$defaultRootValue->setValue($oldRoot);
$this->assertEquals($shouldEmit, $result);
}
/**
* Create test movable mount points
*
* @param array $mountPoints array of mount point locations
* @param bool $isTargetAllowed value to return for the isTargetAllowed call
* @return array array of MountPoint objects
*/
private function createTestMovableMountPoints($mountPoints, $isTargetAllowed = true) {
$mounts = [];
foreach ($mountPoints as $mountPoint) {
$storage = new Temporary();
$testMount = $this->getMockBuilder('\Test\TestMoveableMountPoint')
->setMethods(['moveMount', 'isTargetAllowed'])
->setConstructorArgs([$storage, $mountPoint])
->getMock();
$testMount->expects($this->any())
->method('isTargetAllowed')
->will($this->returnValue($isTargetAllowed));
$mounts[] = $testMount;
}
$mountProvider = $this->createMock('\OCP\Files\Config\IMountProvider');
$mountProvider->expects($this->any())
->method('getMountsForUser')
->will($this->returnValue($mounts));
$mountProviderCollection = \OC::$server->getMountProviderCollection();
$mountProviderCollection->registerProvider($mountProvider);
return $mounts;
}
/**
* Test mount point move
*/
public function testMountPointMove() {
$this->loginAsUser($this->user);
list($mount1, $mount2) = $this->createTestMovableMountPoints([
$this->user . '/files/mount1',
$this->user . '/files/mount2',
]);
$mount1->expects($this->once())
->method('moveMount')
->will($this->returnValue(true));
$mount2->expects($this->once())
->method('moveMount')
->will($this->returnValue(true));
$view = new View('/' . $this->user . '/files/');
$view->mkdir('sub');
$this->assertTrue($view->rename('mount1', 'renamed_mount'), 'Can rename mount point');
$this->assertTrue($view->rename('mount2', 'sub/moved_mount'), 'Can move a mount point into a subdirectory');
}
/**
* Test that moving a mount point into another is forbidden
*/
public function testMoveMountPointIntoAnother() {
$this->loginAsUser($this->user);
list($mount1, $mount2) = $this->createTestMovableMountPoints([
$this->user . '/files/mount1',
$this->user . '/files/mount2',
]);
$mount1->expects($this->never())
->method('moveMount');
$mount2->expects($this->never())
->method('moveMount');
$view = new View('/' . $this->user . '/files/');
$this->assertFalse($view->rename('mount1', 'mount2'), 'Cannot overwrite another mount point');
$this->assertFalse($view->rename('mount1', 'mount2/sub'), 'Cannot move a mount point into another');
}
/**
* Test that moving a mount point that says it's not allowed will fail
*/
public function testMoveMountPointNotAllowed() {
$this->loginAsUser($this->user);
$userFolder = \OC::$server->getUserFolder($this->user);
list($mount1) = $this->createTestMovableMountPoints([
$this->user . '/files/mount1',
], false);
$mount1->expects($this->never())
->method('moveMount');
$view = new View('/' . $this->user . '/files/');
$view->mkdir('somedir');
$fileId = $view->getFileInfo('somedir')->getId();
$this->assertFalse($view->rename('mount1', 'shareddir'), 'Cannot overwrite shared folder');
}
public function basicOperationProviderForLocks() {
return [
// --- write hook ----
// [
// 'touch',
// ['touch-create.txt'],
// 'touch-create.txt',
// 'create',
// ILockingProvider::LOCK_SHARED,
// ILockingProvider::LOCK_EXCLUSIVE,
// ILockingProvider::LOCK_SHARED,
// ],
[
'fopen',
['test-write.txt', 'w'],
'test-write.txt',
'write',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_EXCLUSIVE,
null,
// exclusive lock stays until fclose
ILockingProvider::LOCK_EXCLUSIVE,
],
// [
// 'mkdir',
// ['newdir'],
// 'newdir',
// 'write',
// ILockingProvider::LOCK_SHARED,
// ILockingProvider::LOCK_EXCLUSIVE,
// ILockingProvider::LOCK_SHARED,
// ],
// [
// 'file_put_contents',
// ['file_put_contents.txt', 'blah'],
// 'file_put_contents.txt',
// 'write',
// ILockingProvider::LOCK_SHARED,
// ILockingProvider::LOCK_EXCLUSIVE,
// ILockingProvider::LOCK_SHARED,
// ],
// ---- delete hook ----
[
'rmdir',
['dir'],
'dir',
'delete',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_EXCLUSIVE,
ILockingProvider::LOCK_SHARED,
],
[
'unlink',
['test.txt'],
'test.txt',
'delete',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_EXCLUSIVE,
ILockingProvider::LOCK_SHARED,
],
// ---- read hook (no post hooks) ----
[
'file_get_contents',
['test.txt'],
'test.txt',
'read',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_SHARED,
null,
],
[
'fopen',
['test.txt', 'r'],
'test.txt',
'read',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_SHARED,
null,
],
[
'opendir',
['dir'],
'dir',
'read',
ILockingProvider::LOCK_SHARED,
ILockingProvider::LOCK_SHARED,
null,
],
// ---- no lock, touch hook ---
['touch', ['test.txt'], 'test.txt', 'touch', null, null, null],
// ---- no hooks, no locks ---
['is_dir', ['dir'], 'dir', null],
['is_file', ['dir'], 'dir', null],
['stat', ['dir'], 'dir', null],
['filetype', ['dir'], 'dir', null],
['filesize', ['dir'], 'dir', null],
['isCreatable', ['dir'], 'dir', null],
['isReadable', ['dir'], 'dir', null],
['isUpdatable', ['dir'], 'dir', null],
['isDeletable', ['dir'], 'dir', null],
['isSharable', ['dir'], 'dir', null],
['file_exists', ['dir'], 'dir', null],
['filemtime', ['dir'], 'dir', null],
];
}
/**
* Test whether locks are set before and after the operation
*
* @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $lockedPath path of the locked item to check
* @param string $hookType hook type
* @param int $expectedLockBefore expected lock during pre hooks
* @param int $expectedLockDuring expected lock during operation
* @param int $expectedLockAfter expected lock during post hooks
* @param int $expectedStrayLock expected lock after returning, should
* be null (unlock) for most operations
*/
public function testLockBasicOperation(
$operation,
$operationArgs,
$lockedPath,
$hookType,
$expectedLockBefore = ILockingProvider::LOCK_SHARED,
$expectedLockDuring = ILockingProvider::LOCK_SHARED,
$expectedLockAfter = ILockingProvider::LOCK_SHARED,
$expectedStrayLock = null
) {
$view = new View('/' . $this->user . '/files/');
/** @var Temporary | \PHPUnit_Framework_MockObject_MockObject $storage */
$storage = $this->getMockBuilder(Temporary::class)
->setMethods([$operation])
->getMock();
Filesystem::mount($storage, [], $this->user . '/');
// work directly on disk because mkdir might be mocked
$realPath = $storage->getSourcePath('');
mkdir($realPath . '/files');
mkdir($realPath . '/files/dir');
file_put_contents($realPath . '/files/test.txt', 'blah');
$storage->getScanner()->scan('files');
$storage->expects($this->once())
->method($operation)
->will($this->returnCallback(
function () use ($view, $lockedPath, &$lockTypeDuring) {
$lockTypeDuring = $this->getFileLockType($view, $lockedPath);
return true;
}
));
$this->assertNull($this->getFileLockType($view, $lockedPath), 'File not locked before operation');
$this->connectMockHooks($hookType, $view, $lockedPath, $lockTypePre, $lockTypePost);
// do operation
call_user_func_array([$view, $operation], $operationArgs);
if ($hookType !== null) {
$this->assertEquals($expectedLockBefore, $lockTypePre, 'File locked properly during pre-hook');
$this->assertEquals($expectedLockAfter, $lockTypePost, 'File locked properly during post-hook');
$this->assertEquals($expectedLockDuring, $lockTypeDuring, 'File locked properly during operation');
} else {
$this->assertNull($lockTypeDuring, 'File not locked during operation');
}
$this->assertEquals($expectedStrayLock, $this->getFileLockType($view, $lockedPath));
}
/**
* Test locks for file_put_content with stream.
* This code path uses $storage->fopen instead
*/
public function testLockFilePutContentWithStream() {
$view = new View('/' . $this->user . '/files/');
$path = 'test_file_put_contents.txt';
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods(['fopen'])
->getMock();
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$storage->expects($this->once())
->method('fopen')
->will($this->returnCallback(
function () use ($view, $path, &$lockTypeDuring) {
$lockTypeDuring = $this->getFileLockType($view, $path);
return fopen('php://temp', 'r+');
}
));
$this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
$this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
// do operation
$view->file_put_contents($path, fopen('php://temp', 'r+'));
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePost, 'File locked properly during post-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
$this->assertNull($this->getFileLockType($view, $path));
}
/**
* Test locks for fopen with fclose at the end
*/
public function testLockFopen() {
$view = new View('/' . $this->user . '/files/');
$path = 'test_file_put_contents.txt';
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods(['fopen'])
->getMock();
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$storage->expects($this->once())
->method('fopen')
->will($this->returnCallback(
function () use ($view, $path, &$lockTypeDuring) {
$lockTypeDuring = $this->getFileLockType($view, $path);
return fopen('php://temp', 'r+');
}
));
$this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
$this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
// do operation
$res = $view->fopen($path, 'w');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
$this->assertNull($lockTypePost, 'No post hook, no lock check possible');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File still locked after fopen');
fclose($res);
$this->assertNull($this->getFileLockType($view, $path), 'File unlocked after fclose');
}
/**
* Test locks for fopen with fclose at the end
*
* @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
*/
public function testLockBasicOperationUnlocksAfterException(
$operation,
$operationArgs,
$path
) {
$view = new View('/' . $this->user . '/files/');
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods([$operation])
->getMock();
Filesystem::mount($storage, [], $this->user . '/');
// work directly on disk because mkdir might be mocked
$realPath = $storage->getSourcePath('');
mkdir($realPath . '/files');
mkdir($realPath . '/files/dir');
file_put_contents($realPath . '/files/test.txt', 'blah');
$storage->getScanner()->scan('files');
$storage->expects($this->once())
->method($operation)
->will($this->returnCallback(
function () {
throw new \Exception('Simulated exception');
}
));
$thrown = false;
try {
call_user_func_array([$view, $operation], $operationArgs);
} catch (\Exception $e) {
$thrown = true;
$this->assertEquals('Simulated exception', $e->getMessage());
}
$this->assertTrue($thrown, 'Exception was rethrown');
$this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
}
/**
* Test locks for fopen with fclose at the end
*
* @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
* @param string $hookType hook type
*/
public function testLockBasicOperationUnlocksAfterCancelledHook(
$operation,
$operationArgs,
$path,
$hookType
) {
$view = new View('/' . $this->user . '/files/');
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods([$operation])
->getMock();
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
Util::connectHook(
Filesystem::CLASSNAME,
$hookType,
'\Test\HookHelper',
'cancellingCallback'
);
call_user_func_array([$view, $operation], $operationArgs);
$this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
}
public function lockFileRenameOrCopyDataProvider() {
return [
['rename', ILockingProvider::LOCK_EXCLUSIVE],
['copy', ILockingProvider::LOCK_SHARED],
];
}
/**
* Test locks for rename or copy operation
*
* @dataProvider lockFileRenameOrCopyDataProvider
*
* @param string $operation operation to be done on the view
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
public function testLockFileRename($operation, $expectedLockTypeSourceDuring) {
$view = new View('/' . $this->user . '/files/');
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods([$operation, 'filemtime'])
->getMock();
$storage->expects($this->any())
->method('filemtime')
->will($this->returnValue(123456789));
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
$storage->expects($this->once())
->method($operation)
->will($this->returnCallback(
function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
return true;
}
));
$this->connectMockHooks($operation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
$this->connectMockHooks($operation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
$view->$operation($sourcePath, $targetPath);
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
$this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
}
/**
* simulate a failed copy operation.
* We expect that we catch the exception, free the lock and re-throw it.
*
* @expectedException \Exception
*/
public function testLockFileCopyException() {
$view = new View('/' . $this->user . '/files/');
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods(['copy'])
->getMock();
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
$storage->expects($this->once())
->method('copy')
->will($this->returnCallback(
function () {
throw new \Exception();
}
));
$this->connectMockHooks('copy', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
$this->connectMockHooks('copy', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
try {
$view->copy($sourcePath, $targetPath);
} catch (\Exception $e) {
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
throw $e;
}
}
/**
* Test rename operation: unlock first path when second path was locked
*/
public function testLockFileRenameUnlockOnException() {
$this->loginAsUser('test');
$view = new View('/' . $this->user . '/files/');
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
$view->file_put_contents($sourcePath, 'meh');
// simulate that the target path is already locked
$view->lockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file is locked before operation');
$thrown = false;
try {
$view->rename($sourcePath, $targetPath);
} catch (\OCP\Lock\LockedException $e) {
$thrown = true;
}
$this->assertTrue($thrown, 'LockedException thrown');
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file still locked after operation');
$view->unlockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
}
/**
* Test rename operation: unlock first path when second path was locked
*/
public function testGetOwner() {
$this->loginAsUser('test');
$view = new View('/test/files/');
$path = 'foo.txt';
$view->file_put_contents($path, 'meh');
$this->assertEquals('test', $view->getFileInfo($path)->getOwner()->getUID());
$folderInfo = $view->getDirectoryContent('');
$folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
return $info->getName() === 'foo.txt';
}));
$this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
$subStorage = new Temporary();
Filesystem::mount($subStorage, [], '/test/files/asd');
$folderInfo = $view->getDirectoryContent('');
$folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
return $info->getName() === 'asd';
}));
$this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
}
public function lockFileRenameOrCopyCrossStorageDataProvider() {
return [
['rename', 'moveFromStorage', ILockingProvider::LOCK_EXCLUSIVE],
['copy', 'copyFromStorage', ILockingProvider::LOCK_SHARED],
];
}
/**
* Test locks for rename or copy operation cross-storage
*
* @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
*
* @param string $viewOperation operation to be done on the view
* @param string $storageOperation operation to be mocked on the storage
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring) {
$view = new View('/' . $this->user . '/files/');
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods([$storageOperation])
->getMock();
$storage2 = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->setMethods([$storageOperation, 'filemtime'])
->getMock();
$storage2->expects($this->any())
->method('filemtime')
->will($this->returnValue(123456789));
$sourcePath = 'original.txt';
$targetPath = 'substorage/target.txt';
Filesystem::mount($storage, [], $this->user . '/');
Filesystem::mount($storage2, [], $this->user . '/files/substorage');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
$storage->expects($this->never())
->method($storageOperation);
$storage2->expects($this->once())
->method($storageOperation)
->will($this->returnCallback(
function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
return true;
}
));
$this->connectMockHooks($viewOperation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
$this->connectMockHooks($viewOperation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
$view->$viewOperation($sourcePath, $targetPath);
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
$this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
}
/**
* Test locks when moving a mount point
*/
public function testLockMoveMountPoint() {
$this->loginAsUser('test');
list($mount) = $this->createTestMovableMountPoints([
$this->user . '/files/substorage',
]);
$view = new View('/' . $this->user . '/files/');
$view->mkdir('subdir');
$sourcePath = 'substorage';
$targetPath = 'subdir/substorage_moved';
$mount->expects($this->once())
->method('moveMount')
->will($this->returnCallback(
function ($target) use ($mount, $view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring, &$lockTypeSharedRootDuring) {
$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath, true);
$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath, true);
$lockTypeSharedRootDuring = $this->getFileLockType($view, $sourcePath, false);
$mount->setMountPoint($target);
return true;
}
));
$this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost, true);
$this->connectMockHooks('rename', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost, true);
// in pre-hook, mount point is still on $sourcePath
$this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSharedRootPre, $dummy, false);
// in post-hook, mount point is now on $targetPath
$this->connectMockHooks('rename', $view, $targetPath, $dummy, $lockTypeSharedRootPost, false);
$this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked before operation');
$this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked before operation');
$this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked before operation');
$view->rename($sourcePath, $targetPath);
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source path locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeSourceDuring, 'Source path locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source path locked properly during post-hook');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target path locked properly during pre-hook');
$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target path locked properly during operation');
$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target path locked properly during post-hook');
$this->assertNull($lockTypeSharedRootPre, 'Shared storage root not locked during pre-hook');
$this->assertNull($lockTypeSharedRootDuring, 'Shared storage root not locked during move');
$this->assertNull($lockTypeSharedRootPost, 'Shared storage root not locked during post-hook');
$this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked after operation');
$this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked after operation');
$this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked after operation');
}
/**
* Connect hook callbacks for hook type
*
* @param string $hookType hook type or null for none
* @param View $view view to check the lock on
* @param string $path path for which to check the lock
* @param int $lockTypePre variable to receive lock type that was active in the pre-hook
* @param int $lockTypePost variable to receive lock type that was active in the post-hook
* @param bool $onMountPoint true to check the mount point instead of the
* mounted storage
*/
private function connectMockHooks($hookType, $view, $path, &$lockTypePre, &$lockTypePost, $onMountPoint = false) {
if ($hookType === null) {
return;
}
$eventHandler = $this->getMockBuilder('\stdclass')
->setMethods(['preCallback', 'postCallback'])
->getMock();
$eventHandler->expects($this->any())
->method('preCallback')
->will($this->returnCallback(
function () use ($view, $path, $onMountPoint, &$lockTypePre) {
$lockTypePre = $this->getFileLockType($view, $path, $onMountPoint);
}
));
$eventHandler->expects($this->any())
->method('postCallback')
->will($this->returnCallback(
function () use ($view, $path, $onMountPoint, &$lockTypePost) {
$lockTypePost = $this->getFileLockType($view, $path, $onMountPoint);
}
));
if ($hookType !== null) {
Util::connectHook(
Filesystem::CLASSNAME,
$hookType,
$eventHandler,
'preCallback'
);
Util::connectHook(
Filesystem::CLASSNAME,
'post_' . $hookType,
$eventHandler,
'postCallback'
);
}
}
/**
* Returns the file lock type
*
* @param View $view view
* @param string $path path
* @param bool $onMountPoint true to check the mount point instead of the
* mounted storage
*
* @return int lock type or null if file was not locked
*/
private function getFileLockType(View $view, $path, $onMountPoint = false) {
if ($this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE, $onMountPoint)) {
return ILockingProvider::LOCK_EXCLUSIVE;
} else if ($this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED, $onMountPoint)) {
return ILockingProvider::LOCK_SHARED;
}
return null;
}
public function testRemoveMoveableMountPoint() {
$mountPoint = '/' . $this->user . '/files/mount/';
// Mock the mount point
$mount = $this->getMockBuilder('\Test\TestMoveableMountPoint')
->disableOriginalConstructor()
->getMock();
$mount->expects($this->once())
->method('getMountPoint')
->willReturn($mountPoint);
$mount->expects($this->once())
->method('removeMount')
->willReturn('foo');
$mount->expects($this->any())
->method('getInternalPath')
->willReturn('');
// Register mount
Filesystem::getMountManager()->addMount($mount);
// Listen for events
$eventHandler = $this->getMockBuilder('\stdclass')
->setMethods(['umount', 'post_umount'])
->getMock();
$eventHandler->expects($this->once())
->method('umount')
->with([Filesystem::signal_param_path => '/mount']);
$eventHandler->expects($this->once())
->method('post_umount')
->with([Filesystem::signal_param_path => '/mount']);
Util::connectHook(
Filesystem::CLASSNAME,
'umount',
$eventHandler,
'umount'
);
Util::connectHook(
Filesystem::CLASSNAME,
'post_umount',
$eventHandler,
'post_umount'
);
//Delete the mountpoint
$view = new View('/' . $this->user . '/files');
$this->assertEquals('foo', $view->rmdir('mount'));
}
public function mimeFilterProvider() {
return [
[null, ['test1.txt', 'test2.txt', 'test3.md', 'test4.png']],
['text/plain', ['test1.txt', 'test2.txt']],
['text/markdown', ['test3.md']],
['text', ['test1.txt', 'test2.txt', 'test3.md']],
];
}
/**
* @param string $filter
* @param string[] $expected
* @dataProvider mimeFilterProvider
*/
public function testGetDirectoryContentMimeFilter($filter, $expected) {
$storage1 = new Temporary();
$root = $this->getUniqueID('/');
Filesystem::mount($storage1, [], $root . '/');
$view = new View($root);
$view->file_put_contents('test1.txt', 'asd');
$view->file_put_contents('test2.txt', 'asd');
$view->file_put_contents('test3.md', 'asd');
$view->file_put_contents('test4.png', '');
$content = $view->getDirectoryContent('', $filter);
$files = array_map(function (FileInfo $info) {
return $info->getName();
}, $content);
sort($files);
$this->assertEquals($expected, $files);
}
public function testFilePutContentsClearsChecksum() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$storage->file_put_contents('foo.txt', 'bar');
Filesystem::mount($storage, [], '/test/');
$scanner->scan('');
$view = new View('/test/foo.txt');
$view->putFileInfo('.', ['checksum' => '42']);
$this->assertEquals('bar', $view->file_get_contents(''));
$fh = tmpfile();
fwrite($fh, 'fooo');
rewind($fh);
$view->file_put_contents('', $fh);
$this->assertEquals('fooo', $view->file_get_contents(''));
$data = $view->getFileInfo('.');
$this->assertEquals('', $data->getChecksum());
}
public function testDeleteGhostFile() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$cache = $storage->getCache();
$storage->file_put_contents('foo.txt', 'bar');
Filesystem::mount($storage, [], '/test/');
$scanner->scan('');
$storage->unlink('foo.txt');
$this->assertTrue($cache->inCache('foo.txt'));
$view = new View('/test');
$rootInfo = $view->getFileInfo('');
$this->assertEquals(3, $rootInfo->getSize());
$view->unlink('foo.txt');
$newInfo = $view->getFileInfo('');
$this->assertFalse($cache->inCache('foo.txt'));
$this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
$this->assertEquals(0, $newInfo->getSize());
}
public function testDeleteGhostFolder() {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
$cache = $storage->getCache();
$storage->mkdir('foo');
$storage->file_put_contents('foo/foo.txt', 'bar');
Filesystem::mount($storage, [], '/test/');
$scanner->scan('');
$storage->rmdir('foo');
$this->assertTrue($cache->inCache('foo'));
$this->assertTrue($cache->inCache('foo/foo.txt'));
$view = new View('/test');
$rootInfo = $view->getFileInfo('');
$this->assertEquals(3, $rootInfo->getSize());
$view->rmdir('foo');
$newInfo = $view->getFileInfo('');
$this->assertFalse($cache->inCache('foo'));
$this->assertFalse($cache->inCache('foo/foo.txt'));
$this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
$this->assertEquals(0, $newInfo->getSize());
}
}
|
IljaN/core
|
tests/lib/Files/ViewTest.php
|
PHP
|
agpl-3.0
| 80,800
|
class CreateAddressGroups < ActiveRecord::Migration
def change
create_table :address_groups do |t|
t.string :name
t.timestamps
end
end
end
|
camsys/ridepilot
|
db/migrate/20170625200226_create_address_groups.rb
|
Ruby
|
agpl-3.0
| 164
|
/*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.scheduler.common.job.factories.spi.model.factory;
import org.junit.Assert;
import org.junit.Test;
import org.ow2.proactive.scheduler.common.job.factories.spi.model.exceptions.ConversionException;
import org.ow2.proactive.scheduler.common.job.factories.spi.model.exceptions.ModelSyntaxException;
import org.ow2.proactive.scheduler.common.job.factories.spi.model.exceptions.ValidationException;
/**
* @author ActiveEon Team
* @since 12/10/2018
*/
public class CatalogObjectParserValidatorTest {
@Test
public void testCatalogObjectParserValidatorOK()
throws ModelSyntaxException, ValidationException, ConversionException {
String value = "bucket_1/object10/1539310165443";
Assert.assertEquals(value,
new CatalogObjectParserValidator(ModelType.CATALOG_OBJECT.name()).parseAndValidate(value));
}
@Test(expected = ValidationException.class)
public void testCatalogObjectParserValidatorKO()
throws ModelSyntaxException, ValidationException, ConversionException {
String value = "bucket_1/object10/";
new CatalogObjectParserValidator(ModelType.CATALOG_OBJECT.name()).parseAndValidate(value);
}
@Test(expected = ModelSyntaxException.class)
public void testCatalogObjectParserValidatorInvalidModel()
throws ModelSyntaxException, ValidationException, ConversionException {
String value = "bucket_1/object10/";
new CatalogObjectParserValidator("catalog-type").parseAndValidate(value);
}
}
|
ShatalovYaroslav/scheduling
|
scheduler/scheduler-api/src/test/java/org/ow2/proactive/scheduler/common/job/factories/spi/model/factory/CatalogObjectParserValidatorTest.java
|
Java
|
agpl-3.0
| 2,583
|
/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "BrokenExpDiskGeometry.hpp"
#include "FatalError.hpp"
#include "Random.hpp"
#include "NR.hpp"
#include "SpecialFunctions.hpp"
#include "Units.hpp"
using namespace std;
////////////////////////////////////////////////////////////////////
BrokenExpDiskGeometry::BrokenExpDiskGeometry()
: _hinn(0), _hout(0), _hz(0), _Rb(0), _s(0),
_beta(0), _rho0(0), _SigmaR(0), _Rv(0), _Xv(0)
{
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setupSelfBefore()
{
SepAxGeometry::setupSelfBefore();
// verify property values
if (_hinn <= 0) throw FATALERROR("The inner scale length should be positive");
if (_hout <= 0) throw FATALERROR("The outer scale length should be positive");
if (_hz <= 0) throw FATALERROR("The axial scale height should be positive");
if (_Rb <= 0) throw FATALERROR("The break radius should be positive");
if (_s <= 0) throw FATALERROR("The sharpness should be positive");
_beta = 1.0/_s*(_hout/_hinn-1.0);
// create a radial array with the cumulative mass distribution. Use Ninn points in the
// range between 0 and _Rb, and Nout points between _Rb and the outermost radius,
// which we choose to be _Rb + 10*_hout.
int Ninn = 200;
int Nout = 400;
int N = Ninn+Nout;
_Rv.resize(N+1);
_Xv.resize(N+1);
double dRinn = _Rb/Ninn;
for (int i=0; i<Ninn; i++) _Rv[i] = i*dRinn;
double dRout = 10*_hout/Nout;
for (int i=Ninn; i<=N; i++) _Rv[i] = _Rb + (i-Ninn)*dRout;
_Xv[0] = 0.0;
double intprev = 0.0;
for (int i=1; i<=N; i++)
{
double RL = _Rv[i-1];
double RR = _Rv[i];
double intL = intprev;
double intR = radialdensity(RR)*RR;
intprev = intR;
_Xv[i] = _Xv[i-1] + 0.5*(RR-RL)*(intL+intR);
}
double IR = _Xv[N-1];
_Xv /= IR;
// calculate _rho0;
_rho0 = 1.0/4.0/M_PI/_hz/IR;
// calculate the radial surface density
intprev = 0.0;
double sum = 0.0;
for (int i=1; i<=N; i++)
{
double RL = _Rv[i-1];
double RR = _Rv[i];
double intL = intprev;
double intR = radialdensity(RR);
intprev = intR;
sum += 0.5*(RR-RL)*(intL+intR);
}
_SigmaR = sum*_rho0;
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setRadialScaleInner(double value)
{
_hinn = value;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::radialScaleInner() const
{
return _hinn;
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setRadialScaleOuter(double value)
{
_hout = value;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::radialScaleOuter() const
{
return _hout;
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setAxialScale(double value)
{
_hz = value;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::axialScale() const
{
return _hz;
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setBreakRadius(double value)
{
_Rb = value;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::breakRadius() const
{
return _Rb;
}
////////////////////////////////////////////////////////////////////
void BrokenExpDiskGeometry::setSharpness(double value)
{
_s = value;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::sharpness() const
{
return _s;
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::radialdensity(double R) const
{
return exp(-R/_hinn) * pow( 1.0+exp(_s*(R-_Rb)/_hout) , _beta);
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::density(double R, double z) const
{
return _rho0 * exp(-abs(z)/_hz) * radialdensity(R);
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::randomR() const
{
return _random->cdf(_Rv,_Xv);
}
////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::randomz() const
{
double z, XX;
XX = _random->uniform();
z = (XX<=0.5) ? _hz*log(2.0*XX) : -_hz*log(2.0*(1.0-XX));
return z;
}
//////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::SigmaR() const
{
return _SigmaR;
}
//////////////////////////////////////////////////////////////////////
double BrokenExpDiskGeometry::SigmaZ() const
{
return 2.0 * _rho0 * _hz * radialdensity(0.0);
}
//////////////////////////////////////////////////////////////////////
|
SKIRT/SKIRT
|
SKIRTcore/BrokenExpDiskGeometry.cpp
|
C++
|
agpl-3.0
| 5,220
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.krad.datadictionary.validation.constraint;
import java.io.Serializable;
import java.util.List;
/**
* This class is a direct copy of one that was in Kuali Student. Look up constraints are currently not implemented.
*
* @since 1.1
*/
public class CommonLookup implements Serializable {
private static final long serialVersionUID = 1L;
private String id; // unique ID of this lookup
private String name; // name of this search
private String desc;
private String searchTypeId;
private String resultReturnKey;
private String searchParamIdKey;
private List<CommonLookupParam> params;
public String getSearchTypeId() {
return searchTypeId;
}
public void setSearchTypeId(String searchTypeId) {
this.searchTypeId = searchTypeId;
}
public String getResultReturnKey() {
return resultReturnKey;
}
public void setResultReturnKey(String resultReturnKey) {
this.resultReturnKey = resultReturnKey;
}
public List<CommonLookupParam> getParams() {
return params;
}
public void setParams(List<CommonLookupParam> params) {
this.params = params;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getSearchParamIdKey() {
return searchParamIdKey;
}
public void setSearchParamIdKey(String searchParamIdKey) {
this.searchParamIdKey = searchParamIdKey;
}
}
|
quikkian-ua-devops/will-financials
|
kfs-kns/src/main/java/org/kuali/kfs/krad/datadictionary/validation/constraint/CommonLookup.java
|
Java
|
agpl-3.0
| 2,587
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.purap.fixture;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.module.purap.businessobject.RequisitionAccount;
import org.kuali.kfs.module.purap.businessobject.RequisitionItem;
import org.kuali.kfs.sys.fixture.AccountingLineFixture;
import org.kuali.rice.core.api.util.type.KualiDecimal;
public enum RequisitionAccountingLineFixture {
BASIC_REQ_ACCOUNT_1(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.PURAP_LINE3 // AccountingLineFixture
), BASIC_REQ_ACCOUNT_2(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.PURAP_LINE1 // AccountingLineFixture
), PERFORMANCE_ACCOUNT(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.PURAP_PERFORMANCE_LINE // AccountingLineFixture
), APO_REQ_ACCOUNT_1(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.APO_LINE1 // AccountingLineFixture
), APO_REQ_ACCOUNT_2(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, // PurApAccountingLineFixture
AccountingLineFixture.APO_LINE2 // AccountingLineFixture
), APO_REQ_ACCOUNT_3(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, // PurApAccountingLineFixture
AccountingLineFixture.APO_LINE3 // AccountingLineFixture
), APO_REQ_ACCOUNT_4(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.APO_LINE4 // AccountingLineFixture
), REQ_ACCOUNT_NEGATIVE_AMOUNT(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.PURAP_LINE_NEGATIVE_AMT // AccountingLineFixture
), REQ_ACCOUNT_MULTI_QUANTITY(PurApAccountingLineFixture.REQ_ACCOUNT_MULTI, // PurApAccountingLineFixture
AccountingLineFixture.REQ_ACCOUNT_MULTI_QUANTITY // AccountingLineFixture
), REQ_ACCOUNT_MULTI_NON_QUANTITY(PurApAccountingLineFixture.REQ_ACCOUNT_MULTI, // PurApAccountingLineFixture
AccountingLineFixture.REQ_ACCOUNT_MULTI_NON_QUANTITY // AccountingLineFixture
), APO_ACCOUNT_VALID_CAPITAL_ASSET_OBJECT_CODE(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture
AccountingLineFixture.APO_LINE2, // AccountingLineFixture
"7001" // objectCode
), APO_ACCOUNT_VALID_CAPITAL_ASSET_OBJECT_CODE_50_PERCENT(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, //PurApAccountingLineFixture
AccountingLineFixture.APO_LINE4, // AccountingLineFixture
"7001" // objectCode
), APO_ACCOUNT_VALID_EXPENSE_OBJECT_CODE_50_PERCENT(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, //PurApAccountingLineFixture
AccountingLineFixture.APO_LINE4, // AccountingLineFixture
"5000" // objectCode
),;
private PurApAccountingLineFixture purApAccountingLineFixture;
private AccountingLineFixture accountingLineFixture;
private String objectCode;
private RequisitionAccountingLineFixture(PurApAccountingLineFixture purApAccountingLineFixture, AccountingLineFixture accountingLineFixture) {
this.purApAccountingLineFixture = purApAccountingLineFixture;
this.accountingLineFixture = accountingLineFixture;
}
private RequisitionAccountingLineFixture(PurApAccountingLineFixture purApAccountingLineFixture, AccountingLineFixture accountingLineFixture, String objectCode) {
this.purApAccountingLineFixture = purApAccountingLineFixture;
this.accountingLineFixture = accountingLineFixture;
this.objectCode = objectCode;
}
public PurApAccountingLine createPurApAccountingLine(Class clazz, PurApAccountingLineFixture puralFixture, AccountingLineFixture alFixture) {
PurApAccountingLine line = null;
// TODO: what should this debit code really be
line = puralFixture.createPurApAccountingLine(RequisitionAccount.class, alFixture);
if (StringUtils.isNotBlank(objectCode)) {
line.setFinancialObjectCode(objectCode);
line.refreshReferenceObject("objectCode");
}
return line;
}
public void addTo(RequisitionItem item) {
PurApAccountingLine purApAccountingLine = createPurApAccountingLine(item.getAccountingLineClass(), purApAccountingLineFixture, accountingLineFixture);
//fix item reference
purApAccountingLine.setPurapItem(item);
// fix amount
purApAccountingLine.setAmount(item.calculateExtendedPrice().multiply(new KualiDecimal(purApAccountingLine.getAccountLinePercent())).divide(new KualiDecimal(100)));
item.getSourceAccountingLines().add(purApAccountingLine);
}
/**
* This method adds an account to an item
*
* @param document
* @param purApItemFixture
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void addTo(PurApItem item, PurApAccountingLineFixture purApaccountFixture, AccountingLineFixture alFixture) throws IllegalAccessException, InstantiationException {
// purApaccountFixture.createPurApAccountingLine(RequisitionAccount.class, alFixture);
if (0 == 0) {
;
}
}
}
|
quikkian-ua-devops/will-financials
|
kfs-purap/src/test/java/org/kuali/kfs/module/purap/fixture/RequisitionAccountingLineFixture.java
|
Java
|
agpl-3.0
| 6,153
|
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"sort"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names"
jc "github.com/juju/testing/checkers"
"github.com/juju/utils"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/juju/constraints"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/state/multiwatcher"
"github.com/juju/juju/state/watcher"
"github.com/juju/juju/testing"
)
var (
_ backingEntityDoc = (*backingMachine)(nil)
_ backingEntityDoc = (*backingUnit)(nil)
_ backingEntityDoc = (*backingService)(nil)
_ backingEntityDoc = (*backingRelation)(nil)
_ backingEntityDoc = (*backingAnnotation)(nil)
_ backingEntityDoc = (*backingStatus)(nil)
_ backingEntityDoc = (*backingConstraints)(nil)
_ backingEntityDoc = (*backingSettings)(nil)
_ backingEntityDoc = (*backingOpenedPorts)(nil)
_ backingEntityDoc = (*backingAction)(nil)
_ backingEntityDoc = (*backingBlock)(nil)
)
var dottedConfig = `
options:
key.dotted: {default: My Key, description: Desc, type: string}
`
type allWatcherBaseSuite struct {
internalStateSuite
envCount int
}
func (s *allWatcherBaseSuite) newState(c *gc.C) *State {
s.envCount++
cfg := testing.CustomEnvironConfig(c, testing.Attrs{
"name": fmt.Sprintf("testenv%d", s.envCount),
"uuid": utils.MustNewUUID().String(),
})
_, st, err := s.state.NewEnvironment(cfg, s.owner)
c.Assert(err, jc.ErrorIsNil)
s.AddCleanup(func(*gc.C) { st.Close() })
return st
}
// setUpScenario adds some entities to the state so that
// we can check that they all get pulled in by
// all(Env)WatcherStateBacking.GetAll.
func (s *allWatcherBaseSuite) setUpScenario(c *gc.C, st *State, units int) (entities entityInfoSlice) {
envUUID := st.EnvironUUID()
add := func(e multiwatcher.EntityInfo) {
entities = append(entities, e)
}
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m.Tag(), gc.Equals, names.NewMachineTag("0"))
err = m.SetHasVote(true)
c.Assert(err, jc.ErrorIsNil)
// TODO(dfc) instance.Id should take a TAG!
err = m.SetProvisioned(instance.Id("i-"+m.Tag().String()), "fake_nonce", nil)
c.Assert(err, jc.ErrorIsNil)
hc, err := m.HardwareCharacteristics()
c.Assert(err, jc.ErrorIsNil)
err = m.SetProviderAddresses(network.NewAddress("example.com"))
c.Assert(err, jc.ErrorIsNil)
add(&multiwatcher.MachineInfo{
EnvUUID: envUUID,
Id: "0",
InstanceId: "i-machine-0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "quantal",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: m.Addresses(),
HardwareCharacteristics: hc,
HasVote: true,
WantsVote: false,
})
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
err = wordpress.SetExposed()
c.Assert(err, jc.ErrorIsNil)
err = wordpress.SetMinUnits(units)
c.Assert(err, jc.ErrorIsNil)
err = wordpress.SetConstraints(constraints.MustParse("mem=100M"))
c.Assert(err, jc.ErrorIsNil)
setServiceConfigAttr(c, wordpress, "blog-title", "boring")
add(&multiwatcher.ServiceInfo{
EnvUUID: envUUID,
Name: "wordpress",
Exposed: true,
CharmURL: serviceCharmURL(wordpress).String(),
OwnerTag: s.owner.String(),
Life: multiwatcher.Life("alive"),
MinUnits: units,
Constraints: constraints.MustParse("mem=100M"),
Config: charm.Settings{"blog-title": "boring"},
Subordinate: false,
Status: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
})
pairs := map[string]string{"x": "12", "y": "99"}
err = st.SetAnnotations(wordpress, pairs)
c.Assert(err, jc.ErrorIsNil)
add(&multiwatcher.AnnotationInfo{
EnvUUID: envUUID,
Tag: "service-wordpress",
Annotations: pairs,
})
logging := AddTestingService(c, st, "logging", AddTestingCharm(c, st, "logging"), s.owner)
add(&multiwatcher.ServiceInfo{
EnvUUID: envUUID,
Name: "logging",
CharmURL: serviceCharmURL(logging).String(),
OwnerTag: s.owner.String(),
Life: multiwatcher.Life("alive"),
Config: charm.Settings{},
Subordinate: true,
Status: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
})
eps, err := st.InferEndpoints("logging", "wordpress")
c.Assert(err, jc.ErrorIsNil)
rel, err := st.AddRelation(eps...)
c.Assert(err, jc.ErrorIsNil)
add(&multiwatcher.RelationInfo{
EnvUUID: envUUID,
Key: "logging:logging-directory wordpress:logging-dir",
Id: rel.Id(),
Endpoints: []multiwatcher.Endpoint{
{ServiceName: "logging", Relation: charm.Relation{Name: "logging-directory", Role: "requirer", Interface: "logging", Optional: false, Limit: 1, Scope: "container"}},
{ServiceName: "wordpress", Relation: charm.Relation{Name: "logging-dir", Role: "provider", Interface: "logging", Optional: false, Limit: 0, Scope: "container"}}},
})
for i := 0; i < units; i++ {
wu, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
c.Assert(wu.Tag().String(), gc.Equals, fmt.Sprintf("unit-wordpress-%d", i))
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m.Tag().String(), gc.Equals, fmt.Sprintf("machine-%d", i+1))
add(&multiwatcher.UnitInfo{
EnvUUID: envUUID,
Name: fmt.Sprintf("wordpress/%d", i),
Service: wordpress.Name(),
Series: m.Series(),
MachineId: m.Id(),
Ports: []network.Port{},
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Subordinate: false,
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
})
pairs := map[string]string{"name": fmt.Sprintf("bar %d", i)}
err = st.SetAnnotations(wu, pairs)
c.Assert(err, jc.ErrorIsNil)
add(&multiwatcher.AnnotationInfo{
EnvUUID: envUUID,
Tag: fmt.Sprintf("unit-wordpress-%d", i),
Annotations: pairs,
})
err = m.SetProvisioned(instance.Id("i-"+m.Tag().String()), "fake_nonce", nil)
c.Assert(err, jc.ErrorIsNil)
err = m.SetStatus(StatusError, m.Tag().String(), nil)
c.Assert(err, jc.ErrorIsNil)
hc, err := m.HardwareCharacteristics()
c.Assert(err, jc.ErrorIsNil)
add(&multiwatcher.MachineInfo{
EnvUUID: envUUID,
Id: fmt.Sprint(i + 1),
InstanceId: "i-" + m.Tag().String(),
Status: multiwatcher.Status("error"),
StatusInfo: m.Tag().String(),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "quantal",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HardwareCharacteristics: hc,
HasVote: false,
WantsVote: false,
})
err = wu.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
deployer, ok := wu.DeployerTag()
c.Assert(ok, jc.IsTrue)
c.Assert(deployer, gc.Equals, names.NewMachineTag(fmt.Sprintf("%d", i+1)))
wru, err := rel.Unit(wu)
c.Assert(err, jc.ErrorIsNil)
// Create the subordinate unit as a side-effect of entering
// scope in the principal's relation-unit.
err = wru.EnterScope(nil)
c.Assert(err, jc.ErrorIsNil)
lu, err := st.Unit(fmt.Sprintf("logging/%d", i))
c.Assert(err, jc.ErrorIsNil)
c.Assert(lu.IsPrincipal(), jc.IsFalse)
deployer, ok = lu.DeployerTag()
c.Assert(ok, jc.IsTrue)
c.Assert(deployer, gc.Equals, names.NewUnitTag(fmt.Sprintf("wordpress/%d", i)))
add(&multiwatcher.UnitInfo{
EnvUUID: envUUID,
Name: fmt.Sprintf("logging/%d", i),
Service: "logging",
Series: "quantal",
Ports: []network.Port{},
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Subordinate: true,
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
})
}
return
}
var _ = gc.Suite(&allWatcherStateSuite{})
type allWatcherStateSuite struct {
allWatcherBaseSuite
}
func (s *allWatcherStateSuite) Reset(c *gc.C) {
s.TearDownTest(c)
s.SetUpTest(c)
}
func (s *allWatcherStateSuite) TestGetAll(c *gc.C) {
expectEntities := s.setUpScenario(c, s.state, 2)
s.checkGetAll(c, expectEntities)
}
func (s *allWatcherStateSuite) TestGetAllMultiEnv(c *gc.C) {
// Set up 2 environments and ensure that GetAll returns the
// entities for the first environment with no errors.
expectEntities := s.setUpScenario(c, s.state, 2)
// Use more units in the second env to ensure the number of
// entities will mismatch if environment filtering isn't in place.
s.setUpScenario(c, s.newState(c), 4)
s.checkGetAll(c, expectEntities)
}
func (s *allWatcherStateSuite) checkGetAll(c *gc.C, expectEntities entityInfoSlice) {
b := newAllWatcherStateBacking(s.state)
all := newStore()
err := b.GetAll(all)
c.Assert(err, jc.ErrorIsNil)
var gotEntities entityInfoSlice = all.All()
sort.Sort(gotEntities)
sort.Sort(expectEntities)
substNilSinceTimeForEntities(c, gotEntities)
assertEntitiesEqual(c, gotEntities, expectEntities)
}
func serviceCharmURL(svc *Service) *charm.URL {
url, _ := svc.CharmURL()
return url
}
func setServiceConfigAttr(c *gc.C, svc *Service, attr string, val interface{}) {
err := svc.UpdateConfigSettings(charm.Settings{attr: val})
c.Assert(err, jc.ErrorIsNil)
}
// changeTestCase encapsulates entities to add, a change, and
// the expected contents for a test.
type changeTestCase struct {
// about describes the test case.
about string
// initialContents contains the infos of the
// watcher before signalling the change.
initialContents []multiwatcher.EntityInfo
// change signals the change of the watcher.
change watcher.Change
// expectContents contains the expected infos of
// the watcher before signalling the change.
expectContents []multiwatcher.EntityInfo
}
func substNilSinceTimeForStatus(c *gc.C, status *multiwatcher.StatusInfo) {
if status.Current != "" {
c.Assert(status.Since, gc.NotNil)
}
status.Since = nil
}
// substNilSinceTimeForEntities zeros out any updated timestamps for unit
// or service status values so we can easily check the results.
func substNilSinceTimeForEntities(c *gc.C, entities []multiwatcher.EntityInfo) {
// Zero out any updated timestamps for unit or service status values
// so we can easily check the results.
for i, entity := range entities {
if unitInfo, ok := entity.(*multiwatcher.UnitInfo); ok {
substNilSinceTimeForStatus(c, &unitInfo.WorkloadStatus)
substNilSinceTimeForStatus(c, &unitInfo.AgentStatus)
entities[i] = unitInfo
}
if serviceInfo, ok := entity.(*multiwatcher.ServiceInfo); ok {
substNilSinceTimeForStatus(c, &serviceInfo.Status)
entities[i] = serviceInfo
}
}
}
// changeTestFunc is a function for the preparation of a test and
// the creation of the according case.
type changeTestFunc func(c *gc.C, st *State) changeTestCase
// performChangeTestCases runs a passed number of test cases for changes.
func (s *allWatcherStateSuite) performChangeTestCases(c *gc.C, changeTestFuncs []changeTestFunc) {
for i, changeTestFunc := range changeTestFuncs {
test := changeTestFunc(c, s.state)
c.Logf("test %d. %s", i, test.about)
b := newAllWatcherStateBacking(s.state)
all := newStore()
for _, info := range test.initialContents {
all.Update(info)
}
err := b.Changed(all, test.change)
c.Assert(err, jc.ErrorIsNil)
entities := all.All()
substNilSinceTimeForEntities(c, entities)
assertEntitiesEqual(c, entities, test.expectContents)
s.Reset(c)
}
}
func (s *allWatcherStateSuite) TestChangeAnnotations(c *gc.C) {
testChangeAnnotations(c, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeMachines(c *gc.C) {
testChangeMachines(c, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeRelations(c *gc.C) {
testChangeRelations(c, s.owner, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeServices(c *gc.C) {
testChangeServices(c, s.owner, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeServicesConstraints(c *gc.C) {
testChangeServicesConstraints(c, s.owner, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeUnits(c *gc.C) {
testChangeUnits(c, s.owner, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeUnitsNonNilPorts(c *gc.C) {
testChangeUnitsNonNilPorts(c, s.owner, s.performChangeTestCases)
}
func (s *allWatcherStateSuite) TestChangeActions(c *gc.C) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
action, err := st.EnqueueAction(u.Tag(), "vacuumdb", map[string]interface{}{})
c.Assert(err, jc.ErrorIsNil)
enqueued := makeActionInfo(action, st)
action, err = action.Begin()
c.Assert(err, jc.ErrorIsNil)
started := makeActionInfo(action, st)
return changeTestCase{
about: "action change picks up last change",
initialContents: []multiwatcher.EntityInfo{&enqueued, &started},
change: watcher.Change{C: actionsC, Id: st.docID(action.Id())},
expectContents: []multiwatcher.EntityInfo{&started},
}
},
}
s.performChangeTestCases(c, changeTestFuncs)
}
func (s *allWatcherStateSuite) TestChangeBlocks(c *gc.C) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no blocks in state, no blocks in store -> do nothing",
change: watcher.Change{
C: blocksC,
Id: "1",
}}
},
func(c *gc.C, st *State) changeTestCase {
blockId := st.docID("0")
blockType := DestroyBlock.ToParams()
blockMsg := "woot"
return changeTestCase{
about: "no change if block is not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.BlockInfo{
EnvUUID: st.EnvironUUID(),
Id: blockId,
Type: blockType,
Message: blockMsg,
Tag: st.EnvironTag().String(),
}},
change: watcher.Change{
C: blocksC,
Id: st.localID(blockId),
},
expectContents: []multiwatcher.EntityInfo{&multiwatcher.BlockInfo{
EnvUUID: st.EnvironUUID(),
Id: blockId,
Type: blockType,
Message: blockMsg,
Tag: st.EnvironTag().String(),
}},
}
},
func(c *gc.C, st *State) changeTestCase {
err := st.SwitchBlockOn(DestroyBlock, "multiwatcher testing")
c.Assert(err, jc.ErrorIsNil)
b, found, err := st.GetBlockForType(DestroyBlock)
c.Assert(err, jc.ErrorIsNil)
c.Assert(found, jc.IsTrue)
blockId := b.Id()
return changeTestCase{
about: "block is added if it's in backing but not in Store",
change: watcher.Change{
C: blocksC,
Id: blockId,
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.BlockInfo{
EnvUUID: st.EnvironUUID(),
Id: st.localID(blockId),
Type: b.Type().ToParams(),
Message: b.Message(),
Tag: st.EnvironTag().String(),
}}}
},
func(c *gc.C, st *State) changeTestCase {
err := st.SwitchBlockOn(DestroyBlock, "multiwatcher testing")
c.Assert(err, jc.ErrorIsNil)
b, found, err := st.GetBlockForType(DestroyBlock)
c.Assert(err, jc.ErrorIsNil)
c.Assert(found, jc.IsTrue)
err = st.SwitchBlockOff(DestroyBlock)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "block is removed if it's in backing and in multiwatcher.Store",
change: watcher.Change{
C: blocksC,
Id: b.Id(),
},
}
},
}
s.performChangeTestCases(c, changeTestFuncs)
}
func (s *allWatcherStateSuite) TestClosingPorts(c *gc.C) {
defer s.Reset(c)
// Init the test environment.
wordpress := AddTestingService(c, s.state, "wordpress", AddTestingCharm(c, s.state, "wordpress"), s.owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := s.state.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
publicAddress := network.NewScopedAddress("1.2.3.4", network.ScopePublic)
privateAddress := network.NewScopedAddress("4.3.2.1", network.ScopeCloudLocal)
err = m.SetProviderAddresses(publicAddress)
c.Assert(err, jc.ErrorIsNil)
err = m.SetMachineAddresses(privateAddress)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPorts("tcp", 12345, 12345)
c.Assert(err, jc.ErrorIsNil)
// Create all watcher state backing.
b := newAllWatcherStateBacking(s.state)
all := newStore()
all.Update(&multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "0",
})
// Check opened ports.
err = b.Changed(all, watcher.Change{
C: "units",
Id: s.state.docID("wordpress/0"),
})
c.Assert(err, jc.ErrorIsNil)
entities := all.All()
substNilSinceTimeForEntities(c, entities)
assertEntitiesEqual(c, entities, []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
PublicAddress: "1.2.3.4",
PrivateAddress: "4.3.2.1",
Ports: []network.Port{{"tcp", 12345}},
PortRanges: []network.PortRange{{12345, 12345, "tcp"}},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Data: map[string]interface{}{},
},
},
&multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "0",
},
})
// Close the ports.
err = u.ClosePorts("tcp", 12345, 12345)
c.Assert(err, jc.ErrorIsNil)
err = b.Changed(all, watcher.Change{
C: openedPortsC,
Id: s.state.docID("m#0#n#juju-public"),
})
c.Assert(err, jc.ErrorIsNil)
entities = all.All()
assertEntitiesEqual(c, entities, []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
PublicAddress: "1.2.3.4",
PrivateAddress: "4.3.2.1",
Ports: []network.Port{},
PortRanges: []network.PortRange{},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Data: map[string]interface{}{},
},
},
&multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "0",
},
})
}
func (s *allWatcherStateSuite) TestSettings(c *gc.C) {
defer s.Reset(c)
// Init the test environment.
svc := AddTestingService(c, s.state, "dummy-service", AddTestingCharm(c, s.state, "dummy"), s.owner)
b := newAllWatcherStateBacking(s.state)
all := newStore()
// 1st scenario part: set settings and signal change.
setServiceConfigAttr(c, svc, "username", "foo")
setServiceConfigAttr(c, svc, "outlook", "foo@bar")
all.Update(&multiwatcher.ServiceInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
})
err := b.Changed(all, watcher.Change{
C: "settings",
Id: s.state.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
})
c.Assert(err, jc.ErrorIsNil)
entities := all.All()
substNilSinceTimeForEntities(c, entities)
assertEntitiesEqual(c, entities, []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"outlook": "foo@bar", "username": "foo"},
},
})
// 2nd scenario part: destroy the service and signal change.
err = svc.Destroy()
c.Assert(err, jc.ErrorIsNil)
err = b.Changed(all, watcher.Change{
C: "settings",
Id: s.state.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
})
c.Assert(err, jc.ErrorIsNil)
entities = all.All()
assertEntitiesEqual(c, entities, []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
},
})
}
// TestStateWatcher tests the integration of the state watcher
// with the state-based backing. Most of the logic is tested elsewhere -
// this just tests end-to-end.
func (s *allWatcherStateSuite) TestStateWatcher(c *gc.C) {
m0, err := s.state.AddMachine("trusty", JobManageEnviron)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m0.Id(), gc.Equals, "0")
m1, err := s.state.AddMachine("saucy", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m1.Id(), gc.Equals, "1")
tw := newTestAllWatcher(s.state, c)
defer tw.Stop()
// Expect to see events for the already created machines first.
deltas := tw.All(2)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobManageEnviron.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: true,
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "1",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
// Destroy a machine and make sure that's seen.
err = m1.Destroy()
c.Assert(err, jc.ErrorIsNil)
deltas = tw.All(1)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "1",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("dying"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
err = m1.EnsureDead()
c.Assert(err, jc.ErrorIsNil)
deltas = tw.All(1)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "1",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("dead"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
// Make some more changes to the state.
arch := "amd64"
mem := uint64(4096)
hc := &instance.HardwareCharacteristics{
Arch: &arch,
Mem: &mem,
}
err = m0.SetProvisioned("i-0", "bootstrap_nonce", hc)
c.Assert(err, jc.ErrorIsNil)
err = m1.Remove()
c.Assert(err, jc.ErrorIsNil)
m2, err := s.state.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m2.Id(), gc.Equals, "2")
wordpress := AddTestingService(c, s.state, "wordpress", AddTestingCharm(c, s.state, "wordpress"), s.owner)
wu, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = wu.AssignToMachine(m2)
c.Assert(err, jc.ErrorIsNil)
// Look for the state changes from the allwatcher.
deltas = tw.All(5)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "0",
InstanceId: "i-0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobManageEnviron.ToParams()},
Addresses: []network.Address{},
HardwareCharacteristics: hc,
HasVote: false,
WantsVote: true,
},
}, {
Removed: true,
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "1",
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: s.state.EnvironUUID(),
Id: "2",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "quantal",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}, {
Entity: &multiwatcher.ServiceInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "wordpress",
CharmURL: "local:quantal/quantal-wordpress-3",
OwnerTag: s.owner.String(),
Life: "alive",
Config: make(map[string]interface{}),
Status: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
},
}, {
Entity: &multiwatcher.UnitInfo{
EnvUUID: s.state.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "2",
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
},
}})
}
func (s *allWatcherStateSuite) TestStateWatcherTwoEnvironments(c *gc.C) {
loggo.GetLogger("juju.state.watcher").SetLogLevel(loggo.TRACE)
for i, test := range []struct {
about string
setUpState func(*State)
triggerEvent func(*State)
}{
{
about: "machines",
triggerEvent: func(st *State) {
m0, err := st.AddMachine("trusty", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m0.Id(), gc.Equals, "0")
},
}, {
about: "services",
triggerEvent: func(st *State) {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
},
}, {
about: "units",
setUpState: func(st *State) {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
},
triggerEvent: func(st *State) {
svc, err := st.Service("wordpress")
c.Assert(err, jc.ErrorIsNil)
_, err = svc.AddUnit()
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "relations",
setUpState: func(st *State) {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
AddTestingService(c, st, "mysql", AddTestingCharm(c, st, "mysql"), s.owner)
},
triggerEvent: func(st *State) {
eps, err := st.InferEndpoints("mysql", "wordpress")
c.Assert(err, jc.ErrorIsNil)
_, err = st.AddRelation(eps...)
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "annotations",
setUpState: func(st *State) {
m, err := st.AddMachine("trusty", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m.Id(), gc.Equals, "0")
},
triggerEvent: func(st *State) {
m, err := st.Machine("0")
c.Assert(err, jc.ErrorIsNil)
err = st.SetAnnotations(m, map[string]string{"foo": "bar"})
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "statuses",
setUpState: func(st *State) {
m, err := st.AddMachine("trusty", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m.Id(), gc.Equals, "0")
err = m.SetProvisioned("inst-id", "fake_nonce", nil)
c.Assert(err, jc.ErrorIsNil)
},
triggerEvent: func(st *State) {
m, err := st.Machine("0")
c.Assert(err, jc.ErrorIsNil)
err = m.SetStatus("error", "pete tong", nil)
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "constraints",
setUpState: func(st *State) {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
},
triggerEvent: func(st *State) {
svc, err := st.Service("wordpress")
c.Assert(err, jc.ErrorIsNil)
cpuCores := uint64(99)
err = svc.SetConstraints(constraints.Value{CpuCores: &cpuCores})
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "settings",
setUpState: func(st *State) {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
},
triggerEvent: func(st *State) {
svc, err := st.Service("wordpress")
c.Assert(err, jc.ErrorIsNil)
err = svc.UpdateConfigSettings(charm.Settings{"blog-title": "boring"})
c.Assert(err, jc.ErrorIsNil)
},
}, {
about: "blocks",
triggerEvent: func(st *State) {
m, found, err := st.GetBlockForType(DestroyBlock)
c.Assert(err, jc.ErrorIsNil)
c.Assert(found, jc.IsFalse)
c.Assert(m, gc.IsNil)
err = st.SwitchBlockOn(DestroyBlock, "test block")
c.Assert(err, jc.ErrorIsNil)
},
},
} {
c.Logf("Test %d: %s", i, test.about)
func() {
checkIsolationForEnv := func(st *State, w, otherW *testWatcher) {
c.Logf("Making changes to environment %s", st.EnvironUUID())
if test.setUpState != nil {
test.setUpState(st)
// Consume events from setup.
w.AssertChanges()
w.AssertNoChange()
otherW.AssertNoChange()
}
test.triggerEvent(st)
// Check event was isolated to the correct watcher.
w.AssertChanges()
w.AssertNoChange()
otherW.AssertNoChange()
}
otherState := s.newState(c)
w1 := newTestAllWatcher(s.state, c)
defer w1.Stop()
w2 := newTestAllWatcher(otherState, c)
defer w2.Stop()
checkIsolationForEnv(s.state, w1, w2)
checkIsolationForEnv(otherState, w2, w1)
}()
s.Reset(c)
}
}
var _ = gc.Suite(&allEnvWatcherStateSuite{})
type allEnvWatcherStateSuite struct {
allWatcherBaseSuite
state1 *State
}
func (s *allEnvWatcherStateSuite) SetUpTest(c *gc.C) {
s.allWatcherBaseSuite.SetUpTest(c)
s.state1 = s.newState(c)
}
func (s *allEnvWatcherStateSuite) Reset(c *gc.C) {
s.TearDownTest(c)
s.SetUpTest(c)
}
// performChangeTestCases runs a passed number of test cases for changes.
func (s *allEnvWatcherStateSuite) performChangeTestCases(c *gc.C, changeTestFuncs []changeTestFunc) {
for i, changeTestFunc := range changeTestFuncs {
func() { // in aid of per-loop defers
defer s.Reset(c)
test0 := changeTestFunc(c, s.state)
c.Logf("test %d. %s", i, test0.about)
b := newAllEnvWatcherStateBacking(s.state)
defer b.Release()
all := newStore()
// Do updates and check for first env.
for _, info := range test0.initialContents {
all.Update(info)
}
err := b.Changed(all, test0.change)
c.Assert(err, jc.ErrorIsNil)
var entities entityInfoSlice = all.All()
substNilSinceTimeForEntities(c, entities)
assertEntitiesEqual(c, entities, test0.expectContents)
// Now do the same updates for a second env.
test1 := changeTestFunc(c, s.state1)
for _, info := range test1.initialContents {
all.Update(info)
}
err = b.Changed(all, test1.change)
c.Assert(err, jc.ErrorIsNil)
entities = all.All()
// substNilSinceTimeForEntities gets upset if it sees non-nil
// times - which the entities for the first env will have - so
// build a list of the entities for the second env.
newEntities := make([]multiwatcher.EntityInfo, 0)
for _, entity := range entities {
if entity.EntityId().EnvUUID == s.state1.EnvironUUID() {
newEntities = append(newEntities, entity)
}
}
substNilSinceTimeForEntities(c, newEntities)
// Expected to see entities for both envs.
var expectedEntities entityInfoSlice = append(
test0.expectContents,
test1.expectContents...)
sort.Sort(entities)
sort.Sort(expectedEntities)
assertEntitiesEqual(c, entities, expectedEntities)
}()
}
}
func (s *allEnvWatcherStateSuite) TestChangeAnnotations(c *gc.C) {
testChangeAnnotations(c, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeMachines(c *gc.C) {
testChangeMachines(c, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeRelations(c *gc.C) {
testChangeRelations(c, s.owner, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeServices(c *gc.C) {
testChangeServices(c, s.owner, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeServicesConstraints(c *gc.C) {
testChangeServicesConstraints(c, s.owner, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeUnits(c *gc.C) {
testChangeUnits(c, s.owner, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeUnitsNonNilPorts(c *gc.C) {
testChangeUnitsNonNilPorts(c, s.owner, s.performChangeTestCases)
}
func (s *allEnvWatcherStateSuite) TestChangeEnvironments(c *gc.C) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no environment in state -> do nothing",
change: watcher.Change{
C: "environments",
Id: "non-existing-uuid",
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "environment is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.EnvironmentInfo{
EnvUUID: "some-uuid",
}},
change: watcher.Change{
C: "environments",
Id: "some-uuid",
}}
},
func(c *gc.C, st *State) changeTestCase {
env, err := st.Environment()
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "environment is added if it's in backing but not in Store",
change: watcher.Change{
C: "environments",
Id: st.EnvironUUID(),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.EnvironmentInfo{
EnvUUID: env.UUID(),
Name: env.Name(),
Life: multiwatcher.Life("alive"),
Owner: env.Owner().Id(),
ServerUUID: env.ServerUUID(),
}}}
},
func(c *gc.C, st *State) changeTestCase {
env, err := st.Environment()
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "environment is updated if it's in backing and in Store",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.EnvironmentInfo{
EnvUUID: env.UUID(),
Name: "",
Life: multiwatcher.Life("alive"),
Owner: env.Owner().Id(),
ServerUUID: env.ServerUUID(),
},
},
change: watcher.Change{
C: "environments",
Id: env.UUID(),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.EnvironmentInfo{
EnvUUID: env.UUID(),
Name: env.Name(),
Life: multiwatcher.Life("alive"),
Owner: env.Owner().Id(),
ServerUUID: env.ServerUUID(),
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), s.owner)
err := svc.SetConstraints(constraints.MustParse("mem=4G arch=amd64"))
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "status is changed if the service exists in the store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=99M cpu-cores=2 cpu-power=4"),
}},
change: watcher.Change{
C: "constraints",
Id: st.docID("s#wordpress"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=4G arch=amd64"),
}}}
},
}
s.performChangeTestCases(c, changeTestFuncs)
}
func (s *allEnvWatcherStateSuite) TestChangeForDeadEnv(c *gc.C) {
// Ensure an entity is removed when a change is seen but
// the environment the entity belonged to has already died.
b := newAllEnvWatcherStateBacking(s.state)
defer b.Release()
all := newStore()
// Insert a machine for an environment that doesn't actually
// exist (mimics env removal).
all.Update(&multiwatcher.MachineInfo{
EnvUUID: "uuid",
Id: "0",
})
c.Assert(all.All(), gc.HasLen, 1)
err := b.Changed(all, watcher.Change{
C: "machines",
Id: ensureEnvUUID("uuid", "0"),
})
c.Assert(err, jc.ErrorIsNil)
// Entity info should be gone now.
c.Assert(all.All(), gc.HasLen, 0)
}
func (s *allEnvWatcherStateSuite) TestGetAll(c *gc.C) {
// Set up 2 environments and ensure that GetAll returns the
// entities for both of them.
entities0 := s.setUpScenario(c, s.state, 2)
entities1 := s.setUpScenario(c, s.state1, 4)
expectedEntities := append(entities0, entities1...)
// allEnvWatcherStateBacking also watches environments so add those in.
env, err := s.state.Environment()
c.Assert(err, jc.ErrorIsNil)
env1, err := s.state1.Environment()
c.Assert(err, jc.ErrorIsNil)
expectedEntities = append(expectedEntities,
&multiwatcher.EnvironmentInfo{
EnvUUID: env.UUID(),
Name: env.Name(),
Life: multiwatcher.Life("alive"),
Owner: env.Owner().Id(),
ServerUUID: env.ServerUUID(),
},
&multiwatcher.EnvironmentInfo{
EnvUUID: env1.UUID(),
Name: env1.Name(),
Life: multiwatcher.Life("alive"),
Owner: env1.Owner().Id(),
ServerUUID: env1.ServerUUID(),
},
)
b := newAllEnvWatcherStateBacking(s.state)
all := newStore()
err = b.GetAll(all)
c.Assert(err, jc.ErrorIsNil)
var gotEntities entityInfoSlice = all.All()
sort.Sort(gotEntities)
sort.Sort(expectedEntities)
substNilSinceTimeForEntities(c, gotEntities)
assertEntitiesEqual(c, gotEntities, expectedEntities)
}
// TestStateWatcher tests the integration of the state watcher with
// allEnvWatcherStateBacking. Most of the logic is comprehensively
// tested elsewhere - this just tests end-to-end.
func (s *allEnvWatcherStateSuite) TestStateWatcher(c *gc.C) {
st0 := s.state
env0, err := st0.Environment()
c.Assert(err, jc.ErrorIsNil)
st1 := s.state1
env1, err := st1.Environment()
c.Assert(err, jc.ErrorIsNil)
// Create some initial machines across 2 environments
m00, err := st0.AddMachine("trusty", JobManageEnviron)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m00.Id(), gc.Equals, "0")
m10, err := st1.AddMachine("saucy", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m10.Id(), gc.Equals, "0")
tw := newTestAllEnvWatcher(st0, c)
defer tw.Stop()
// Expect to see events for the already created environments and
// machines first.
deltas := tw.All(4)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.EnvironmentInfo{
EnvUUID: env0.UUID(),
Name: env0.Name(),
Life: "alive",
Owner: env0.Owner().Id(),
ServerUUID: env0.ServerUUID(),
},
}, {
Entity: &multiwatcher.EnvironmentInfo{
EnvUUID: env1.UUID(),
Name: env1.Name(),
Life: "alive",
Owner: env1.Owner().Id(),
ServerUUID: env1.ServerUUID(),
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: st0.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobManageEnviron.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: true,
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: st1.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
// Destroy a machine and make sure that's seen.
err = m10.Destroy()
c.Assert(err, jc.ErrorIsNil)
deltas = tw.All(1)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: st1.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("dying"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
err = m10.EnsureDead()
c.Assert(err, jc.ErrorIsNil)
deltas = tw.All(1)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: st1.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("dead"),
Series: "saucy",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
// Make further changes to the state, including the addition of a
// new environment.
err = m00.SetProvisioned("i-0", "bootstrap_nonce", nil)
c.Assert(err, jc.ErrorIsNil)
err = m10.Remove()
c.Assert(err, jc.ErrorIsNil)
m11, err := st1.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m11.Id(), gc.Equals, "1")
wordpress := AddTestingService(c, st1, "wordpress", AddTestingCharm(c, st1, "wordpress"), s.owner)
wu, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = wu.AssignToMachine(m11)
c.Assert(err, jc.ErrorIsNil)
st2 := s.newState(c)
env2, err := st2.Environment()
c.Assert(err, jc.ErrorIsNil)
m20, err := st2.AddMachine("trusty", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
c.Assert(m20.Id(), gc.Equals, "0")
// Look for the state changes from the allwatcher.
deltas = tw.All(7)
zeroOutTimestampsForDeltas(c, deltas)
checkDeltasEqual(c, deltas, []multiwatcher.Delta{{
Entity: &multiwatcher.MachineInfo{
EnvUUID: st0.EnvironUUID(),
Id: "0",
InstanceId: "i-0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobManageEnviron.ToParams()},
Addresses: []network.Address{},
HardwareCharacteristics: &instance.HardwareCharacteristics{},
HasVote: false,
WantsVote: true,
},
}, {
Removed: true,
Entity: &multiwatcher.MachineInfo{
EnvUUID: st1.EnvironUUID(),
Id: "0",
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: st1.EnvironUUID(),
Id: "1",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "quantal",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}, {
Entity: &multiwatcher.ServiceInfo{
EnvUUID: st1.EnvironUUID(),
Name: "wordpress",
CharmURL: "local:quantal/quantal-wordpress-3",
OwnerTag: s.owner.String(),
Life: "alive",
Config: make(map[string]interface{}),
Status: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
},
}, {
Entity: &multiwatcher.UnitInfo{
EnvUUID: st1.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "1",
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
},
}, {
Entity: &multiwatcher.EnvironmentInfo{
EnvUUID: env2.UUID(),
Name: env2.Name(),
Life: "alive",
Owner: env2.Owner().Id(),
ServerUUID: env2.ServerUUID(),
},
}, {
Entity: &multiwatcher.MachineInfo{
EnvUUID: st2.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("pending"),
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
},
}})
}
func zeroOutTimestampsForDeltas(c *gc.C, deltas []multiwatcher.Delta) {
for i, delta := range deltas {
if unitInfo, ok := delta.Entity.(*multiwatcher.UnitInfo); ok {
substNilSinceTimeForStatus(c, &unitInfo.WorkloadStatus)
substNilSinceTimeForStatus(c, &unitInfo.AgentStatus)
delta.Entity = unitInfo
} else if serviceInfo, ok := delta.Entity.(*multiwatcher.ServiceInfo); ok {
substNilSinceTimeForStatus(c, &serviceInfo.Status)
delta.Entity = serviceInfo
}
deltas[i] = delta
}
}
// The testChange* funcs are extracted so the test cases can be used
// to test both the allWatcher and allEnvWatcher.
func testChangeAnnotations(c *gc.C, runChangeTests func(*gc.C, []changeTestFunc)) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no annotation in state, no annotation in store -> do nothing",
change: watcher.Change{
C: "annotations",
Id: st.docID("m#0"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "annotation is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.AnnotationInfo{
EnvUUID: st.EnvironUUID(),
Tag: "machine-0",
}},
change: watcher.Change{
C: "annotations",
Id: st.docID("m#0"),
}}
},
func(c *gc.C, st *State) changeTestCase {
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = st.SetAnnotations(m, map[string]string{"foo": "bar", "arble": "baz"})
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "annotation is added if it's in backing but not in Store",
change: watcher.Change{
C: "annotations",
Id: st.docID("m#0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.AnnotationInfo{
EnvUUID: st.EnvironUUID(),
Tag: "machine-0",
Annotations: map[string]string{"foo": "bar", "arble": "baz"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = st.SetAnnotations(m, map[string]string{
"arble": "khroomph",
"pretty": "",
"new": "attr",
})
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "annotation is updated if it's in backing and in multiwatcher.Store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.AnnotationInfo{
EnvUUID: st.EnvironUUID(),
Tag: "machine-0",
Annotations: map[string]string{
"arble": "baz",
"foo": "bar",
"pretty": "polly",
},
}},
change: watcher.Change{
C: "annotations",
Id: st.docID("m#0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.AnnotationInfo{
EnvUUID: st.EnvironUUID(),
Tag: "machine-0",
Annotations: map[string]string{
"arble": "khroomph",
"new": "attr",
}}}}
},
}
runChangeTests(c, changeTestFuncs)
}
func testChangeMachines(c *gc.C, runChangeTests func(*gc.C, []changeTestFunc)) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no machine in state -> do nothing",
change: watcher.Change{
C: "statuses",
Id: st.docID("m#0"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no machine in state, no machine in store -> do nothing",
change: watcher.Change{
C: "machines",
Id: st.docID("1"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "machine is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "1",
}},
change: watcher.Change{
C: "machines",
Id: st.docID("1"),
}}
},
func(c *gc.C, st *State) changeTestCase {
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = m.SetStatus(StatusError, "failure", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "machine is added if it's in backing but not in Store",
change: watcher.Change{
C: "machines",
Id: st.docID("0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "quantal",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HasVote: false,
WantsVote: false,
}}}
},
func(c *gc.C, st *State) changeTestCase {
m, err := st.AddMachine("trusty", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = m.SetProvisioned("i-0", "bootstrap_nonce", nil)
c.Assert(err, jc.ErrorIsNil)
err = m.SetSupportedContainers([]instance.ContainerType{instance.LXC})
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "machine is updated if it's in backing and in Store",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("error"),
StatusInfo: "another failure",
StatusData: map[string]interface{}{},
},
},
change: watcher.Change{
C: "machines",
Id: st.docID("0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
InstanceId: "i-0",
Status: multiwatcher.Status("error"),
StatusInfo: "another failure",
StatusData: map[string]interface{}{},
Life: multiwatcher.Life("alive"),
Series: "trusty",
Jobs: []multiwatcher.MachineJob{JobHostUnits.ToParams()},
Addresses: []network.Address{},
HardwareCharacteristics: &instance.HardwareCharacteristics{},
SupportedContainers: []instance.ContainerType{instance.LXC},
SupportedContainersKnown: true,
}}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no change if status is not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("m#0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
}}}
},
func(c *gc.C, st *State) changeTestCase {
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = m.SetStatus(StatusStarted, "", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "status is changed if the machine exists in the store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("m#0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
Status: multiwatcher.Status("started"),
StatusData: make(map[string]interface{}),
}}}
},
}
runChangeTests(c, changeTestFuncs)
}
func testChangeRelations(c *gc.C, owner names.UserTag, runChangeTests func(*gc.C, []changeTestFunc)) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no relation in state, no service in store -> do nothing",
change: watcher.Change{
C: "relations",
Id: st.docID("logging:logging-directory wordpress:logging-dir"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "relation is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.RelationInfo{
EnvUUID: st.EnvironUUID(),
Key: "logging:logging-directory wordpress:logging-dir",
}},
change: watcher.Change{
C: "relations",
Id: st.docID("logging:logging-directory wordpress:logging-dir"),
}}
},
func(c *gc.C, st *State) changeTestCase {
AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
AddTestingService(c, st, "logging", AddTestingCharm(c, st, "logging"), owner)
eps, err := st.InferEndpoints("logging", "wordpress")
c.Assert(err, jc.ErrorIsNil)
_, err = st.AddRelation(eps...)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "relation is added if it's in backing but not in Store",
change: watcher.Change{
C: "relations",
Id: st.docID("logging:logging-directory wordpress:logging-dir"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.RelationInfo{
EnvUUID: st.EnvironUUID(),
Key: "logging:logging-directory wordpress:logging-dir",
Endpoints: []multiwatcher.Endpoint{
{ServiceName: "logging", Relation: charm.Relation{Name: "logging-directory", Role: "requirer", Interface: "logging", Optional: false, Limit: 1, Scope: "container"}},
{ServiceName: "wordpress", Relation: charm.Relation{Name: "logging-dir", Role: "provider", Interface: "logging", Optional: false, Limit: 0, Scope: "container"}}},
}}}
},
}
runChangeTests(c, changeTestFuncs)
}
func testChangeServices(c *gc.C, owner names.UserTag, runChangeTests func(*gc.C, []changeTestFunc)) {
// TODO(wallyworld) - add test for changing service status when that is implemented
changeTestFuncs := []changeTestFunc{
// Services.
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no service in state, no service in store -> do nothing",
change: watcher.Change{
C: "services",
Id: st.docID("wordpress"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "service is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
},
},
change: watcher.Change{
C: "services",
Id: st.docID("wordpress"),
}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
err := wordpress.SetExposed()
c.Assert(err, jc.ErrorIsNil)
err = wordpress.SetMinUnits(42)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "service is added if it's in backing but not in Store",
change: watcher.Change{
C: "services",
Id: st.docID("wordpress"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Exposed: true,
CharmURL: "local:quantal/quantal-wordpress-3",
OwnerTag: owner.String(),
Life: multiwatcher.Life("alive"),
MinUnits: 42,
Config: charm.Settings{},
Status: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
setServiceConfigAttr(c, svc, "blog-title", "boring")
return changeTestCase{
about: "service is updated if it's in backing and in multiwatcher.Store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Exposed: true,
CharmURL: "local:quantal/quantal-wordpress-3",
MinUnits: 47,
Constraints: constraints.MustParse("mem=99M"),
Config: charm.Settings{"blog-title": "boring"},
}},
change: watcher.Change{
C: "services",
Id: st.docID("wordpress"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
CharmURL: "local:quantal/quantal-wordpress-3",
OwnerTag: owner.String(),
Life: multiwatcher.Life("alive"),
Constraints: constraints.MustParse("mem=99M"),
Config: charm.Settings{"blog-title": "boring"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
setServiceConfigAttr(c, svc, "blog-title", "boring")
return changeTestCase{
about: "service re-reads config when charm URL changes",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
// Note: CharmURL has a different revision number from
// the wordpress revision in the testing repo.
CharmURL: "local:quantal/quantal-wordpress-2",
Config: charm.Settings{"foo": "bar"},
}},
change: watcher.Change{
C: "services",
Id: st.docID("wordpress"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
CharmURL: "local:quantal/quantal-wordpress-3",
OwnerTag: owner.String(),
Life: multiwatcher.Life("alive"),
Config: charm.Settings{"blog-title": "boring"},
}}}
},
// Settings.
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no service in state -> do nothing",
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no change if service is not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
}},
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
},
expectContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "dummy-service", AddTestingCharm(c, st, "dummy"), owner)
setServiceConfigAttr(c, svc, "username", "foo")
setServiceConfigAttr(c, svc, "outlook", "foo@bar")
return changeTestCase{
about: "service config is changed if service exists in the store with the same URL",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
}},
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"username": "foo", "outlook": "foo@bar"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "dummy-service", AddTestingCharm(c, st, "dummy"), owner)
setServiceConfigAttr(c, svc, "username", "foo")
setServiceConfigAttr(c, svc, "outlook", "foo@bar")
setServiceConfigAttr(c, svc, "username", nil)
return changeTestCase{
about: "service config is changed after removing of a setting",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"username": "foo", "outlook": "foo@bar"},
}},
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"outlook": "foo@bar"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
testCharm := AddCustomCharm(
c, st, "dummy",
"config.yaml", dottedConfig,
"quantal", 1)
svc := AddTestingService(c, st, "dummy-service", testCharm, owner)
setServiceConfigAttr(c, svc, "key.dotted", "foo")
return changeTestCase{
about: "service config is unescaped when reading from the backing store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"key.dotted": "bar"},
}},
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-1",
Config: charm.Settings{"key.dotted": "foo"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "dummy-service", AddTestingCharm(c, st, "dummy"), owner)
setServiceConfigAttr(c, svc, "username", "foo")
return changeTestCase{
about: "service config is unchanged if service exists in the store with a different URL",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-2", // Note different revno.
Config: charm.Settings{"username": "bar"},
}},
change: watcher.Change{
C: "settings",
Id: st.docID("s#dummy-service#local:quantal/quantal-dummy-1"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "dummy-service",
CharmURL: "local:quantal/quantal-dummy-2",
Config: charm.Settings{"username": "bar"},
}}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "non-service config change is ignored",
change: watcher.Change{
C: "settings",
Id: st.docID("m#0"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "service config change with no charm url is ignored",
change: watcher.Change{
C: "settings",
Id: st.docID("s#foo"),
}}
},
}
runChangeTests(c, changeTestFuncs)
}
func testChangeServicesConstraints(c *gc.C, owner names.UserTag, runChangeTests func(*gc.C, []changeTestFunc)) {
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no service in state -> do nothing",
change: watcher.Change{
C: "constraints",
Id: st.docID("s#wordpress"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no change if service is not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=99M"),
}},
change: watcher.Change{
C: "constraints",
Id: st.docID("s#wordpress"),
},
expectContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=99M"),
}}}
},
func(c *gc.C, st *State) changeTestCase {
svc := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
err := svc.SetConstraints(constraints.MustParse("mem=4G arch=amd64"))
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "status is changed if the service exists in the store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=99M cpu-cores=2 cpu-power=4"),
}},
change: watcher.Change{
C: "constraints",
Id: st.docID("s#wordpress"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Constraints: constraints.MustParse("mem=4G arch=amd64"),
}}}
},
}
runChangeTests(c, changeTestFuncs)
}
func testChangeUnits(c *gc.C, owner names.UserTag, runChangeTests func(*gc.C, []changeTestFunc)) {
now := time.Now()
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no unit in state, no unit in store -> do nothing",
change: watcher.Change{
C: "units",
Id: st.docID("1"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "unit is removed if it's not in backing",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/1",
},
},
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/1"),
}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("tcp", 12345)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("udp", 54321)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPorts("tcp", 5555, 5558)
c.Assert(err, jc.ErrorIsNil)
err = u.SetAgentStatus(StatusError, "failure", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit is added if it's in backing but not in Store",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
Ports: []network.Port{
{"tcp", 5555},
{"tcp", 5556},
{"tcp", 5557},
{"tcp", 5558},
{"tcp", 12345},
{"udp", 54321},
},
PortRanges: []network.PortRange{
{5555, 5558, "tcp"},
{12345, 12345, "tcp"},
{54321, 54321, "udp"},
},
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("udp", 17070)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit is updated if it's in backing and in multiwatcher.Store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Status: multiwatcher.Status("error"),
StatusInfo: "another failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "another failure",
Data: map[string]interface{}{},
Since: &now,
},
Ports: []network.Port{{"udp", 17070}},
PortRanges: []network.PortRange{{17070, 17070, "udp"}},
}},
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
Ports: []network.Port{{"udp", 17070}},
PortRanges: []network.PortRange{{17070, 17070, "udp"}},
Status: multiwatcher.Status("error"),
StatusInfo: "another failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "another failure",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("tcp", 4242)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit info is updated if a port is opened on the machine it is placed in",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
StatusData: map[string]interface{}{},
},
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
StatusData: map[string]interface{}{},
},
},
change: watcher.Change{
C: openedPortsC,
Id: st.docID("m#0#n#juju-public"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Ports: []network.Port{{"tcp", 4242}},
PortRanges: []network.PortRange{{4242, 4242, "tcp"}},
StatusData: map[string]interface{}{},
},
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
StatusData: map[string]interface{}{},
},
}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPorts("tcp", 21, 22)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit is created if a port is opened on the machine it is placed in",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
},
},
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Data: map[string]interface{}{},
},
Ports: []network.Port{{"tcp", 21}, {"tcp", 22}},
PortRanges: []network.PortRange{{21, 22, "tcp"}},
},
&multiwatcher.MachineInfo{
EnvUUID: st.EnvironUUID(),
Id: "0",
},
}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("tcp", 12345)
c.Assert(err, jc.ErrorIsNil)
publicAddress := network.NewScopedAddress("public", network.ScopePublic)
privateAddress := network.NewScopedAddress("private", network.ScopeCloudLocal)
err = m.SetProviderAddresses(publicAddress, privateAddress)
c.Assert(err, jc.ErrorIsNil)
err = u.SetAgentStatus(StatusError, "failure", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit addresses are read from the assigned machine for recent Juju releases",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
PublicAddress: "public",
PrivateAddress: "private",
MachineId: "0",
Ports: []network.Port{{"tcp", 12345}},
PortRanges: []network.PortRange{{12345, 12345, "tcp"}},
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no unit in state -> do nothing",
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0"),
}}
},
func(c *gc.C, st *State) changeTestCase {
return changeTestCase{
about: "no change if status is not in backing",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
Since: &now,
},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = u.SetAgentStatus(StatusIdle, "", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "status is changed if the unit exists in the store",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("started"),
StatusInfo: "",
StatusData: map[string]interface{}{},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "maintenance",
Message: "working",
Data: map[string]interface{}{},
Since: &now,
},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("started"),
StatusInfo: "",
StatusData: make(map[string]interface{}),
WorkloadStatus: multiwatcher.StatusInfo{
Current: "maintenance",
Message: "working",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = u.SetAgentStatus(StatusIdle, "", nil)
c.Assert(err, jc.ErrorIsNil)
err = u.SetStatus(StatusMaintenance, "doing work", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "unit status is changed if the agent comes off error state",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("error"),
StatusInfo: "failure",
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
Since: &now,
},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("started"),
StatusInfo: "",
StatusData: make(map[string]interface{}),
WorkloadStatus: multiwatcher.StatusInfo{
Current: "maintenance",
Message: "doing work",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = u.SetAgentStatus(StatusError, "hook error", map[string]interface{}{
"1st-key": "one",
"2nd-key": 2,
"3rd-key": true,
})
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "status is changed with additional status data",
initialContents: []multiwatcher.EntityInfo{&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("started"),
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "active",
Since: &now,
},
}},
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("error"),
StatusInfo: "hook error",
StatusData: map[string]interface{}{
"1st-key": "one",
"2nd-key": 2,
"3rd-key": true,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "hook error",
Data: map[string]interface{}{
"1st-key": "one",
"2nd-key": 2,
"3rd-key": true,
},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
err = u.SetStatus(StatusActive, "", nil)
c.Assert(err, jc.ErrorIsNil)
return changeTestCase{
about: "service status is changed if the unit status changes",
initialContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("error"),
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
Since: &now,
},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
Since: &now,
},
},
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Status: multiwatcher.StatusInfo{
Current: "error",
Message: "failure",
Data: map[string]interface{}{},
Since: &now,
},
},
},
change: watcher.Change{
C: "statuses",
Id: st.docID("u#wordpress/0#charm"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Status: multiwatcher.Status("started"),
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "active",
Message: "",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "idle",
Message: "",
Data: map[string]interface{}{},
},
},
&multiwatcher.ServiceInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress",
Status: multiwatcher.StatusInfo{
Current: "active",
Message: "",
Data: map[string]interface{}{},
},
},
}}
},
}
runChangeTests(c, changeTestFuncs)
}
// initFlag helps to control the different test scenarios.
type initFlag int
const (
noFlag initFlag = 0
assignUnit initFlag = 1
openPorts initFlag = 2
closePorts initFlag = 4
)
func testChangeUnitsNonNilPorts(c *gc.C, owner names.UserTag, runChangeTests func(*gc.C, []changeTestFunc)) {
initEnv := func(c *gc.C, st *State, flag initFlag) {
wordpress := AddTestingService(c, st, "wordpress", AddTestingCharm(c, st, "wordpress"), owner)
u, err := wordpress.AddUnit()
c.Assert(err, jc.ErrorIsNil)
m, err := st.AddMachine("quantal", JobHostUnits)
c.Assert(err, jc.ErrorIsNil)
if flag&assignUnit != 0 {
// Assign the unit.
err = u.AssignToMachine(m)
c.Assert(err, jc.ErrorIsNil)
}
if flag&openPorts != 0 {
// Add a network to the machine and open a port.
publicAddress := network.NewScopedAddress("1.2.3.4", network.ScopePublic)
privateAddress := network.NewScopedAddress("4.3.2.1", network.ScopeCloudLocal)
err = m.SetProviderAddresses(publicAddress, privateAddress)
c.Assert(err, jc.ErrorIsNil)
err = u.OpenPort("tcp", 12345)
if flag&assignUnit != 0 {
c.Assert(err, jc.ErrorIsNil)
} else {
c.Assert(err, gc.ErrorMatches, `cannot open ports 12345-12345/tcp \("wordpress/0"\) for unit "wordpress/0": .*`)
c.Assert(err, jc.Satisfies, errors.IsNotAssigned)
}
}
if flag&closePorts != 0 {
// Close the port again (only if been opened before).
err = u.ClosePort("tcp", 12345)
c.Assert(err, jc.ErrorIsNil)
}
}
changeTestFuncs := []changeTestFunc{
func(c *gc.C, st *State) changeTestCase {
initEnv(c, st, assignUnit)
return changeTestCase{
about: "don't open ports on unit",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
Ports: []network.Port{},
PortRanges: []network.PortRange{},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
initEnv(c, st, assignUnit|openPorts)
return changeTestCase{
about: "open a port on unit",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
PublicAddress: "1.2.3.4",
PrivateAddress: "4.3.2.1",
Ports: []network.Port{{"tcp", 12345}},
PortRanges: []network.PortRange{{12345, 12345, "tcp"}},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
initEnv(c, st, assignUnit|openPorts|closePorts)
return changeTestCase{
about: "open a port on unit and close it again",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
MachineId: "0",
PublicAddress: "1.2.3.4",
PrivateAddress: "4.3.2.1",
Ports: []network.Port{},
PortRanges: []network.PortRange{},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
func(c *gc.C, st *State) changeTestCase {
initEnv(c, st, openPorts)
return changeTestCase{
about: "open ports on an unassigned unit",
change: watcher.Change{
C: "units",
Id: st.docID("wordpress/0"),
},
expectContents: []multiwatcher.EntityInfo{
&multiwatcher.UnitInfo{
EnvUUID: st.EnvironUUID(),
Name: "wordpress/0",
Service: "wordpress",
Series: "quantal",
Ports: []network.Port{},
PortRanges: []network.PortRange{},
Status: "pending",
StatusData: map[string]interface{}{},
WorkloadStatus: multiwatcher.StatusInfo{
Current: "unknown",
Message: "Waiting for agent initialization to finish",
Data: map[string]interface{}{},
},
AgentStatus: multiwatcher.StatusInfo{
Current: "allocating",
Message: "",
Data: map[string]interface{}{},
},
}}}
},
}
runChangeTests(c, changeTestFuncs)
}
func newTestAllWatcher(st *State, c *gc.C) *testWatcher {
return newTestWatcher(newAllWatcherStateBacking(st), st, c)
}
func newTestAllEnvWatcher(st *State, c *gc.C) *testWatcher {
return newTestWatcher(newAllEnvWatcherStateBacking(st), st, c)
}
type testWatcher struct {
st *State
c *gc.C
b Backing
sm *storeManager
w *Multiwatcher
deltas chan []multiwatcher.Delta
}
func newTestWatcher(b Backing, st *State, c *gc.C) *testWatcher {
sm := newStoreManager(b)
w := NewMultiwatcher(sm)
tw := &testWatcher{
st: st,
c: c,
b: b,
sm: sm,
w: w,
deltas: make(chan []multiwatcher.Delta),
}
go func() {
for {
deltas, err := tw.w.Next()
if err != nil {
break
}
tw.deltas <- deltas
}
}()
return tw
}
func (tw *testWatcher) Next(timeout time.Duration) []multiwatcher.Delta {
select {
case d := <-tw.deltas:
return d
case <-time.After(timeout):
return nil
}
}
func (tw *testWatcher) NumDeltas() int {
count := 0
tw.st.StartSync()
for {
// TODO(mjs) - this is somewhat fragile. There are no
// guarentees that the watcher will be able to return deltas
// in ShortWait time.
deltas := len(tw.Next(testing.ShortWait))
if deltas == 0 {
break
}
count += deltas
}
return count
}
func (tw *testWatcher) All(expectedCount int) []multiwatcher.Delta {
var allDeltas []multiwatcher.Delta
tw.st.StartSync()
// Wait up to LongWait for the expected deltas to arrive, unless
// we don't expect any (then just wait for ShortWait).
maxDuration := testing.LongWait
if expectedCount <= 0 {
maxDuration = testing.ShortWait
}
now := time.Now()
maxTime := now.Add(maxDuration)
for {
remaining := maxTime.Sub(now)
if remaining < time.Duration(0) {
break // timed out
}
deltas := tw.Next(remaining)
if len(deltas) > 0 {
allDeltas = append(allDeltas, deltas...)
if len(allDeltas) >= expectedCount {
break
}
}
now = time.Now()
}
return allDeltas
}
func (tw *testWatcher) Stop() {
tw.c.Assert(tw.w.Stop(), jc.ErrorIsNil)
tw.c.Assert(tw.sm.Stop(), jc.ErrorIsNil)
tw.c.Assert(tw.b.Release(), jc.ErrorIsNil)
}
func (tw *testWatcher) AssertNoChange() {
tw.c.Assert(tw.NumDeltas(), gc.Equals, 0)
}
func (tw *testWatcher) AssertChanges() {
tw.c.Assert(tw.NumDeltas(), jc.GreaterThan, 0)
}
type entityInfoSlice []multiwatcher.EntityInfo
func (s entityInfoSlice) Len() int { return len(s) }
func (s entityInfoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s entityInfoSlice) Less(i, j int) bool {
id0, id1 := s[i].EntityId(), s[j].EntityId()
if id0.Kind != id1.Kind {
return id0.Kind < id1.Kind
}
if id0.EnvUUID != id1.EnvUUID {
return id0.EnvUUID < id1.EnvUUID
}
return id0.Id < id1.Id
}
func checkDeltasEqual(c *gc.C, d0, d1 []multiwatcher.Delta) {
// Deltas are returned in arbitrary order, so we compare them as maps.
c.Check(deltaMap(d0), jc.DeepEquals, deltaMap(d1))
}
func deltaMap(deltas []multiwatcher.Delta) map[interface{}]multiwatcher.EntityInfo {
m := make(map[interface{}]multiwatcher.EntityInfo)
for _, d := range deltas {
id := d.Entity.EntityId()
if d.Removed {
m[id] = nil
} else {
m[id] = d.Entity
}
}
return m
}
func makeActionInfo(a *Action, st *State) multiwatcher.ActionInfo {
results, message := a.Results()
return multiwatcher.ActionInfo{
EnvUUID: st.EnvironUUID(),
Id: a.Id(),
Receiver: a.Receiver(),
Name: a.Name(),
Parameters: a.Parameters(),
Status: string(a.Status()),
Message: message,
Results: results,
Enqueued: a.Enqueued(),
Started: a.Started(),
Completed: a.Completed(),
}
}
func jcDeepEqualsCheck(c *gc.C, got, want interface{}) bool {
ok, err := jc.DeepEqual(got, want)
if ok {
c.Check(err, jc.ErrorIsNil)
}
return ok
}
// assertEntitiesEqual is a specialised version of the typical
// jc.DeepEquals check that provides more informative output when
// comparing EntityInfo slices.
func assertEntitiesEqual(c *gc.C, got, want []multiwatcher.EntityInfo) {
if jcDeepEqualsCheck(c, got, want) {
return
}
if len(got) != len(want) {
c.Errorf("entity length mismatch; got %d; want %d", len(got), len(want))
} else {
c.Errorf("entity contents mismatch; same length %d", len(got))
}
// Lets construct a decent output.
var errorOutput string
errorOutput = "\ngot: \n"
for _, e := range got {
errorOutput += fmt.Sprintf(" %T %#v\n", e, e)
}
errorOutput += "expected: \n"
for _, e := range want {
errorOutput += fmt.Sprintf(" %T %#v\n", e, e)
}
c.Errorf(errorOutput)
var firstDiffError string
if len(got) == len(want) {
for i := 0; i < len(got); i++ {
g := got[i]
w := want[i]
if !jcDeepEqualsCheck(c, g, w) {
firstDiffError += "\n"
firstDiffError += fmt.Sprintf("first difference at position %d\n", i)
firstDiffError += "got:\n"
firstDiffError += fmt.Sprintf(" %T %#v\n", g, g)
firstDiffError += "expected:\n"
firstDiffError += fmt.Sprintf(" %T %#v\n", w, w)
break
}
}
c.Errorf(firstDiffError)
}
c.FailNow()
}
func deepEqual(c *gc.C, got, want interface{}) bool {
same, err := jc.DeepEqual(got, want)
return err == nil && same
}
|
cloud-green/juju
|
state/allwatcher_internal_test.go
|
GO
|
agpl-3.0
| 96,772
|
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NGAP-IEs"
* found in "../support/ngap-r16.4.0/38413-g40.asn"
* `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-BER -no-gen-XER -no-gen-OER -no-gen-UPER`
*/
#ifndef _NGAP_PDUSessionResourceSetupItemHOReq_H_
#define _NGAP_PDUSessionResourceSetupItemHOReq_H_
#include <asn_application.h>
/* Including external dependencies */
#include "NGAP_PDUSessionID.h"
#include "NGAP_S-NSSAI.h"
#include <OCTET_STRING.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declarations */
struct NGAP_ProtocolExtensionContainer;
/* NGAP_PDUSessionResourceSetupItemHOReq */
typedef struct NGAP_PDUSessionResourceSetupItemHOReq {
NGAP_PDUSessionID_t pDUSessionID;
NGAP_S_NSSAI_t s_NSSAI;
OCTET_STRING_t handoverRequestTransfer;
struct NGAP_ProtocolExtensionContainer *iE_Extensions; /* OPTIONAL */
/*
* This type is extensible,
* possible extensions are below.
*/
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} NGAP_PDUSessionResourceSetupItemHOReq_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_NGAP_PDUSessionResourceSetupItemHOReq;
extern asn_SEQUENCE_specifics_t asn_SPC_NGAP_PDUSessionResourceSetupItemHOReq_specs_1;
extern asn_TYPE_member_t asn_MBR_NGAP_PDUSessionResourceSetupItemHOReq_1[4];
#ifdef __cplusplus
}
#endif
#endif /* _NGAP_PDUSessionResourceSetupItemHOReq_H_ */
#include <asn_internal.h>
|
acetcom/nextepc
|
lib/asn1c/ngap/NGAP_PDUSessionResourceSetupItemHOReq.h
|
C
|
agpl-3.0
| 1,508
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Product GTIN module for Odoo
# Copyright (C) 2004-2011 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2011 Camptocamp (<http://www.camptocamp.at>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
_logger = logging.getLogger(__name__)
from openerp.osv import orm, fields
import operator
CONSTRAINT_MESSAGE = 'Error: Invalid EAN/GTIN code'
HELP_MESSAGE = ("EAN8 EAN13 UPC JPC GTIN \n"
"http://en.wikipedia.org/wiki/Global_Trade_Item_Number")
def is_pair(x):
return not x % 2
def check_ean8(eancode):
"""Check if the given ean code answer ean8 requirements
For more details: http://en.wikipedia.org/wiki/EAN-8
:param eancode: string, ean-8 code
:return: boolean
"""
if not eancode or not eancode.isdigit():
return False
if not len(eancode) == 8:
_logger.warn('Ean8 code has to have a length of 8 characters.')
return False
sum = 0
ean_len = int(len(eancode))
for i in range(ean_len-1):
if is_pair(i):
sum += 3 * int(eancode[i])
else:
sum += int(eancode[i])
check = 10 - operator.mod(sum, 10)
if check == 10:
check = 0
return check == int(eancode[-1])
def check_upc(upccode):
"""Check if the given code answers upc requirements
For more details:
http://en.wikipedia.org/wiki/Universal_Product_Code
:param upccode: string, upc code
:return: bool
"""
if not upccode or not upccode.isdigit():
return False
if not len(upccode) == 12:
_logger.warn('UPC code has to have a length of 12 characters.')
return False
sum_pair = 0
ean_len = int(len(upccode))
for i in range(ean_len-1):
if is_pair(i):
sum_pair += int(upccode[i])
sum = sum_pair * 3
for i in range(ean_len-1):
if not is_pair(i):
sum += int(upccode[i])
check = ((sum/10 + 1) * 10) - sum
return check == int(upccode[-1])
def check_ean13(eancode):
"""Check if the given ean code answer ean13 requirements
For more details:
http://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29
:param eancode: string, ean-13 code
:return: boolean
"""
if not eancode or not eancode.isdigit():
return False
if not len(eancode) == 13:
_logger.warn('Ean13 code has to have a length of 13 characters.')
return False
sum = 0
ean_len = int(len(eancode))
for i in range(ean_len-1):
pos = int(ean_len-2-i)
if is_pair(i):
sum += 3 * int(eancode[pos])
else:
sum += int(eancode[pos])
check = 10 - operator.mod(sum, 10)
if check == 10:
check = 0
return check == int(eancode[-1])
def check_ean11(eancode):
pass
def check_gtin14(eancode):
pass
DICT_CHECK_EAN = {8: check_ean8,
11: check_ean11,
12: check_upc,
13: check_ean13,
14: check_gtin14,
}
def check_ean(eancode):
if not eancode:
return True
if not len(eancode) in DICT_CHECK_EAN:
return False
try:
int(eancode)
except:
return False
return DICT_CHECK_EAN[len(eancode)](eancode)
class product_product(orm.Model):
_inherit = "product.product"
def _check_ean_key(self, cr, uid, ids):
for rec in self.browse(cr, uid, ids):
if not check_ean(rec.ean13):
return False
return True
_columns = {
'ean13': fields.char(
'EAN/GTIN', size=14,
help="Code for %s" % HELP_MESSAGE),
}
_constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean13'])]
class product_packaging(orm.Model):
_inherit = "product.packaging"
def _check_ean_key(self, cr, uid, ids):
for rec in self.browse(cr, uid, ids):
if not check_ean(rec.ean):
return False
return True
_columns = {
'ean': fields.char(
'EAN', size=14,
help='Barcode number for %s' % HELP_MESSAGE),
}
_constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean'])]
class res_partner(orm.Model):
_inherit = "res.partner"
def _check_ean_key(self, cr, uid, ids):
for rec in self.browse(cr, uid, ids):
if not check_ean(rec.ean13):
return False
return True
_columns = {
'ean13': fields.char(
'EAN', size=14,
help="Code for %s" % HELP_MESSAGE),
}
_constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean13'])]
|
cgstudiomap/cgstudiomap
|
main/parts/product-attribute/product_gtin/product_gtin.py
|
Python
|
agpl-3.0
| 5,465
|
import { combineReducers } from 'redux'
const FETCH_ENTRIES = 'FETCH_ENTRIES'
const RECEIVE_ENTRIES = 'RECEIVE_ENTRIES'
const RECEIVE_MORE_ENTRIES = 'RECEIVE_MORE_ENTRIES'
const RECEIVE_ERROR = 'RECEIVE_ERROR'
const INSERT_ENTRIES = 'INSERT_ENTRIES'
const UPDATE_ENTRIES = 'UPDATE_ENTRIES'
const DELETE_ENTRY = 'DELETE_ENTRY'
const EMIT_ERROR = 'EMIT_ERROR'
const entries = (state = [], action) => {
switch (action.type) {
case RECEIVE_MORE_ENTRIES:
return [...state, ...action.entries]
case RECEIVE_ENTRIES:
return action.entries
case INSERT_ENTRIES:
return [...action.entries, ...state]
case UPDATE_ENTRIES:
return state.map(entry => {
let updatedEntry = action.entries.find(
actionEntry => actionEntry._id === entry._id
)
return updatedEntry || entry
})
case DELETE_ENTRY:
// TODO: quick and dirty fix for removeFromAlbum (we got IDs instead of photos)
const id =
typeof action.entity === 'object'
? action.entity.id || action.entity._id
: action.entity
// TODO: why is the back sending an id prop instead of a _id prop here???
const idx = state.findIndex(e => e._id === id)
if (idx === -1) return state
return [...state.slice(0, idx), ...state.slice(idx + 1)]
default:
return state
}
}
const fetchStatus = (state = 'pending', action) => {
switch (action.type) {
case FETCH_ENTRIES:
return 'loading'
case RECEIVE_ENTRIES:
return 'loaded'
case RECEIVE_ERROR:
return 'failed'
default:
return state
}
}
const lastFetch = (state = null, action) => {
switch (action.type) {
case RECEIVE_ENTRIES:
case RECEIVE_MORE_ENTRIES:
return Date.now()
default:
return state
}
}
const hasMore = (state = false, action) => {
switch (action.type) {
case RECEIVE_ENTRIES:
case RECEIVE_MORE_ENTRIES:
return action.next !== undefined ? action.next : state
default:
return state
}
}
const index = (state = null, action) => {
switch (action.type) {
case RECEIVE_ENTRIES:
return action.index !== undefined ? action.index : state
default:
return state
}
}
const listReducer = combineReducers({
entries,
fetchStatus,
lastFetch,
hasMore,
index
})
const listsReducer = (state = {}, action) => {
switch (action.type) {
case FETCH_ENTRIES:
case RECEIVE_ENTRIES:
case RECEIVE_MORE_ENTRIES:
case RECEIVE_ERROR:
case INSERT_ENTRIES:
case UPDATE_ENTRIES:
case DELETE_ENTRY:
return Object.assign({}, state, {
[action.name]: listReducer(state[action.name] || {}, action)
})
default:
return state
}
}
export default listsReducer
export const createFetchAction = (listName, saga) => {
return (...args) => {
return (dispatch, getState) => {
let fetchingMoreEntries = false
const existingList = getList(getState(), listName)
if (existingList) {
const { fetchStatus, hasMore } = existingList
fetchingMoreEntries = fetchStatus === 'loaded' && hasMore === true
}
if (!fetchingMoreEntries) {
dispatch({ type: FETCH_ENTRIES, name: listName })
}
return saga(...args)
.then(resp => {
return fetchingMoreEntries && resp.skip !== 0
? dispatch({ type: RECEIVE_MORE_ENTRIES, name: listName, ...resp })
: dispatch({ type: RECEIVE_ENTRIES, name: listName, ...resp })
})
.catch(error =>
dispatch({ type: RECEIVE_ERROR, name: listName, error })
)
}
}
}
const shouldRefetch = list => {
if (!list) {
return true
}
// here we could add conditions so that we don't refetch a list fetched 30s ago
return true
}
export const createFetchIfNeededAction = (listName, saga) => {
return (...args) => {
return (dispatch, getState) => {
const existingList = getList(getState(), listName)
if (existingList && !shouldRefetch(existingList)) {
return Promise.resolve(existingList)
}
return dispatch(createFetchAction(listName, saga)(...args))
}
}
}
export const createInsertAction = (listName, saga) => {
return (...args) => {
return (dispatch, getState) => {
const existingList = getList(getState(), listName)
return saga(...args).then(resp => {
if (existingList) {
return dispatch(insertAction(listName, resp))
} else {
return resp
}
})
}
}
}
export const createUpdateAction = (listName, saga) => {
return (...args) => {
return (dispatch, getState) => {
const existingList = getList(getState(), listName)
return saga(...args).then(resp => {
if (existingList) {
return dispatch(updateAction(listName, resp))
} else {
return resp
}
})
}
}
}
export const createDeleteAction = (listName, saga) => {
return (...args) => {
return (dispatch, getState) => {
const existingList = getList(getState(), listName)
return saga(...args).then(resp => {
if (existingList) {
resp.entries.forEach(e => dispatch(deleteAction(listName, e)))
}
return resp
})
}
}
}
export const errorAction = (listName, error) => ({
type: EMIT_ERROR,
name: listName,
error,
alert: {
message: error.message || error
}
})
// TODO: remove the discrepancy between insert and deleteAction inputs (full response with entries vs single entry)
export const insertAction = (listName, resp) => ({
type: INSERT_ENTRIES,
name: listName,
...resp
})
export const updateAction = (listName, resp) => ({
type: UPDATE_ENTRIES,
name: listName,
...resp
})
export const deleteAction = (listName, entity) => ({
type: DELETE_ENTRY,
name: listName,
entity
})
export const getList = (state, name) => state.lists[name]
|
enguerran/cozy-files-v3
|
src/photos/ducks/lists/index.js
|
JavaScript
|
agpl-3.0
| 5,918
|
<!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Freedomotic - Open IoT Framework</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css ./styles/main.css -->
<link rel="stylesheet" href="./styles/main.css">
<!-- endbuild -->
<!-- build:js ./js/webcomponents.js -->
<script src="bower_components/webcomponentsjs/webcomponents.js"></script>
<!-- endbuild -->
<link rel="import" href="./bower_components/polymer/polymer.html">
<link rel="import" href="./bower_components/fd-polymer-i18next-translate/fd-polymer-i18next-translate.html">
<link rel="import" href="./bower_components/core-image/core-image.html">
<link rel="import" href="./bower_components/core-media-query/core-media-query.html">
<link rel="import" href="./bower_components/core-a11y-keys/core-a11y-keys.html">
<link rel="import" href="./bower_components/paper-input/paper-input.html">
<link rel="import" href="./bower_components/paper-button/paper-button.html">
<link rel="import" href="./bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="./bower_components/paper-shadow/paper-shadow.html">
<link rel="import" href="./bower_components/fd-polymer-rest-service/fd-polymer-rest-service.html">
<link rel="import" href="./bower_components/fd-polymer-ws-service/fd-polymer-ws-service.html">
<link rel="import" href="./elements/nautes-pass-dashboard.html">
</head>
<body unresolved>
<template is="auto-binding">
<template id="loginContent">
<div class="logocontainer" self-stretch>
<core-image class="logo" src="images/freedomotic-logo-light-transparent.png" sizing="contain" preload fade></core-image>
</div>
<div layout vertical self-stretch end-justified style="padding:1em 2em;">
<template if="{{!config.api.address}}">
<paper-input-decorator id="addressInput" label="{{'address' | t}}" floatingLabel error="Invalid Address">
<input is="core-input" id="address" value="{{address}}" />
</paper-input-decorator>
</template>
<paper-input id="name" label="{{'name' | t}}" value="{{name}}" floatingLabel></paper-input>
<paper-input-decorator id="passwordInput" label="{{'password' | t}}" floatingLabel error="{{'incorrect_login_msg' | t }}">
<input id="password" is="core-input" value="{{password}}" name="password" type="password" />
</paper-input-decorator>
<template if="{{config.api.ssl == undefined}}">
<core-label center horizontal layout style="margin:1em;">
<div flex>SSL</div>
<paper-checkbox checked="{{ssl}}" for></paper-checkbox>
</core-label>
</template>
<core-label center horizontal layout style="margin:1em;">
<div flex>Remember me</div>
<paper-checkbox id="rememberMe" checked="{{rememberMe}}" for></paper-checkbox>
</core-label>
<template if="{{!config.api.port || !config.api.path}}">
<small style="margin:1em;" on-tap="{{toggleHideAdvanced}}">Show advanced options</small>
</template>
<template if="{{!hideAdvanced}}">
<template if="{{!config.port}}">
<paper-input label="Port" id="port" value="{{port}}" floatingLabel></paper-input>
</template>
<template if="{{!config.api.path}}">
<paper-input label="Path" id="path" value="{{path}}" floatingLabel></paper-input>
</template>
</template>
<paper-button raised style="margin:1em;" on-tap="{{tryLogin}}" id="loginButton">{{'login' | t}}</paper-button>
</div>
</template>
<core-ajax id="config" auto url="./config.json" handleAs="json" on-core-response="{{configChanged}}" ></core-ajax>
<fd-api-settings address="{{address}}" apiVersion="{{path}}" ssl="{{ssl}}" port="{{port}}" apiUrl="{{apiUrl}}" noSave="false" webappConfig="{{config.webapp}}"></fd-api-settings>
<fd-rest-service id="reLogin" fdType="system/info/framework" on-rest-error="{{backToLogin}}" on-rest-response="{{gotoApp}}"></fd-rest-service>
<template if="{{!successLogin }}">
<fd-rest-service id="doLogin" auto="false" method="POST" contentType="application/x-www-form-urlencoded" fdType="users/_/login" on-rest-error="{{backToLogin}}" on-rest-response="{{gotoApp}}" apiUrl="{{apiUrl}}"></fd-rest-service>
<core-media-query query="max-width: 480px" queryMatches="{{smallScreen}}"></core-media-query>
<template if="{{!smallScreen}}">
<core-image class="background" src="{{background}}" sizing="cover" preload fade></core-image>
<div layout horizontal center class="container">
<paper-shadow z="5" class="login" layout vertical center self-center>
<template ref="loginContent" bind></template>
</paper-shadow>
</div>
</template>
<template if="{{smallScreen}}" ref="loginContent"></template>
</template>
<template if="{{successLogin}}">
<fd-rest-service id="prelogout" auto="false" method="POST" fdType="users/_/logout" on-rest-response="{{backToLogin}}"></fd-rest-service>
<nautes-pass-dashboard background="{{background}}" on-logout="{{backToLogin}}"></nautes-pass-dashboard>
</template>
<a href="http://goo.gl/forms/CqZZfBCHNx" target="_blank"><paper-button raised id="feedback"><core-icon icon="bug-report"></core-icon> Bugs?</paper-button></a>
</template>
<script type="text/javascript">
var scope = document.querySelector('template[is=auto-binding]');
scope.preInit = true;
scope.successLogin = false;
scope.backToLogin = function(e) {
// console.log("BACK TO LOGIN", e);
scope.preInit= false;
scope.successLogin = false;
if (e.detail.detail.xhr.status == 0) {
var address = document.querySelector('#addressInput');
if (address) {
address.isInvalid = true;
}
}
else {
var password = document.querySelector('#passwordInput');
if (password) {
password.isInvalid = true;
}
}
// focus on username field
var username = document.querySelector('#name');
if (username) {
username.focus();
}
// cleanup password field
var password = document.querySelector('#password');
if (password) {
//console.log(password);
password.value = "";
}
// block login button fo 3 seconds
var loginButton = document.querySelector('#loginButton');
if (loginButton) {
loginButton.disabled = true;
}
if (loginButton) {
this.async(
function() {
var loginButton = this.$.loginButton;
loginButton.disabled = false;
}, null, 5000);
}
};
scope.gotoApp = function(e) {
//console.log("APPARENTLY IT'S A SUCCESSFUL RESPONSE")
if (e.detail.detail.xhr.status == 0) {
scope.backToLogin(e);
}
else {
// console.log("LOGIN SUCCESS", e);
scope.preInit=false;
scope.successLogin = true;
}
};
scope.hideAdvanced = true;
scope.toggleHideAdvanced = function() {
scope.hideAdvanced = !scope.hideAdvanced;
};
scope.resetValidity = function() {
var address = document.querySelector('#addressInput');
if (!!address){
address.isInvalid = false;
}
var password = document.querySelector('#passwordInput');
if (!!password){
password.isInvalid = false;
}
}
scope.tryLogin = function() {
scope.resetValidity();
// find userAPI
var api = document.querySelector('#doLogin');
api.body = "name=" + scope.name + "&password=" + scope.password + "&rememberMe=" + scope.rememberMe + "&";
api.go();
};
scope.tryLogout = function() {
var api = document.querySelector('#prelogout');
api.go();
};
scope.configChanged = function(response) {
scope.config = response.detail.response;
console.log("CONFIG", scope.config);
scope.address = (!!scope.config.api.address) ? scope.config.api.address : scope.address;
if (scope.address === '$location.hostname$' ) {
scope.address = location.hostname;
}
scope.port = (!!scope.config.api.port) ? scope.config.api.port : scope.port;
scope.path = (!!scope.config.api.path) ? scope.config.api.path : scope.path;
scope.ssl = (scope.config.api.ssl != undefined) ? scope.config.api.ssl : scope.ssl;
scope.background = scope.config.backgrounds[Math.floor((Math.random() * scope.config.backgrounds.length))];
};
document.addEventListener('rest-error', function(e) {
// console.log("ERROR ON A REST CALL", e);
if (e.detail.detail.xhr.status == 401) {
scope.backToLogin(e);
}
});
</script>
</body>
</html>
|
freedomotic/fd-polymer-webapp
|
app/index.html
|
HTML
|
agpl-3.0
| 10,220
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Fri Jul 10 16:42:50 IST 2015 -->
<title>ReloadEmailEvent</title>
<meta name="date" content="2015-07-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ReloadEmailEvent";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ReloadEmailEvent.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/ephesoft/gxt/admin/client/event/ReloadBatchClassEvent.html" title="class in com.ephesoft.gxt.admin.client.event"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/ephesoft/gxt/admin/client/event/ReloadImageEvent.html" title="class in com.ephesoft.gxt.admin.client.event"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/ephesoft/gxt/admin/client/event/ReloadEmailEvent.html" target="_top">Frames</a></li>
<li><a href="ReloadEmailEvent.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_classes_inherited_from_class_com.google.gwt.event.shared.GwtEvent">Nested</a> | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_com.google.web.bindery.event.shared.binder.GenericEvent">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.ephesoft.gxt.admin.client.event</div>
<h2 title="Class ReloadEmailEvent" class="title">Class ReloadEmailEvent</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.web.bindery.event.shared.Event<H></li>
<li>
<ul class="inheritance">
<li>com.google.gwt.event.shared.GwtEvent<com.google.web.bindery.event.shared.binder.impl.GenericEventHandler></li>
<li>
<ul class="inheritance">
<li>com.google.web.bindery.event.shared.binder.GenericEvent</li>
<li>
<ul class="inheritance">
<li>com.ephesoft.gxt.admin.client.event.ReloadEmailEvent</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">ReloadEmailEvent</span>
extends com.google.web.bindery.event.shared.binder.GenericEvent</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_com.google.gwt.event.shared.GwtEvent">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class com.google.gwt.event.shared.GwtEvent</h3>
<code>com.google.gwt.event.shared.GwtEvent.Type<H></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../com/ephesoft/gxt/admin/client/event/ReloadEmailEvent.html#ReloadEmailEvent()">ReloadEmailEvent</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.web.bindery.event.shared.binder.GenericEvent">
<!-- -->
</a>
<h3>Methods inherited from class com.google.web.bindery.event.shared.binder.GenericEvent</h3>
<code>getAssociatedType</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.gwt.event.shared.GwtEvent">
<!-- -->
</a>
<h3>Methods inherited from class com.google.gwt.event.shared.GwtEvent</h3>
<code>getSource</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.web.bindery.event.shared.Event">
<!-- -->
</a>
<h3>Methods inherited from class com.google.web.bindery.event.shared.Event</h3>
<code>toDebugString, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ReloadEmailEvent()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ReloadEmailEvent</h4>
<pre>public ReloadEmailEvent()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ReloadEmailEvent.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/ephesoft/gxt/admin/client/event/ReloadBatchClassEvent.html" title="class in com.ephesoft.gxt.admin.client.event"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/ephesoft/gxt/admin/client/event/ReloadImageEvent.html" title="class in com.ephesoft.gxt.admin.client.event"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/ephesoft/gxt/admin/client/event/ReloadEmailEvent.html" target="_top">Frames</a></li>
<li><a href="ReloadEmailEvent.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_classes_inherited_from_class_com.google.gwt.event.shared.GwtEvent">Nested</a> | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_com.google.web.bindery.event.shared.binder.GenericEvent">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
ungerik/ephesoft
|
Ephesoft_Community_Release_4.0.2.0/javadocs/com/ephesoft/gxt/admin/client/event/ReloadEmailEvent.html
|
HTML
|
agpl-3.0
| 9,910
|
class API::Logger
def initialize(app)
@app = app
end
def call(env)
payload = {
remote_addr: env['REMOTE_ADDR'],
request_method: env['REQUEST_METHOD'],
request_path: env['PATH_INFO'],
request_query: env['QUERY_STRING'],
x_organization: env['HTTP_X_ORGANIZATION']
}
ActiveSupport::Notifications.instrument "grape.request", payload do
@app.call(env).tap do |response|
if env["api.endpoint"] && env["api.endpoint"].params.present?
payload[:params] = env["api.endpoint"].params.to_hash
payload[:params].delete("route_info")
payload[:params].delete("format")
end
payload[:response_status] = response[0]
end
end
end
end
|
Loos/bike_index
|
app/controllers/api/logger.rb
|
Ruby
|
agpl-3.0
| 745
|
import {
DataSourcePluginOptionsEditorProps,
onUpdateDatasourceJsonDataOptionChecked,
SelectableValue,
updateDatasourcePluginJsonDataOption,
} from '@grafana/data';
import { EventsWithValidation, InlineFormLabel, LegacyForms, regexValidation } from '@grafana/ui';
import React, { SyntheticEvent } from 'react';
import { PromOptions } from '../types';
import { ExemplarsSettings } from './ExemplarsSettings';
const { Select, Input, FormField, Switch } = LegacyForms;
const httpOptions = [
{ value: 'POST', label: 'POST' },
{ value: 'GET', label: 'GET' },
];
type Props = Pick<DataSourcePluginOptionsEditorProps<PromOptions>, 'options' | 'onOptionsChange'>;
export const PromSettings = (props: Props) => {
const { options, onOptionsChange } = props;
// We are explicitly adding httpMethod so it is correctly displayed in dropdown. This way, it is more predictable for users.
if (!options.jsonData.httpMethod) {
options.jsonData.httpMethod = 'POST';
}
return (
<>
<div className="gf-form-group">
<div className="gf-form-inline">
<div className="gf-form">
<FormField
label="Scrape interval"
labelWidth={13}
inputEl={
<Input
className="width-6"
value={options.jsonData.timeInterval}
spellCheck={false}
placeholder="15s"
onChange={onChangeHandler('timeInterval', options, onOptionsChange)}
validationEvents={promSettingsValidationEvents}
/>
}
tooltip="Set this to the typical scrape and evaluation interval configured in Prometheus. Defaults to 15s."
/>
</div>
</div>
<div className="gf-form-inline">
<div className="gf-form">
<FormField
label="Query timeout"
labelWidth={13}
inputEl={
<Input
className="width-6"
value={options.jsonData.queryTimeout}
onChange={onChangeHandler('queryTimeout', options, onOptionsChange)}
spellCheck={false}
placeholder="60s"
validationEvents={promSettingsValidationEvents}
/>
}
tooltip="Set the Prometheus query timeout."
/>
</div>
</div>
<div className="gf-form">
<InlineFormLabel
width={13}
tooltip="You can use either POST or GET HTTP method to query your Prometheus data source. POST is the recommended method as it allows bigger queries. Change this to GET if you have a Prometheus version older than 2.1 or if POST requests are restricted in your network."
>
HTTP Method
</InlineFormLabel>
<Select
aria-label="Select HTTP method"
menuShouldPortal
options={httpOptions}
value={httpOptions.find((o) => o.value === options.jsonData.httpMethod)}
onChange={onChangeHandler('httpMethod', options, onOptionsChange)}
width={7}
/>
</div>
</div>
<h3 className="page-heading">Misc</h3>
<div className="gf-form-group">
<div className="gf-form">
<Switch
checked={options.jsonData.disableMetricsLookup ?? false}
label="Disable metrics lookup"
labelClass="width-14"
onChange={onUpdateDatasourceJsonDataOptionChecked(props, 'disableMetricsLookup')}
tooltip="Checking this option will disable the metrics chooser and metric/label support in the query field's autocomplete. This helps if you have performance issues with bigger Prometheus instances."
/>
</div>
<div className="gf-form-inline">
<div className="gf-form max-width-30">
<FormField
label="Custom query parameters"
labelWidth={14}
tooltip="Add Custom parameters to all Prometheus or Thanos queries."
inputEl={
<Input
className="width-25"
value={options.jsonData.customQueryParameters}
onChange={onChangeHandler('customQueryParameters', options, onOptionsChange)}
spellCheck={false}
placeholder="Example: max_source_resolution=5m&timeout=10"
/>
}
/>
</div>
</div>
</div>
<ExemplarsSettings
options={options.jsonData.exemplarTraceIdDestinations}
onChange={(exemplarOptions) =>
updateDatasourcePluginJsonDataOption(
{ onOptionsChange, options },
'exemplarTraceIdDestinations',
exemplarOptions
)
}
/>
</>
);
};
export const promSettingsValidationEvents = {
[EventsWithValidation.onBlur]: [
regexValidation(
/^$|^\d+(ms|[Mwdhmsy])$/,
'Value is not valid, you can use number with time unit specifier: y, M, w, d, h, m, s'
),
],
};
export const getValueFromEventItem = (eventItem: SyntheticEvent<HTMLInputElement> | SelectableValue<string>) => {
if (!eventItem) {
return '';
}
if (eventItem.hasOwnProperty('currentTarget')) {
return eventItem.currentTarget.value;
}
return (eventItem as SelectableValue<string>).value;
};
const onChangeHandler =
(key: keyof PromOptions, options: Props['options'], onOptionsChange: Props['onOptionsChange']) =>
(eventItem: SyntheticEvent<HTMLInputElement> | SelectableValue<string>) => {
onOptionsChange({
...options,
jsonData: {
...options.jsonData,
[key]: getValueFromEventItem(eventItem),
},
});
};
|
grafana/grafana
|
public/app/plugins/datasource/prometheus/configuration/PromSettings.tsx
|
TypeScript
|
agpl-3.0
| 5,824
|
/*=====================================================================
PIXHAWK Micro Air Vehicle Flying Robotics Toolkit
(c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch>
This file is part of the PIXHAWK project
PIXHAWK is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PIXHAWK is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PIXHAWK. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Waypoint list widget
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
* @author Benjamin Knecht <mavteam@student.ethz.ch>
* @author Petri Tanskanen <mavteam@student.ethz.ch>
*
*/
#include "WaypointList.h"
#include "ui_WaypointList.h"
#include <UASInterface.h>
#include <UASManager.h>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QMouseEvent>
WaypointList::WaypointList(QWidget *parent, UASInterface* uas) :
QWidget(parent),
uas(NULL),
mavX(0.0),
mavY(0.0),
mavZ(0.0),
mavYaw(0.0),
showOfflineWarning(false),
m_ui(new Ui::WaypointList)
{
m_ui->setupUi(this);
//EDIT TAB
editableListLayout = new QVBoxLayout(m_ui->editableListWidget);
editableListLayout->setSpacing(0);
editableListLayout->setMargin(0);
editableListLayout->setAlignment(Qt::AlignTop);
m_ui->editableListWidget->setLayout(editableListLayout);
// ADD WAYPOINT
// Connect add action, set right button icon and connect action to this class
connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered()));
connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(addEditable()));
// ADD WAYPOINT AT CURRENT POSITION
connect(m_ui->positionAddButton, SIGNAL(clicked()), this, SLOT(addCurrentPositionWaypoint()));
// SEND WAYPOINTS
connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit()));
// DELETE ALL WAYPOINTS
connect(m_ui->clearWPListButton, SIGNAL(clicked()), this, SLOT(clearWPWidget()));
// REQUEST WAYPOINTS
connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read()));
// SAVE/LOAD WAYPOINTS
connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints()));
connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints()));
//connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*)));
//VIEW TAB
viewOnlyListLayout = new QVBoxLayout(m_ui->viewOnlyListWidget);
viewOnlyListLayout->setSpacing(0);
viewOnlyListLayout->setMargin(0);
viewOnlyListLayout->setAlignment(Qt::AlignTop);
m_ui->viewOnlyListWidget->setLayout(viewOnlyListLayout);
// REFRESH VIEW TAB
connect(m_ui->refreshButton, SIGNAL(clicked()), this, SLOT(refresh()));
// SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED
if (uas)
{
WPM = uas->getWaypointManager();
//setUAS(uas);
}
else
{
// Hide buttons, which don't make sense without valid UAS
m_ui->positionAddButton->hide();
m_ui->transmitButton->hide();
m_ui->readButton->hide();
m_ui->refreshButton->hide();
//FIXME: The whole "Onboard Waypoints"-tab should be hidden, instead of "refresh" button
UnconnectedUASInfoWidget* inf = new UnconnectedUASInfoWidget(this);
viewOnlyListLayout->insertWidget(0, inf); //insert a "NO UAV" info into the Onboard Tab
showOfflineWarning = true;
WPM = new UASWaypointManager(NULL);
}
setUAS(uas);
// STATUS LABEL
updateStatusLabel("");
this->setVisible(false);
loadFileGlobalWP = false;
readGlobalWP = false;
centerMapCoordinate.setX(0.0);
centerMapCoordinate.setY(0.0);
}
WaypointList::~WaypointList()
{
delete m_ui;
}
void WaypointList::updatePosition(UASInterface* uas, double x, double y, double z, quint64 usec)
{
Q_UNUSED(uas);
Q_UNUSED(usec);
mavX = x;
mavY = y;
mavZ = z;
}
void WaypointList::updateAttitude(UASInterface* uas, double roll, double pitch, double yaw, quint64 usec)
{
Q_UNUSED(uas);
Q_UNUSED(usec);
Q_UNUSED(roll);
Q_UNUSED(pitch);
mavYaw = yaw;
}
void WaypointList::setUAS(UASInterface* uas)
{
//if (this->uas == NULL && uas != NULL)
if (this->uas == NULL)
{
this->uas = uas;
connect(WPM, SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &)));
connect(WPM, SIGNAL(waypointEditableListChanged(void)), this, SLOT(waypointEditableListChanged(void)));
connect(WPM, SIGNAL(waypointEditableChanged(int,Waypoint*)), this, SLOT(updateWaypointEditable(int,Waypoint*)));
connect(WPM, SIGNAL(waypointViewOnlyListChanged(void)), this, SLOT(waypointViewOnlyListChanged(void)));
connect(WPM, SIGNAL(waypointViewOnlyChanged(int,Waypoint*)), this, SLOT(updateWaypointViewOnly(int,Waypoint*)));
connect(WPM, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointViewOnlyChanged(quint16)));
if (uas != NULL)
{
connect(uas, SIGNAL(localPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updatePosition(UASInterface*,double,double,double,quint64)));
connect(uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,double,double,double,quint64)));
}
//connect(WPM,SIGNAL(loadWPFile()),this,SLOT(setIsLoadFileWP()));
//connect(WPM,SIGNAL(readGlobalWPFromUAS(bool)),this,SLOT(setIsReadGlobalWP(bool)));
}
}
void WaypointList::saveWaypoints()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)"));
WPM->saveWaypoints(fileName);
}
void WaypointList::loadWaypoints()
{
//create a popup notifying the user about the limitations of offline editing
if (showOfflineWarning == true)
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("Offline editor!");
msgBox.setInformativeText("You are using the offline mission editor. Please don't forget to save your mission plan before connecting the UAV, otherwise it will be lost.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
int ret = msgBox.exec();
showOfflineWarning = false;
}
QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)"));
WPM->loadWaypoints(fileName);
}
void WaypointList::transmit()
{
if (uas)
{
WPM->writeWaypoints();
}
}
void WaypointList::read()
{
if (uas)
{
WPM->readWaypoints(true);
}
}
void WaypointList::refresh()
{
if (uas)
{
WPM->readWaypoints(false);
}
}
void WaypointList::addEditable()
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
Waypoint *wp;
if (waypoints.size() > 0)
{
// Create waypoint with last frame
Waypoint *last = waypoints.at(waypoints.size()-1);
wp = new Waypoint(0, last->getX(), last->getY(), last->getZ(), last->getParam1(), last->getParam2(), last->getParam3(), last->getParam4(),
last->getAutoContinue(), false, last->getFrame(), last->getAction());
WPM->addWaypointEditable(wp);
}
else
{
if (uas)
{
// Create first waypoint at current MAV position
addCurrentPositionWaypoint();
}
else
{
//Since no UAV available, create first default waypoint.
updateStatusLabel(tr("No UAV. Added default LOCAL (NED) waypoint"));
wp = new Waypoint(0, 0, 0, -0.50, 0, 0.20, 0, 0,true, true, MAV_FRAME_LOCAL_NED, MAV_CMD_NAV_WAYPOINT);
WPM->addWaypointEditable(wp);
//create a popup notifying the user about the limitations of offline editing
if (showOfflineWarning == true)
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("Offline editor!");
msgBox.setInformativeText("You are using the offline mission editor. Please don't forget to save your mission plan before connecting the UAV, otherwise it will be lost.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
int ret = msgBox.exec();
showOfflineWarning = false;
}
}
}
}
void WaypointList::addCurrentPositionWaypoint()
{
if (uas)
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
Waypoint *wp;
Waypoint *last = 0;
if (waypoints.size() > 0)
{
last = waypoints.at(waypoints.size()-1);
}
if (uas->globalPositionKnown())
{
float acceptanceRadiusGlobal = 10.0f;
float holdTime = 0.0f;
float yawGlobal = 0.0f;
if (last)
{
acceptanceRadiusGlobal = last->getAcceptanceRadius();
holdTime = last->getHoldTime();
yawGlobal = last->getYaw();
}
// Create global frame waypoint per default
wp = new Waypoint(0, uas->getLatitude(), uas->getLongitude(), uas->getAltitude(), 0, acceptanceRadiusGlobal, holdTime, yawGlobal, true, false, MAV_FRAME_GLOBAL_RELATIVE_ALT, MAV_CMD_NAV_WAYPOINT);
WPM->addWaypointEditable(wp);
updateStatusLabel(tr("Added GLOBAL, ALTITUDE OVER GROUND waypoint"));
}
else if (uas->localPositionKnown())
{
float acceptanceRadiusLocal = 0.2f;
float holdTime = 0.5f;
if (last)
{
acceptanceRadiusLocal = last->getAcceptanceRadius();
holdTime = last->getHoldTime();
}
// Create local frame waypoint as second option
wp = new Waypoint(0, uas->getLocalX(), uas->getLocalY(), uas->getLocalZ(), uas->getYaw(), acceptanceRadiusLocal, holdTime, 0.0, true, false, MAV_FRAME_LOCAL_NED, MAV_CMD_NAV_WAYPOINT);
WPM->addWaypointEditable(wp);
updateStatusLabel(tr("Added LOCAL (NED) waypoint"));
}
else
{
// Do nothing
updateStatusLabel(tr("Not adding waypoint, no position of MAV known yet."));
}
}
}
void WaypointList::updateStatusLabel(const QString &string)
{
// Status label in write widget
m_ui->statusLabel->setText(string);
// Status label in read only widget
m_ui->viewStatusLabel->setText(string);
}
// Request UASWaypointManager to send the SET_CURRENT message to UAV
void WaypointList::changeCurrentWaypoint(quint16 seq)
{
if (uas)
{
WPM->setCurrentWaypoint(seq);
}
}
// Request UASWaypointManager to set the new "current" and make sure all other waypoints are not "current"
void WaypointList::currentWaypointEditableChanged(quint16 seq)
{
WPM->setCurrentEditable(seq);
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
if (seq < waypoints.size())
{
for(int i = 0; i < waypoints.size(); i++)
{
WaypointEditableView* widget = wpEditableViews.find(waypoints[i]).value();
if (waypoints[i]->getId() == seq)
{
widget->setCurrent(true);
}
else
{
widget->setCurrent(false);
}
}
}
}
// Update waypointViews to correctly indicate the new current waypoint
void WaypointList::currentWaypointViewOnlyChanged(quint16 seq)
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointViewOnlyList();
if (seq < waypoints.size())
{
for(int i = 0; i < waypoints.size(); i++)
{
WaypointViewOnlyView* widget = wpViewOnlyViews.find(waypoints[i]).value();
if (waypoints[i]->getId() == seq)
{
widget->setCurrent(true);
}
else
{
widget->setCurrent(false);
}
}
}
}
void WaypointList::updateWaypointEditable(int uas, Waypoint* wp)
{
Q_UNUSED(uas);
WaypointEditableView *wpv = wpEditableViews.value(wp);
wpv->updateValues();
}
void WaypointList::updateWaypointViewOnly(int uas, Waypoint* wp)
{
Q_UNUSED(uas);
WaypointViewOnlyView *wpv = wpViewOnlyViews.value(wp);
wpv->updateValues();
}
void WaypointList::waypointViewOnlyListChanged()
{
// Prevent updates to prevent visual flicker
this->setUpdatesEnabled(false);
const QVector<Waypoint *> &waypoints = WPM->getWaypointViewOnlyList();
if (!wpViewOnlyViews.empty()) {
QMapIterator<Waypoint*,WaypointViewOnlyView*> viewIt(wpViewOnlyViews);
viewIt.toFront();
while(viewIt.hasNext()) {
viewIt.next();
Waypoint *cur = viewIt.key();
int i;
for (i = 0; i < waypoints.size(); i++) {
if (waypoints[i] == cur) {
break;
}
}
if (i == waypoints.size()) {
WaypointViewOnlyView* widget = wpViewOnlyViews.find(cur).value();
widget->hide();
viewOnlyListLayout->removeWidget(widget);
wpViewOnlyViews.remove(cur);
}
}
}
// then add/update the views for each waypoint in the list
for(int i = 0; i < waypoints.size(); i++) {
Waypoint *wp = waypoints[i];
if (!wpViewOnlyViews.contains(wp)) {
WaypointViewOnlyView* wpview = new WaypointViewOnlyView(wp, this);
wpViewOnlyViews.insert(wp, wpview);
connect(wpview, SIGNAL(changeCurrentWaypoint(quint16)), this, SLOT(changeCurrentWaypoint(quint16)));
viewOnlyListLayout->insertWidget(i, wpview);
}
WaypointViewOnlyView *wpv = wpViewOnlyViews.value(wp);
//check if ordering has changed
if(viewOnlyListLayout->itemAt(i)->widget() != wpv) {
viewOnlyListLayout->removeWidget(wpv);
viewOnlyListLayout->insertWidget(i, wpv);
}
wpv->updateValues(); // update the values of the ui elements in the view
}
this->setUpdatesEnabled(true);
loadFileGlobalWP = false;
}
void WaypointList::waypointEditableListChanged()
{
// Prevent updates to prevent visual flicker
this->setUpdatesEnabled(false);
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
if (!wpEditableViews.empty()) {
QMapIterator<Waypoint*,WaypointEditableView*> viewIt(wpEditableViews);
viewIt.toFront();
while(viewIt.hasNext()) {
viewIt.next();
Waypoint *cur = viewIt.key();
int i;
for (i = 0; i < waypoints.size(); i++) {
if (waypoints[i] == cur) {
break;
}
}
if (i == waypoints.size()) {
WaypointEditableView* widget = wpEditableViews.find(cur).value();
widget->hide();
editableListLayout->removeWidget(widget);
wpEditableViews.remove(cur);
}
}
}
// then add/update the views for each waypoint in the list
for(int i = 0; i < waypoints.size(); i++) {
Waypoint *wp = waypoints[i];
if (!wpEditableViews.contains(wp)) {
WaypointEditableView* wpview = new WaypointEditableView(wp, this);
wpEditableViews.insert(wp, wpview);
connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*)));
connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*)));
connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*)));
//connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
connect(wpview, SIGNAL(changeCurrentWaypoint(quint16)), this, SLOT(currentWaypointEditableChanged(quint16)));
editableListLayout->insertWidget(i, wpview);
}
WaypointEditableView *wpv = wpEditableViews.value(wp);
//check if ordering has changed
if(editableListLayout->itemAt(i)->widget() != wpv) {
editableListLayout->removeWidget(wpv);
editableListLayout->insertWidget(i, wpv);
}
wpv->updateValues(); // update the values of the ui elements in the view
}
this->setUpdatesEnabled(true);
loadFileGlobalWP = false;
}
void WaypointList::moveUp(Waypoint* wp)
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
//get the current position of wp in the local storage
int i;
for (i = 0; i < waypoints.size(); i++) {
if (waypoints[i] == wp)
break;
}
// if wp was found and its not the first entry, move it
if (i < waypoints.size() && i > 0) {
WPM->moveWaypoint(i, i-1);
}
}
void WaypointList::moveDown(Waypoint* wp)
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
//get the current position of wp in the local storage
int i;
for (i = 0; i < waypoints.size(); i++) {
if (waypoints[i] == wp)
break;
}
// if wp was found and its not the last entry, move it
if (i < waypoints.size()-1) {
WPM->moveWaypoint(i, i+1);
}
}
void WaypointList::removeWaypoint(Waypoint* wp)
{
WPM->removeWaypoint(wp->getId());
}
void WaypointList::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
void WaypointList::on_clearWPListButton_clicked()
{
if (uas) {
emit clearPathclicked();
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
while(!waypoints.isEmpty()) { //for(int i = 0; i <= waypoints.size(); i++)
WaypointEditableView* widget = wpEditableViews.find(waypoints[0]).value();
widget->remove();
}
} else {
// if(isGlobalWP)
// {
// emit clearPathclicked();
// }
}
}
///** @brief The MapWidget informs that a waypoint global was changed on the map */
//void WaypointList::waypointGlobalChanged(QPointF coordinate, int indexWP)
//{
// if (uas)
// {
// const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
// if (waypoints.size() > 0)
// {
// Waypoint *temp = waypoints.at(indexWP);
// temp->setX(coordinate.x());
// temp->setY(coordinate.y());
// //WaypointGlobalView* widget = wpGlobalViews.find(waypoints[indexWP]).value();
// //widget->updateValues();
// }
// }
//}
///** @brief The MapWidget informs that a waypoint global was changed on the map */
//void WaypointList::waypointGlobalPositionChanged(Waypoint* wp)
//{
// QPointF coordinate;
// coordinate.setX(wp->getX());
// coordinate.setY(wp->getY());
// emit ChangeWaypointGlobalPosition(wp->getId(), coordinate);
//}
void WaypointList::clearWPWidget()
{
const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList();
while(!waypoints.isEmpty()) { //for(int i = 0; i <= waypoints.size(); i++)
WaypointEditableView* widget = wpEditableViews.find(waypoints[0]).value();
widget->remove();
}
}
//void WaypointList::setIsLoadFileWP()
//{
// loadFileGlobalWP = true;
//}
//void WaypointList::setIsReadGlobalWP(bool value)
//{
// // FIXME James Check this
// Q_UNUSED(value);
// // readGlobalWP = value;
//}
|
josephlewis42/UDenverQGC
|
src/ui/WaypointList.cc
|
C++
|
agpl-3.0
| 20,720
|
<html>
<head>
<title>La Simpla Vortaro</title>
</head>
<style type="text/css">
#background {
position:absolute; z-index:1; width:100%; height:100%;
}
#header {
/* positioning */
position:absolute;
top:0px;
left:0px;
width:800px;
z-index:2;
/* colour with transparency */
color:#CCC;
background-color:#000;
/* for IE */
filter:alpha(opacity=60);
/* CSS3 standard */
opacity:0.6;
/* text positioning */
text-align: center;
padding: 0px;
}
#content {
position:absolute;
bottom: 0;
left: 500px;
height: 200px;
z-index: 2;
/* text colours */
color:#CCC;
padding:10px;
/* colour with transparency */
background-color:#000;
filter:alpha(opacity=60); /* for IE */
opacity:0.6; /* CSS3 standard */
}
html, body {
margin:0;
padding:0;
width:100%;
height:100%;
overflow:hidden;
text-align:left;
}
h1 {
font-family: serif;
font-weight: normal;
font-size: 700%;
padding: 0;
margin: 10px;
}
h2 {
font-family: "TangerineRegular", serif;
font-size: 300%;
}
</style>
<body>
<div>
<img id="background" src="book.jpg">
</div>
<div id="header">
<h1>La Simpla Vortaro</h1>
</div>
<div id="content">
<h2>Entajpu vian vorton: (Box)</h2>
</div>
</body>
</html>
|
Wilfred/simpla-vortaro
|
templates/mockups/mockup3.html
|
HTML
|
agpl-3.0
| 1,181
|
<!-- Generated by pkgdown: do not edit by hand -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculates day length (in hours) and the solar elevation — daylength • phenocamr</title>
<!-- favicons -->
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="/apple-touch-icon.png">
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha256-bZLfwXAP04zRMK2BjiO8iu9pf4FbLqX6zitd+tIvLhE=" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha256-nuL8/2cJ5NDSSwnKD8VqreErSWHtnEP9E7AySL+1ev4=" crossorigin="anonymous"></script>
<!-- bootstrap-toc -->
<link rel="stylesheet" href="../bootstrap-toc.css">
<script src="../bootstrap-toc.js"></script>
<!-- Font Awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.1/css/all.min.css" integrity="sha256-PbSmjxuVAzJ6FPvNYsrXygfGhNJYyZ2GktDbkMBqQZg=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.1/css/v4-shims.min.css" integrity="sha256-A6jcAdwFD48VMjlI3GDxUd+eCQa7/KWy6G9oe/ovaPA=" crossorigin="anonymous" />
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Titillium+Web:ital,wght@0,300;0,400;0,700;1,300;1,400&display=swap" rel="stylesheet">
<!-- clipboard.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js" integrity="sha256-FiZwavyI2V6+EXO1U+xzLG3IKldpiTFf3153ea9zikQ=" crossorigin="anonymous"></script>
<!-- headroom.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/headroom.min.js" integrity="sha256-DJFC1kqIhelURkuza0AvYal5RxMtpzLjFhsnVIeuk+U=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/jQuery.headroom.min.js" integrity="sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=" crossorigin="anonymous"></script>
<!-- pkgdown -->
<link href="../pkgdown.css" rel="stylesheet">
<script src="../pkgdown.js"></script>
<!-- ropensci -->
<link href="../bglabs.css" rel="stylesheet">
<meta property="og:title" content="Calculates day length (in hours) and the solar elevation — daylength" />
<meta property="og:description" content="This routine uses Forsythe et al. 1995." />
<meta property="og:image" content="/logo.png" />
<meta name="twitter:card" content="summary" />
</head>
<body data-spy="scroll" data-target="#toc">
<div class="container template-reference-topic">
<header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-brand-container">
<a class="hidden-sm hidden-xs" href="https://bluegreenlabs.org">
<img src="https://bluegreenlabs.org/img/logo_text_small.png" id="hexlogo" alt="bluegreen labs" />
</a>
<a class="hidden-md hidden-lg" href="https://bluegreenlabs.org">
<img src="https://bluegreenlabs.org/img/logo.png" id="hexlogo" alt="bluegreen labs" />
</a>
<a class="navbar-brand" href="../index.html">
<i>phenocamr <small>v1.1.5</small></i>
</a>
</div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="../index.html">
<span class="fas fa-home fa-lg"></span>
</a>
</li>
<li>
<a href="../reference/index.html">Reference</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Articles
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/phenocamr-vignette.html">phenocamr functionality</a>
</li>
</ul>
</li>
<li>
<a href="../news/index.html">Changelog</a>
</li>
<li>
<a href="https://twitter.com/bluegreen_labs">
<span class="fab fa-twitter fa-lg"></span>
</a>
</li>
<li>
<a href="https://github.com/bluegreen-labs/issues/">
<span class="fab fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
</header>
<div class="row">
<div class="col-md-9 contents">
<div class="page-header">
<h1>Calculates day length (in hours) and the solar elevation</h1>
<small class="dont-index">Source: <a href='https://github.com/bluegreen-labs/issues/blob/master/R/daylength.r'><code>R/daylength.r</code></a></small>
<div class="hidden name"><code>daylength.Rd</code></div>
</div>
<div class="ref-description">
<p>This routine uses Forsythe et al. 1995.</p>
</div>
<pre class="usage"><span class='fu'>daylength</span><span class='op'>(</span><span class='va'>doy</span>, <span class='va'>latitude</span><span class='op'>)</span></pre>
<h2 class="hasAnchor" id="arguments"><a class="anchor" href="#arguments"></a>Arguments</h2>
<table class="ref-arguments">
<colgroup><col class="name" /><col class="desc" /></colgroup>
<tr>
<th>doy</th>
<td><p>a vector with doy values 1 - 365(6)</p></td>
</tr>
<tr>
<th>latitude</th>
<td><p>a given latitude</p></td>
</tr>
</table>
<h2 class="hasAnchor" id="value"><a class="anchor" href="#value"></a>Value</h2>
<p>nested list with daylength (daylength) and
solar elevation (solar_elev) elements</p>
<h2 class="hasAnchor" id="examples"><a class="anchor" href="#examples"></a>Examples</h2>
<pre class="examples"><div class='input'>
<span class='kw'>if</span> <span class='op'>(</span><span class='cn'>FALSE</span><span class='op'>)</span> <span class='op'>{</span>
<span class='co'># calcualte the hours of sunlight and solar elevation on day of year 1</span>
<span class='co'># and latitude 51</span>
<span class='va'>ephem</span> <span class='op'><-</span> <span class='fu'>daylength</span><span class='op'>(</span><span class='fl'>1</span>, <span class='fl'>51</span><span class='op'>)</span>
<span class='fu'><a href='https://rdrr.io/r/base/print.html'>print</a></span><span class='op'>(</span><span class='va'>ephem</span><span class='op'>)</span>
<span class='op'>}</span>
</div></pre>
</div>
<div class="col-md-3 hidden-xs hidden-sm" id="pkgdown-sidebar">
<nav id="toc" data-toggle="toc" class="sticky-top">
<h2 data-toc-skip>Contents</h2>
</nav>
</div>
</div>
<footer>
<!-- begin footer -->
<div class="footer">
<div class="container">
<div class="row start bottom-8">
<div class="col-xs-10">
<div class="row">
<div class="col-md-4 col-xs-6">
<a href="http://github.com/bluegreen-labs" target="_blank">
<div class="icon fab fa-github"></div></a>
<a href="https://bluegreenlabs.org/labs/" target="_blank">
<div class="icon fa fa-flask"></div></a>
<a href="http://twitter.com/bluegreen_labs" target="_blank">
<div class="icon fab fa-twitter"></div></a>
</div>
</div>
<div class="row top-4">
<div class="col-md-2 col-sm-4">
<ul>
<h5 class="bottom-2">About</h5>
<li><a href="https://bluegreenlabs.org/#intro">BlueGreen Labs</a></li>
<li><a href="https://bluegreenlabs.org/#people">Our Team</a></li>
<li><a href="https://bluegreenlabs.org/#contact">Contact Us</a></li>
</ul>
</div>
<div class="col-md-2 col-sm-4">
<ul>
<h5 class="bottom-2">Resources</h5>
<li><a href="https://github.com/bluegreen-labs">Packages</a></li>
<li><a href="https://bluegreenlabs.org/publication/">Publications</a></li>
<li><a href="https://bluegreenlabs.org/post/">Blog</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- / end footer -->
</footer>
</div>
</body>
</html>
|
khufkens/phenocamr
|
docs/reference/daylength.html
|
HTML
|
agpl-3.0
| 9,432
|
<?php
// created: 2013-02-07 16:25:26
$sugar_config = array (
'admin_access_control' => false,
'admin_export_only' => false,
'cache_dir' => 'cache/',
'calculate_response_time' => true,
'calendar' =>
array (
'default_view' => 'week',
'show_calls_by_default' => true,
'show_tasks_by_default' => true,
'editview_width' => 990,
'editview_height' => 485,
'day_timestep' => 15,
'week_timestep' => 30,
'items_draggable' => true,
'items_resizable' => true,
'enable_repeat' => true,
'max_repeat_count' => 1000,
),
'chartEngine' => 'Jit',
'common_ml_dir' => '',
'create_default_user' => false,
'cron' =>
array (
'max_cron_jobs' => 10,
'max_cron_runtime' => 30,
'min_cron_interval' => 30,
),
'currency' => '',
'dashlet_display_row_options' =>
array (
0 => '1',
1 => '3',
2 => '5',
3 => '10',
),
'date_formats' =>
array (
'Y-m-d' => '2010-12-23',
'm-d-Y' => '12-23-2010',
'd-m-Y' => '23-12-2010',
'Y/m/d' => '2010/12/23',
'm/d/Y' => '12/23/2010',
'd/m/Y' => '23/12/2010',
'Y.m.d' => '2010.12.23',
'd.m.Y' => '23.12.2010',
'm.d.Y' => '12.23.2010',
),
'datef' => 'm/d/Y',
'dbconfig' =>
array (
'db_host_name' => 'localhost',
'db_host_instance' => 'SQLEXPRESS',
'db_user_name' => 'root',
'db_password' => 'sa',
'db_name' => 'rrd',
'db_type' => 'mysql',
'db_port' => '',
'db_manager' => 'MysqliManager',
),
'dbconfigoption' =>
array (
'persistent' => true,
'autofree' => false,
'debug' => 0,
'ssl' => false,
),
'default_action' => 'index',
'default_charset' => 'UTF-8',
'default_currencies' =>
array (
'AUD' =>
array (
'name' => 'Australian Dollars',
'iso4217' => 'AUD',
'symbol' => '$',
),
'BRL' =>
array (
'name' => 'Brazilian Reais',
'iso4217' => 'BRL',
'symbol' => 'R$',
),
'GBP' =>
array (
'name' => 'British Pounds',
'iso4217' => 'GBP',
'symbol' => '£',
),
'CAD' =>
array (
'name' => 'Canadian Dollars',
'iso4217' => 'CAD',
'symbol' => '$',
),
'CNY' =>
array (
'name' => 'Chinese Yuan',
'iso4217' => 'CNY',
'symbol' => '¥',
),
'EUR' =>
array (
'name' => 'Euro',
'iso4217' => 'EUR',
'symbol' => '€',
),
'HKD' =>
array (
'name' => 'Hong Kong Dollars',
'iso4217' => 'HKD',
'symbol' => '$',
),
'INR' =>
array (
'name' => 'Indian Rupees',
'iso4217' => 'INR',
'symbol' => '₨',
),
'KRW' =>
array (
'name' => 'Korean Won',
'iso4217' => 'KRW',
'symbol' => '₩',
),
'YEN' =>
array (
'name' => 'Japanese Yen',
'iso4217' => 'JPY',
'symbol' => '¥',
),
'MXM' =>
array (
'name' => 'Mexican Pesos',
'iso4217' => 'MXM',
'symbol' => '$',
),
'SGD' =>
array (
'name' => 'Singaporean Dollars',
'iso4217' => 'SGD',
'symbol' => '$',
),
'CHF' =>
array (
'name' => 'Swiss Franc',
'iso4217' => 'CHF',
'symbol' => 'SFr.',
),
'THB' =>
array (
'name' => 'Thai Baht',
'iso4217' => 'THB',
'symbol' => '฿',
),
'USD' =>
array (
'name' => 'US Dollars',
'iso4217' => 'USD',
'symbol' => '$',
),
),
'default_currency_iso4217' => 'USD',
'default_currency_name' => 'US Dollars',
'default_currency_significant_digits' => 2,
'default_currency_symbol' => '$',
'default_date_format' => 'm/d/Y',
'default_decimal_seperator' => '.',
'default_email_charset' => 'UTF-8',
'default_email_client' => 'sugar',
'default_email_editor' => 'html',
'default_export_charset' => 'UTF-8',
'default_language' => 'en_us',
'default_locale_name_format' => 's f l',
'default_max_tabs' => '7',
'default_module' => 'Home',
'default_navigation_paradigm' => 'gm',
'default_number_grouping_seperator' => ',',
'default_password' => '',
'default_permissions' =>
array (
'dir_mode' => 1528,
'file_mode' => 432,
'user' => '',
'group' => '',
),
'default_subpanel_links' => false,
'default_subpanel_tabs' => true,
'default_swap_last_viewed' => false,
'default_swap_shortcuts' => false,
'default_theme' => 'VTPL',
'default_time_format' => 'h:ia',
'default_user_is_admin' => false,
'default_user_name' => '',
'demoData' => 'yes',
'disable_convert_lead' => false,
'disable_export' => false,
'disable_persistent_connections' => 'false',
'display_email_template_variable_chooser' => false,
'display_inbound_email_buttons' => false,
'dump_slow_queries' => false,
'email_address_separator' => ',',
'email_default_client' => 'sugar',
'email_default_delete_attachments' => true,
'email_default_editor' => 'html',
'export_delimiter' => ',',
'history_max_viewed' => 50,
'host_name' => 'localhost',
'import_max_execution_time' => 3600,
'import_max_records_per_file' => 100,
'import_max_records_total_limit' => '',
'installer_locked' => true,
'jobs' =>
array (
'min_retry_interval' => 30,
'max_retries' => 5,
'timeout' => 86400,
),
'js_custom_version' => 1,
'js_lang_version' => 4,
'languages' =>
array (
'en_us' => 'English (US)',
),
'large_scale_test' => false,
'lead_conv_activity_opt' => 'donothing',
'list_max_entries_per_page' => 20,
'list_max_entries_per_subpanel' => 10,
'lock_default_user_name' => false,
'lock_homepage' => false,
'lock_subpanels' => false,
'log_dir' => '.',
'log_file' => 'sugarcrm.log',
'log_memory_usage' => false,
'logger' =>
array (
'level' => 'fatal',
'file' =>
array (
'ext' => '.log',
'name' => 'sugarcrm',
'dateFormat' => '%c',
'maxSize' => '10MB',
'maxLogs' => 10,
'suffix' => '',
),
),
'max_dashlets_homepage' => '15',
'name_formats' =>
array (
's f l' => 's f l',
'f l' => 'f l',
's l' => 's l',
'l, s f' => 'l, s f',
'l, f' => 'l, f',
's l, f' => 's l, f',
'l s f' => 'l s f',
'l f s' => 'l f s',
),
'passwordsetting' =>
array (
'SystemGeneratedPasswordON' => true,
'generatepasswordtmpl' => '9bcfa05d-3288-034a-0f5a-5111e6e7b8cc',
'lostpasswordtmpl' => 'c636a422-a241-ab44-c071-5111e69d04b3',
'forgotpasswordON' => true,
'linkexpiration' => true,
'linkexpirationtime' => 24,
'linkexpirationtype' => 60,
'systexpiration' => 1,
'systexpirationtime' => 7,
'systexpirationtype' => '0',
'systexpirationlogin' => '',
'minpwdlength' => 6,
'oneupper' => true,
'onelower' => true,
'onenumber' => true,
),
'portal_view' => 'single_user',
'require_accounts' => true,
'resource_management' =>
array (
'special_query_limit' => 50000,
'special_query_modules' =>
array (
0 => 'Reports',
1 => 'Export',
2 => 'Import',
3 => 'Administration',
4 => 'Sync',
),
'default_limit' => 1000,
),
'rss_cache_time' => '10800',
'save_query' => 'all',
'search_wildcard_char' => '%',
'search_wildcard_infront' => false,
'session_dir' => '',
'showDetailData' => true,
'showThemePicker' => true,
'site_url' => 'http://localhost/rrd',
'slow_query_time_msec' => '100',
'sugar_version' => '6.5.8',
'sugarbeet' => true,
'time_formats' =>
array (
'H:i' => '23:00',
'h:ia' => '11:00pm',
'h:iA' => '11:00PM',
'h:i a' => '11:00 pm',
'h:i A' => '11:00 PM',
'H.i' => '23.00',
'h.ia' => '11.00pm',
'h.iA' => '11.00PM',
'h.i a' => '11.00 pm',
'h.i A' => '11.00 PM',
),
'timef' => 'H:i',
'tmp_dir' => 'cache/xml/',
'tracker_max_display_length' => 15,
'translation_string_prefix' => false,
'unique_key' => 'c724c99c34ff308b7a7d08f6c3b728f0',
'upload_badext' =>
array (
0 => 'php',
1 => 'php3',
2 => 'php4',
3 => 'php5',
4 => 'pl',
5 => 'cgi',
6 => 'py',
7 => 'asp',
8 => 'cfm',
9 => 'js',
10 => 'vbs',
11 => 'html',
12 => 'htm',
),
'upload_dir' => 'upload/',
'upload_maxsize' => 120000000,
'use_common_ml_dir' => false,
'use_real_names' => true,
'vcal_time' => '2',
'verify_client_ip' => true,
'email_xss' => 'YToxMzp7czo2OiJhcHBsZXQiO3M6NjoiYXBwbGV0IjtzOjQ6ImJhc2UiO3M6NDoiYmFzZSI7czo1OiJlbWJlZCI7czo1OiJlbWJlZCI7czo0OiJmb3JtIjtzOjQ6ImZvcm0iO3M6NToiZnJhbWUiO3M6NToiZnJhbWUiO3M6ODoiZnJhbWVzZXQiO3M6ODoiZnJhbWVzZXQiO3M6NjoiaWZyYW1lIjtzOjY6ImlmcmFtZSI7czo2OiJpbXBvcnQiO3M6ODoiXD9pbXBvcnQiO3M6NToibGF5ZXIiO3M6NToibGF5ZXIiO3M6NDoibGluayI7czo0OiJsaW5rIjtzOjY6Im9iamVjdCI7czo2OiJvYmplY3QiO3M6MzoieG1wIjtzOjM6InhtcCI7czo2OiJzY3JpcHQiO3M6Njoic2NyaXB0Ijt9',
'disabled_themes' => '',
'addAjaxBannedModules' =>
array (
0 => 'Home',
1 => 'Tasks',
2 => 'Meetings',
3 => 'Notes',
4 => 'Leads',
5 => 'ProspectLists',
6 => 'Opportunities',
7 => 'Contacts',
8 => 'Bugs',
9 => 'Accounts',
10 => 'Cases',
11 => 'Prospects',
12 => 'Calls',
),
);
|
harish-patel/rrd
|
config.php
|
PHP
|
agpl-3.0
| 9,128
|
<?php
/**
* Data class for happenings
*
* PHP version 5
*
* @category Data
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
* @link http://status.net/
*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2011, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('STATUSNET')) {
exit(1);
}
/**
* Data class for userpoints
*
* There's already an Event class in lib/event.php, so we couldn't
* call this an Event without causing a hole in space-time.
*
* "UserPoints" seemed good enough.
*
* @category Event
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
* @link http://status.net/
*
* @see Managed_DataObject
*/
class UserPoints extends Managed_DataObject
{
const OBJECT_TYPE = 'http://activitystrea.ms/schema/1.0/event';
public $__table = 'user_points'; // table name
public $profile_id; // int
public $cumulative_points;
public $available_points;
public $points_index;
public $nickname;
/**
* Get an instance by key
*
* @param string $k Key to use to lookup (usually 'id' for this class)
* @param mixed $v Value to lookup
*
* @return Happening object found, or null for no hits
*
*/
function staticGet($k, $v=null)
{
return Memcached_DataObject::staticGet('UserPoints', $k, $v);
}
/**
* The One True Thingy that must be defined and declared.
*/
public static function schemaDef()
{
return array(
'description' => 'A real-world happening',
'fields' => array(
'profile_id' => array('type' => 'int', 'not null' => true),
'nickname' => array('type' => 'varchar', 'length' => 64),
'cumulative_points' => array('type' => 'int', 'not null' => true),
'available_points' => array('type' => 'int', 'not null' => true),
'points_index' => array('type' => 'int', 'not null' => true),
),
'primary key' => array('profile_id'),
);
}
static function getPoints($profile_id)
{
return UserPoints::staticGet('profile_id', $profile_id);
}
}
|
gayathri6/stepstream_salute
|
plugins/Event/UserPoints.php
|
PHP
|
agpl-3.0
| 3,036
|
DELETE FROM `weenie` WHERE `class_Id` = 35297;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (35297, 'ace35297-greatswordofflameandlight', 6, '2019-02-10 00:00:00') /* MeleeWeapon */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (35297, 1, 1) /* ItemType - MeleeWeapon */
, (35297, 5, 500) /* EncumbranceVal */
, (35297, 9, 1048576) /* ValidLocations - MeleeWeapon */
, (35297, 16, 1) /* ItemUseable - No */
, (35297, 18, 128) /* UiEffects - Frost */
, (35297, 19, 40000) /* Value */
, (35297, 33, -2) /* Bonded - Destroy */
, (35297, 36, 9999) /* ResistMagic */
, (35297, 44, 226) /* Damage */
, (35297, 45, 17) /* DamageType - Slash, Fire */
, (35297, 47, 166) /* AttackType - Thrust, Slash, DoubleSlash, DoubleThrust */
, (35297, 48, 44) /* WeaponSkill - HeavyWeapons */
, (35297, 49, 1) /* WeaponTime */
, (35297, 51, 1) /* CombatUse - Melee */
, (35297, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (35297, 106, 400) /* ItemSpellcraft */
, (35297, 107, 2000) /* ItemCurMana */
, (35297, 108, 2000) /* ItemMaxMana */
, (35297, 109, 10) /* ItemDifficulty */
, (35297, 114, 1) /* Attuned - Attuned */
, (35297, 158, 11) /* WieldRequirements - CreatureType */
, (35297, 159, 0) /* WieldSkillType - None */
, (35297, 160, 13) /* WieldDifficulty */
, (35297, 166, 22) /* SlayerCreatureType - Shadow */
, (35297, 179, 8) /* ImbuedEffect - SlashRending */
, (35297, 353, 2) /* WeaponType - Sword */
, (35297, 8030, 0) /* PCAPRecordedMaxVelocityEstimated */
, (35297, 8041, 1) /* PCAPRecordedPlacement - RightHandCombat */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (35297, 23, True ) /* DestroyOnSell */
, (35297, 69, False) /* IsSellable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (35297, 5, -0.05) /* ManaRate */
, (35297, 21, 0) /* WeaponLength */
, (35297, 22, 0.5) /* DamageVariance */
, (35297, 26, 0) /* MaximumVelocity */
, (35297, 29, 1.18) /* WeaponDefense */
, (35297, 62, 1.48) /* WeaponOffense */
, (35297, 63, 1) /* DamageMod */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (35297, 1, 'Greatsword of Flame and Light') /* Name */
, (35297, 16, 'A sword mostly composed of a white-hot flame. Lightning striking between the free floating metal sections that the flames coalesce around.') /* LongDesc */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (35297, 1, 0x020016D4) /* Setup */
, (35297, 3, 0x20000014) /* SoundTable */
, (35297, 8, 0x06006633) /* Icon */
, (35297, 22, 0x3400002B) /* PhysicsEffectTable */
, (35297, 55, 3911) /* ProcSpell - RingHarmOther */
, (35297, 8001, 2327192) /* PCAPRecordedWeenieHeader - Value, Usable, UiEffects, CombatUse, Wielder, ValidLocations, CurrentlyWieldedLocation, Burden */
, (35297, 8003, 16) /* PCAPRecordedObjectDesc - Attackable */
, (35297, 8005, 170017) /* PCAPRecordedPhysicsDesc - CSetup, Parent, STable, PeTable, Position, AnimationFrame */
, (35297, 8009, 1) /* PCAPRecordedParentLocation - RightHand */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (35297, 8040, 0xD599003F, 180.025, 155, 373.939, 0.707107, 0.707107, 0, 0) /* PCAPRecordedLocation */
/* @teleloc 0xD599003F [180.025000 155.000000 373.939000] 0.707107 0.707107 0.000000 0.000000 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (35297, 8000, 0xDC1439C8) /* PCAPRecordedObjectIID */
, (35297, 8008, 0xDC1439C9) /* PCAPRecordedParentIID */;
INSERT INTO `weenie_properties_spell_book` (`object_Id`, `spell`, `probability`)
VALUES (35297, 2694, 2) /* ModerateSwordAptitude */;
|
ACEmulator/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/MeleeWeapon/MeleeWeapon/35297 Greatsword of Flame and Light.sql
|
SQL
|
agpl-3.0
| 4,335
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1996, 2017 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
#include "db_config.h"
#include "db_int.h"
#pragma hdrstop
#include "dbinc/db_page.h"
#include "dbinc/db_swap.h"
#include "dbinc/hash.h"
/*
* __ham_pgin --
* Convert host-specific page layout from the host-independent format
* stored on disk.
*
* PUBLIC: int __ham_pgin __P((DB *, db_pgno_t, void *, DBT *));
*/
int __ham_pgin(DB *dbp, db_pgno_t pg, void * pp, DBT * cookie)
{
PAGE * h = (PAGE *)pp;
DB_PGINFO * pginfo = (DB_PGINFO*)cookie->data;
/*
* The hash access method does blind reads of pages, causing them
* to be created. If the type field isn't set it's one of them,
* initialize the rest of the page and return.
*/
if(h->type != P_HASHMETA && h->pgno == PGNO_INVALID) {
P_INIT(pp, (db_indx_t)pginfo->db_pagesize, pg, PGNO_INVALID, PGNO_INVALID, 0, P_HASH);
return 0;
}
if(!F_ISSET(pginfo, DB_AM_SWAP))
return 0;
return (h->type == P_HASHMETA ? __ham_mswap(dbp->env, pp) : __db_byteswap(dbp, pg, (PAGE *)pp, pginfo->db_pagesize, 1));
}
/*
* __ham_pgout --
* Convert host-specific page layout to the host-independent format
* stored on disk.
*
* PUBLIC: int __ham_pgout __P((DB *, db_pgno_t, void *, DBT *));
*/
int __ham_pgout(DB *dbp, db_pgno_t pg, void * pp, DBT * cookie)
{
PAGE * h;
DB_PGINFO * pginfo = (DB_PGINFO*)cookie->data;
if(!F_ISSET(pginfo, DB_AM_SWAP))
return 0;
h = (PAGE *)pp;
return (h->type == P_HASHMETA ? __ham_mswap(dbp->env, pp) : __db_byteswap(dbp, pg, (PAGE *)pp, pginfo->db_pagesize, 0));
}
/*
* __ham_mswap --
* Swap the bytes on the hash metadata page.
*
* PUBLIC: int __ham_mswap __P((ENV *, void *));
*/
int __ham_mswap(ENV *env, void * pg)
{
uint8 * p;
int i;
COMPQUIET(env, NULL);
__db_metaswap((PAGE *)pg);
p = (uint8*)pg + sizeof(DBMETA);
SWAP32(p); /* max_bucket */
SWAP32(p); /* high_mask */
SWAP32(p); /* low_mask */
SWAP32(p); /* ffactor */
SWAP32(p); /* nelem */
SWAP32(p); /* h_charkey */
for(i = 0; i < NCACHED; ++i)
SWAP32(p); /* spares */
SWAP32(p); /* threshold */
SWAP32(p); /* file id lo */
SWAP32(p); /* file id hi */
SWAP32(p); /* sdb id lo */
SWAP32(p); /* sdb id hi */
p += 54 * sizeof(uint32); /* unused */
SWAP32(p); /* crypto_magic */
return 0;
}
|
papyrussolution/OpenPapyrus
|
Src/OSF/BDB-6232/hash_conv.c
|
C
|
agpl-3.0
| 2,499
|
[](https://runbot.odoo-community.org/runbot/repo/github-com-oca-social-205)
[](https://travis-ci.org/OCA/social)
[](https://coveralls.io/r/OCA/social?branch=8.0)
Social addons for Odoo
======================
Addons concerning Odoo's social ERP features and messaging in general
[//]: # (addons)
Available addons
----------------
addon | version | summary
--- | --- | ---
[email_template_qweb](email_template_qweb/) | 8.0.1.0.0 | Use the QWeb templating mechanism for emails
[mail_attach_existing_attachment](mail_attach_existing_attachment/) | 8.0.1.0.0 | Adding attachment on the object by sending this one
[mail_compose_select_lang](mail_compose_select_lang/) | 8.0.1.0.0 | Select language in mail compose window
[mail_debrand](mail_debrand/) | 8.0.1.0.0 | Remove Odoo branding from email footers
[mail_follower_custom_notification](mail_follower_custom_notification/) | 8.0.1.0.0 | Let followers choose if they want to receive email notifications for a given subscription
[mail_footer_notified_partners](mail_footer_notified_partners/) | 8.0.1.0.0 | This module adds the list of notified partners in the footer of notification e-mails sent by Odoo.
[mail_forward](mail_forward/) | 8.0.7.0.0 | Add option to forward messages
[mail_full_expand](mail_full_expand/) | 8.0.3.0.0 | Expand mail in a big window
[mail_mandrill](mail_mandrill/) | 8.0.1.0.0 | Mandrill mail events integration
[mail_notification_email_template](mail_notification_email_template/) | 8.0.1.0.0 | Allows to configure message subtypes with mail templates
[mail_optional_autofollow](mail_optional_autofollow/) | 8.0.1.0.0 | Choose if you want to automatically add new recipients as followers on mail.compose.message
[mail_optional_follower_notification](mail_optional_follower_notification/) | 8.0.1.0.0 | Choose if you want to automatically notify followers on mail.compose.message
[mail_print](mail_print/) | 8.0.1.0.0 | PDF Reports to print the emails
[mail_read_new_window](mail_read_new_window/) | 8.0.1.0.0 | Open mail in new window
[mail_restrict_follower_selection](mail_restrict_follower_selection/) | 8.0.1.0.0 | Define a domain from which followers can be selected
[mail_sent](mail_sent/) | 8.0.1.0.0 | Provide a view of sent mails
[mail_template_multi_report](mail_template_multi_report/) | 8.0.1.0.0 | Multiple Reports in Email Templates
[mail_tracking](mail_tracking/) | 8.0.4.0.0 | Email tracking system for all mails sent
[mail_tracking_mailgun](mail_tracking_mailgun/) | 8.0.1.0.0 | Mail tracking and Mailgun webhooks integration
[mail_tracking_mass_mailing](mail_tracking_mass_mailing/) | 8.0.1.0.1 | Improve mass mailing email tracking
[marketing_security_group](marketing_security_group/) | 8.0.1.0.0 | Marketing extra security rules
[mass_mailing_custom_unsubscribe](mass_mailing_custom_unsubscribe/) | 8.0.2.1.0 | Customizable unsubscription process on mass mailing emails
[mass_mailing_event](mass_mailing_event/) | 8.0.1.0.0 | Link mass mailing with event for excluding recipients
[mass_mailing_keep_archives](mass_mailing_keep_archives/) | 8.0.0.0.0 | Mass Mailing Keep Archives
[mass_mailing_sending_queue](mass_mailing_sending_queue/) | 8.0.1.0.0 | A new queue for sending mass mailing
[mass_mailing_statistic_extra](mass_mailing_statistic_extra/) | 8.0.1.0.0 | Mail statistics extra info
[mass_mailing_unique](mass_mailing_unique/) | 8.0.1.0.0 | Avoids duplicate mailing lists and contacts
[portal_welcome_email_template](portal_welcome_email_template/) | 8.0.1.0.0 | Adds an customizable email template for portal user invitation
[social_media_dribbble](social_media_dribbble/) | 8.0.1.0.0 | Dribbble Extension for the social media icons from the odoo core
[social_media_tripadvisor](social_media_tripadvisor/) | 8.0.1.0.0 | Tripadvisor Extension for the social media icons from the odoo core
[social_media_xing](social_media_xing/) | 8.0.1.0.0 | Xing Extension for the social media icons from the odoo core
[website_mail_snippet_bg_color](website_mail_snippet_bg_color/) | 8.0.1.0.0 | Set any background color for any mail editor snippet
[website_mail_snippet_fixed](website_mail_snippet_fixed/) | 8.0.1.0.1 | 560px width extra building blocks
[website_mail_snippet_responsive](website_mail_snippet_responsive/) | 8.0.2.1.0 | Well... pseudo-responsive (see description)
[website_mail_snippet_table_edit](website_mail_snippet_table_edit/) | 8.0.1.0.0 | Allows you to edit any <tr> element in any snippet/template
[website_mail_snippet_vertical_resize_base](website_mail_snippet_vertical_resize_base/) | 8.0.1.0.0 | Allow input of height in pixels with just a class
[website_mass_mailing_name](website_mass_mailing_name/) | 8.0.1.0.0 | Ask for name when subscribing, and create and/or link partner
[//]: # (end addons)
Translation Status
------------------
[](https://www.transifex.com/projects/p/OCA-social-8-0)
|
open-synergy/social
|
README.md
|
Markdown
|
agpl-3.0
| 5,129
|
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2013 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2013. All rights reserved".
********************************************************************************/
/**
* Model for storing currency attribute values on other models.
*/
class CurrencyValue extends OwnedModel
{
protected function constructDerived($bean, $setDefaults)
{
assert('$bean === null || $bean instanceof RedBean_OODBBean');
assert('is_bool($setDefaults)');
parent::constructDerived($bean, $setDefaults);
if ($bean === null && $setDefaults)
{
$currentUser = Yii::app()->user->userModel;
if (!$currentUser instanceof User)
{
throw new NoCurrentUserSecurityException();
}
$this->currency = Yii::app()->currencyHelper->getActiveCurrencyForCurrentUser();
}
}
public function __toString()
{
if (trim($this->value) == '')
{
return Zurmo::t('Core', '(None)');
}
return strval($this->value);
}
public static function getDefaultMetadata()
{
$metadata = parent::getDefaultMetadata();
$metadata[__CLASS__] = array(
'members' => array(
'rateToBase',
'value',
),
'relations' => array(
'currency' => array(static::HAS_ONE, 'Currency'),
),
'rules' => array(
array('currency', 'required'),
array('rateToBase', 'required'),
array('rateToBase', 'type', 'type' => 'float'),
array('value', 'required'),
array('value', 'type', 'type' => 'float'),
array('value', 'default', 'value' => 0),
array('value', 'numerical', 'min' => 0, 'on' => 'positiveValue'),
),
'defaultSortAttribute' => 'value'
);
return $metadata;
}
public static function isTypeDeletable()
{
return true;
}
/**
* Given an id of a currency model, determine if any currency values are using this currency.
* @return true if at least one currency value model is using this currency.
* @param integer $currencyId
*/
public static function isCurrencyInUseById($currencyId)
{
assert('is_int($currencyId)');
$columnName = static::getForeignKeyName('CurrencyValue', 'currency');
$quote = DatabaseCompatibilityUtil::getQuote();
$where = "{$quote}{$columnName}{$quote} = '{$currencyId}'";
$count = CurrencyValue::getCount(null, $where);
if ($count > 0)
{
return true;
}
return false;
}
/**
* Get the rateToBase from the currency model. If the scenario is importModel, then having a rateToBase
* manually set is ok.
* @return true to signal success and that validate can proceed.
*/
public function beforeValidate()
{
if (!parent::beforeValidate())
{
return false;
}
if ($this->currency->rateToBase !== null &&
($this->rateToBase === null ||
array_key_exists('value', $this->originalAttributeValues) ||
array_key_exists('currency', $this->originalAttributeValues)) &&
!($this->getScenario() == 'importModel' && $this->rateToBase != null))
{
$this->rateToBase = $this->currency->rateToBase;
assert('$this->rateToBase !== null');
}
return true;
}
protected static function translatedAttributeLabels($language)
{
return array_merge(parent::translatedAttributeLabels($language),
array(
'currency' => Zurmo::t('ZurmoModule', 'Currency', array(), null, $language),
'rateToBase' => Zurmo::t('ZurmoModule', 'Rate To Base', array(), null, $language),
'value' => Zurmo::t('Core', 'Value', array(), null, $language),
)
);
}
}
?>
|
jhuymaier/zurmo
|
app/protected/modules/zurmo/models/CurrencyValue.php
|
PHP
|
agpl-3.0
| 6,523
|
/*
* Copyright (C) 2015 DECOIT GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.decoit.siemgui.domain.rules;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author Thomas Rix (rix@decoit.de)
*/
@Getter
@Setter
@EqualsAndHashCode
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class CorrelationRule {
private long entityId;
private long dtoId;
private String name;
private String description;
private CorrelationRuleCondition condition;
private CorrelationRuleAction action;
}
|
decoit/siem-gui-imonitor
|
src/main/java/de/decoit/siemgui/domain/rules/CorrelationRule.java
|
Java
|
agpl-3.0
| 1,269
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket::broadcast</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_socket.html" title="basic_socket">
<link rel="prev" href="bind/overload2.html" title="basic_socket::bind (2 of 2 overloads)">
<link rel="next" href="bytes_readable.html" title="basic_socket::bytes_readable">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="bind/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="bytes_readable.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_socket.broadcast"></a><a class="link" href="broadcast.html" title="basic_socket::broadcast">basic_socket::broadcast</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from socket_base.</em></span>
</p>
<p>
<a class="indexterm" name="idp113550064"></a>
Socket option to permit sending of broadcast messages.
</p>
<pre class="programlisting"><span class="keyword">typedef</span> <span class="identifier">implementation_defined</span> <span class="identifier">broadcast</span><span class="special">;</span>
</pre>
<p>
Implements the SOL_SOCKET/SO_BROADCAST socket option.
</p>
<h6>
<a name="boost_asio.reference.basic_socket.broadcast.h0"></a>
<span class="phrase"><a name="boost_asio.reference.basic_socket.broadcast.examples"></a></span><a class="link" href="broadcast.html#boost_asio.reference.basic_socket.broadcast.examples">Examples</a>
</h6>
<p>
Setting the option:
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">udp</span><span class="special">::</span><span class="identifier">socket</span> <span class="identifier">socket</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">);</span>
<span class="special">...</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">broadcast</span> <span class="identifier">option</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="identifier">socket</span><span class="special">.</span><span class="identifier">set_option</span><span class="special">(</span><span class="identifier">option</span><span class="special">);</span>
</pre>
<p>
Getting the current option value:
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">udp</span><span class="special">::</span><span class="identifier">socket</span> <span class="identifier">socket</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">);</span>
<span class="special">...</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">broadcast</span> <span class="identifier">option</span><span class="special">;</span>
<span class="identifier">socket</span><span class="special">.</span><span class="identifier">get_option</span><span class="special">(</span><span class="identifier">option</span><span class="special">);</span>
<span class="keyword">bool</span> <span class="identifier">is_set</span> <span class="special">=</span> <span class="identifier">option</span><span class="special">.</span><span class="identifier">value</span><span class="special">();</span>
</pre>
<h6>
<a name="boost_asio.reference.basic_socket.broadcast.h1"></a>
<span class="phrase"><a name="boost_asio.reference.basic_socket.broadcast.requirements"></a></span><a class="link" href="broadcast.html#boost_asio.reference.basic_socket.broadcast.requirements">Requirements</a>
</h6>
<p>
<span class="emphasis"><em>Header: </em></span><code class="literal">boost/asio/basic_socket.hpp</code>
</p>
<p>
<span class="emphasis"><em>Convenience header: </em></span><code class="literal">boost/asio.hpp</code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2017 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="bind/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="bytes_readable.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
cris-iisc/mpc-primitives
|
crislib/libscapi/lib/boost_1_64_0/doc/html/boost_asio/reference/basic_socket/broadcast.html
|
HTML
|
agpl-3.0
| 6,793
|
(function () {
'use strict';
var WindowSize = Class.create({
width: function()
{
var myWidth = 0;
if (typeof(window.innerWidth) == 'number')
{
//Non-IE
myWidth = window.innerWidth;
}
else if (document.documentElement && document.documentElement.clientWidth)
{
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
}
else if (document.body && document.body.clientWidth)
{
//IE 4 compatible
myWidth = document.body.clientWidth;
}
return myWidth;
},
height: function()
{
var myHeight = 0;
if (typeof(window.innerHeight) == 'number')
{
//Non-IE
myHeight = window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
//IE 6+ in 'standards compliant mode'
myHeight = document.documentElement.clientHeight;
}
else if (document.body && document.body.clientHeight)
{
//IE 4 compatible
myHeight = document.body.clientHeight;
}
return myHeight;
},
scrollTop: function (){
return document.viewport.getScrollOffsets()['top'];
}
});
var dateTimePicker = function (element, options){
var picker = {},
date,
viewDate,
unset = true,
input,
component = false,
widget = false,
use24Hours,
minViewModeNumber = 0,
actualFormat,
parseFormats,
currentViewMode,
datePickerModes = [
{
clsName: 'days',
navFnc: 'M',
navStep: 1
},
{
clsName: 'months',
navFnc: 'y',
navStep: 1
},
{
clsName: 'years',
navFnc: 'y',
navStep: 10
},
{
clsName: 'decades',
navFnc: 'y',
navStep: 100
}
],
viewModes = ['days', 'months', 'years', 'decades'],
verticalModes = ['top', 'bottom', 'auto'],
horizontalModes = ['left', 'right', 'auto'],
toolbarPlacements = ['default', 'top', 'bottom'],
keyMap = {
'up': 38,
38: 'up',
'down': 40,
40: 'down',
'left': 37,
37: 'left',
'right': 39,
39: 'right',
'tab': 9,
9: 'tab',
'escape': 27,
27: 'escape',
'enter': 13,
13: 'enter',
'pageUp': 33,
33: 'pageUp',
'pageDown': 34,
34: 'pageDown',
'shift': 16,
16: 'shift',
'control': 17,
17: 'control',
'space': 32,
32: 'space',
't': 84,
84: 't',
'delete': 46,
46: 'delete'
},
keyState = {},
/********************************************************************************
*
* Private functions
*
********************************************************************************/
hasTimeZone = function () {
return moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== '';
},
getMoment = function (d) {
var returnMoment;
if (d === undefined || d === null) {
returnMoment = moment(); //TODO should this use format? and locale?
} else if (moment.isDate(d) || moment.isMoment(d)) {
// If the date that is passed in is already a Date() or moment() object,
// pass it directly to moment.
returnMoment = moment(d);
} else if (hasTimeZone()) { // There is a string to parse and a default time zone
// parse with the tz function which takes a default time zone if it is not in the format string
returnMoment = moment.tz(d, parseFormats, options.useStrict, options.timeZone);
} else {
returnMoment = moment(d, parseFormats, options.useStrict);
}
if (hasTimeZone()) {
returnMoment.tz(options.timeZone);
}
return returnMoment;
},
isEnabled = function (granularity) {
if (typeof granularity !== 'string' || granularity.length > 1) {
throw new TypeError('isEnabled expects a single character string parameter');
}
switch (granularity) {
case 'y':
return actualFormat.indexOf('Y') !== -1;
case 'M':
return actualFormat.indexOf('M') !== -1;
case 'd':
return actualFormat.toLowerCase().indexOf('d') !== -1;
case 'h':
case 'H':
return actualFormat.toLowerCase().indexOf('h') !== -1;
case 'm':
return actualFormat.indexOf('m') !== -1;
case 's':
return actualFormat.indexOf('s') !== -1;
default:
return false;
}
},
hasTime = function () {
return (isEnabled('h') || isEnabled('m') || isEnabled('s'));
},
hasDate = function () {
return (isEnabled('y') || isEnabled('M') || isEnabled('d'));
},
getDatePickerTemplate = function () {
var headTemplate = [
'<thead>',
'<tr>',
'<th class="prev" data-action="previous">',
'<span class="'+options.icons.previous+'"/>',
'</th>',
'<th class="picker-switch" data-action="pickerSwitch" colspan="'+(options.calendarWeeks?'6':'5')+'"></th>',
'<th class="next" data-action="next">',
'<span class="'+options.icons.next+'"/>',
'</th>',
'</tr>',
'</thead>'
].join(''),
contTemplate = [
'<tbody>',
'<tr>',
'<td colspan="'+(options.calendarWeeks?'8':'7')+'"/>',
'</tr>',
'<tbody>'
].join('');
return [
new Element('div', {className:'datepicker-days'}).update([
'<table class="table-condensed">',
headTemplate,
'<tbody/>',
'</table>'
].join('')),
new Element('div', {className:'datepicker-months'}).update([
'<table class="table-condensed">',
headTemplate,
contTemplate,
'</table>'
].join('')),
new Element('div', {className:'datepicker-years'}).update([
'<table class="table-condensed">',
headTemplate,
contTemplate,
'</table>'
].join('')),
new Element('div', {className:'datepicker-decades'}).update([
'<table class="table-condensed">',
headTemplate,
contTemplate,
'</table>'
].join(''))
];
},
getTimePickerMainTemplate = function (){
var topRow = ['<tr>'],
middleRow = ['<tr>'],
bottomRow = ['<tr>'];
if (isEnabled('h')) {
topRow.splice(topRow.length, 0, '<td>',
'<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementHour+'" data-action="incrementHours">',
'<span class="'+options.icons.up+'"/>',
'</a>',
'</td>');
middleRow.splice(middleRow.length, 0, '<td>',
'<span class="timepicker-hour" data-time-component="hours" title="'+options.tooltips.pickHour+'" data-action="showHours"/>',
'</td>');
bottomRow.splice(bottomRow.length, 0, '<td>',
'<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementHour+'" data-action="decrementHours"/>',
'<span class="'+options.icons.down+'"/>',
'</a>',
'</td>');
}
if (isEnabled('m')) {
if (isEnabled('h')) {
topRow.push('<td class="separator"></td>');
middleRow.push('<td class="separator">:</td>');
bottomRow.push('<td class="separator"></td>');
}
topRow.splice(topRow.length, 0, '<td>',
'<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementMinute+'" data-action="incrementMinutes">',
'<span class="'+options.icons.up+'"/>',
'</a>',
'</td>');
middleRow.splice(middleRow.length, 0, '<td>',
'<span class="timepicker-minute" data-time-component="minute" title="'+options.tooltips.pickMinute+'" data-action="showMinutes"/>',
'</td>');
bottomRow.splice(bottomRow.length, 0, '<td>',
'<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementMinute+'" data-action="decrementMinutes"/>',
'<span class="'+options.icons.down+'"/>',
'</a>',
'</td>');
}
if (isEnabled('s')) {
if (isEnabled('m')) {
topRow.push('<td class="separator"></td>');
middleRow.push('<td class="separator">:</td>');
bottomRow.push('<td class="separator"></td>');
}
topRow.splice(topRow.length, 0, '<td>',
'<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementSecond+'" data-action="incrementSeconds">',
'<span class="'+options.icons.up+'"/>',
'</a>',
'</td>');
middleRow.splice(middleRow.length, 0, '<td>',
'<span class="timepicker-second" data-time-component="seconds" title="'+options.tooltips.pickSecond+'" data-action="showSeconds"/>',
'</td>');
bottomRow.splice(bottomRow.length, 0, '<td>',
'<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementSecond+'" data-action="decrementSeconds"/>',
'<span class="'+options.icons.down+'"/>',
'</a>',
'</td>');
}
if (!use24Hours){
topRow.push('<td class="separator"/>');
middleRow.splice(middleRow.length, 0, '<td>',
'<button class="btn btn-primary" data-action="togglePeriod" tabindex="-1"',
' title="'+options.tooltips.togglePeriod+'"/>',
'</td>');
bottomRow.push('<td class="separator"/>');
}
topRow.push('</tr>')
middleRow.push('</tr>')
bottomRow.push('</tr>')
var content = [
'<table class="table-condensed">',
topRow.join(''),
middleRow.join(''),
bottomRow.join(''),
'</table>'
].join('');
return new Element('div', {className:'timepicker-picker'}).update(content);
},
getTimePickerTemplate = function () {
var hoursView = new Element('div', {className:'timepicker-hours'}).update('<table class="table-condensed"></table>'),
minutesView = new Element('div', {className:'timepicker-minutes'}).update('<table class="table-condensed"></table>'),
secondsView = new Element('div', {className:'timepicker-seconds'}).update('<table class="table-condensed"></table>'),
ret = [getTimePickerMainTemplate()];
if (isEnabled('h')) {
ret.push(hoursView);
}
if (isEnabled('m')) {
ret.push(minutesView);
}
if (isEnabled('s')) {
ret.push(secondsView);
}
return ret;
},
getToolbar = function () {
var row = ['<tbody><tr>'];
if (options.showTodayButton) {
row.splice(row.length, 0,
'<td>',
'<a data-action="today" title="'+options.tooltips.today+'">',
'<span class="'+options.icons.today+'"/>',
'</a>',
'</td>'
);
}
if (!options.sideBySide && hasDate() && hasTime()){
row.splice(row.length, 0,
'<td>',
'<a data-action="togglePicker" title="'+options.tooltips.selectTime+'">',
'<span class="'+options.icons.time+'"/>',
'</a>',
'</td>'
);
}
if (options.showClear) {
row.splice(row.length, 0,
'<td>',
'<a data-action="clear" title="'+options.tooltips.clear+'">',
'<span class="'+options.icons.clear+'"/>',
'</a>',
'</td>'
);
}
if (options.showClose) {
row.splice(row.length, 0,
'<td>',
'<a data-action="close" title="'+options.tooltips.close+'">',
'<span class="'+options.icons.close+'"/>',
'</a>',
'</td>'
);
}
row.push('</tr></tbody>')
return new Element('table', { className: 'table-condensed' }).update(row.join(''));
},
getTemplate = function () {
var template = new Element('div', {className: 'bootstrap-datetimepicker-widget dropdown-menu'}),
dateView = new Element('div', {className: 'datepicker'}),
timeView = new Element('div', {className: 'timepicker'}),
content = new Element('ul', {className: 'list-unstyled'}),
toolbar = new Element('li', {className: 'picker-switch' + (options.collapse ? ' accordion-toggle' : '')}).update(getToolbar());
$A(getDatePickerTemplate()).each(function(el){
dateView.insert(el);
});
$A(getTimePickerTemplate()).each(function(el){
timeView.insert(el);
});
if (options.inline) {
template.removeClassName('dropdown-menu');
}
if (use24Hours) {
template.addClassName('usetwentyfour');
}
if (isEnabled('s') && !use24Hours) {
template.addClassName('wider');
}
if (options.sideBySide && hasDate() && hasTime()){
template.addClassName('timepicker-sbs');
if (options.toolbarPlacement === 'top') {
template.insert(toolbar);
}
template.insert(
new Element('div', {className:'row'})
.insert(dateView.addClassName('col-md-6'))
.insert(timeView.addClassName('col-md-6'))
);
if (options.toolbarPlacement === 'bottom'){
template.insert(toolbar);
}
return template;
}
if (options.toolbarPlacement === 'top'){
content.insert(toolbar);
}
if (hasDate()){
content.insert(new Element('li', {className: (options.collapse && hasTime() ? 'collapse in' : '')}).update(dateView));
}
if (options.toolbarPlacement === 'default'){
content.insert(toolbar);
}
if (hasTime()){
content.insert(new Element('li', {className: (options.collapse && hasDate() ? 'collapse' : '')}).update(timeView));
}
if (options.toolbarPlacement === 'bottom'){
content.insert(toolbar);
}
return template.insert(content);
},
dataToOptions = function(){
var dateOptions,
dataOptions = {};
if (element.match('input') || options.inline) {
dateOptions = element.retrieve('dateoptions');
} else {
dateOptions = element.select('input').first().retrieve('dateoptions');
}
if (dateOptions && dateOptions instanceof Object) {
dataOptions = Object.extend(dataOptions, dateOptions);
}
$A(options).each(function (key){
var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1);
if (dateOptions[attributeName] !== undefined) {
dataOptions[key] = dateOptions[attributeName];
}
});
return dataOptions;
},
hasFocus = function (elem){
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) &&
!!(elem.type || elem.href || ~elem.tabIndex);
},
falseFn = function (e){
e.stop();
return false;
},
place = function () {
var eLayout = (component || element).getLayout(true),
position = { top: eLayout.get('top'), left: eLayout.get('left') },
offset = (component || element).cumulativeOffset(),
vertical = options.widgetPositioning.vertical,
horizontal = options.widgetPositioning.horizontal,
parent;
/*if (options.widgetParent) {
parent = options.widgetParent.insert(widget);
} else if (element.match('input')) {
parent = element.insert({after: widget}).up();
} else if (options.inline) {
parent = element.insert(widget);
return;
} else {
parent = element;
element.childElements().first().insert({after: widget});
}*/
component.insert(widget);
parent = component;
var windowSize = new WindowSize();
var wLayout = widget.getLayout(true);
var eOuterHeight = eLayout.get('height') + eLayout.get('border-box-height');
var eOuterWidth = eLayout.get('width') + eLayout.get('border-box-width');
// Top and bottom logic
if (vertical === 'auto'){
if (offset.top + wLayout.get('height') * 1.5 >= windowSize.height() + windowSize.scrollTop() &&
wLayout.get('height') + eOuterHeight < offset.top){
vertical = 'top';
} else {
vertical = 'bottom';
}
}
var pLayout = parent.getLayout(true);
var pOuterHeight = pLayout.get('height') + pLayout.get('border-box-height');
var pOuterWidth = pLayout.get('width') + pLayout.get('border-box-width');
// Left and right logic
if (horizontal === 'auto'){
var outerWidth = wLayout.get('width') + wLayout.get('border-box-width');
if (pLayout.get('width') < offset.left + outerWidth / 2 &&
offset.left + outerWidth > windowSize.width()){
horizontal = 'right';
} else {
horizontal = 'left';
}
}
widget.addClassName('bottom');
/*if (vertical === 'top') {
widget.addClassName('top').removeClassName('bottom');
} else {
widget.addClassName('bottom').removeClassName('top');
}*/
widget.removeClassName('pull-right');
/*
if (horizontal === 'right') {
widget.addClassName('pull-right');
} else {
widget.removeClassName('pull-right');
}*/
// find the first parent element that has a non-static css positioning
if (parent.getStyle('position') === 'static'){
parent = parent.ancestors().filter(function (it) {
return $(it).getStyle('position') !== 'static';
}).first();
}
if (!parent) {
throw new Error('datetimepicker component should be placed within a non-static positioned container');
}
var parentsZindex = [0];
widget.ancestors().each(function(a){
var itemZIndex = $(a).getStyle('z-index');
if (itemZIndex !== 'auto' && Number(itemZIndex) !== 0) parentsZindex.push(Number(itemZIndex));
});
var zIndex = Math.max.apply(Math, parentsZindex) + 10;
//console.log([vertical, horizontal, position, eOuterHeight, pOuterHeight, pOuterWidth]);
/*ToDo: Correct this to properly calculate positioning var style = {
top: vertical === 'top' ? 'auto' : (position.top + eOuterHeight)+'px',
bottom: vertical === 'top' ? (pOuterHeight - (parent === element ? 0 : position.top))+'px' : 'auto',
left: horizontal === 'left' ? (parent === element ? 0 : position.left)+'px' : 'auto',
right: horizontal === 'left' ? 'auto' : (pOuterWidth - eOuterWidth - (parent === element ? 0 : position.left))+'px',
zIndex: zIndex
};*/
var style = {
top: '26px',
left: 0,
right: 'auto',
bottom: 'auto',
zIndex: zIndex
};
//console.log(style);
widget.setStyle(style);
},
notifyEvent = function (e) {
if (e.type === 'dp:change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) {
return;
}
element.fire(e.type, e);
},
viewUpdate = function (e) {
if (e === 'y') {
e = 'YYYY';
}
notifyEvent({
type: 'dp:update',
change: e,
viewDate: viewDate.clone()
});
},
showMode = function (dir) {
if (!widget) {
return;
}
if (dir){
currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir));
}
widget.select('.datepicker > div').each(function(el){
el.hide();
if (el.match('.datepicker-' + datePickerModes[currentViewMode].clsName)){
el.setStyle({display: 'block'});
}
});
},
fillDow = function () {
var row = new Element('tr'),
currentDate = viewDate.clone().startOf('w').startOf('d');
if (options.calendarWeeks === true) {
row.insert(new Element('th', {className: 'cw'}).update('#'));
}
while (currentDate.isBefore(viewDate.clone().endOf('w'))) {
row.insert(new Element('th', {className: 'dow'}).update(currentDate.format('dd')));
currentDate.add(1, 'd');
}
widget.select('.datepicker-days thead').first().insert(row);
},
isInDisabledDates = function (testDate) {
return options.disabledDates[testDate.format('YYYY-MM-DD')] === true;
},
isInEnabledDates = function (testDate) {
return options.enabledDates[testDate.format('YYYY-MM-DD')] === true;
},
isInDisabledHours = function (testDate) {
return options.disabledHours[testDate.format('H')] === true;
},
isInEnabledHours = function (testDate) {
return options.enabledHours[testDate.format('H')] === true;
},
isValid = function (targetMoment, granularity) {
if (!targetMoment.isValid()) {
return false;
}
if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) {
return false;
}
if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) {
return false;
}
if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) {
return false;
}
if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) {
return false;
}
if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) {
return false;
}
if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) {
return false;
}
if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) {
return false;
}
if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) {
var found = false;
$A(options.disabledTimeIntervals).each(function (it) {
if (targetMoment.isBetween(it[0], it[1])) {
found = true;
return false;
}
});
if (found) {
return false;
}
}
return true;
},
fillMonths = function () {
var spans = [],
monthsShort = viewDate.clone().startOf('y').startOf('d'),
tdMonths = widget.select('.datepicker-months td').first();
tdMonths.update('');
while (monthsShort.isSame(viewDate, 'y')) {
//spans.push($('<span>').attr('data-action', 'selectMonth').addClassName('month').text(monthsShort.format('MMM')));
tdMonths.insert(new Element('span', {'data-action':'selectMonth', className: 'month'}).update(monthsShort.format('MMM')));
monthsShort.add(1, 'M');
}
//widget.find('.datepicker-months td').empty().append(spans);
},
updateMonths = function () {
var monthsView = widget.select('.datepicker-months').first(),
monthsViewHeader = monthsView.select('th'),
months = monthsView.select('tbody').first().select('span');
var mvh0 = Prototype.Selector.find(monthsViewHeader, 'th', 0);
if (mvh0 && mvh0.down('span')) mvh0.down('span').writeAttribute('title', options.tooltips.prevYear);
var mvh1 = Prototype.Selector.find(monthsViewHeader, 'th', 1);
if (mvh1 && mvh1.down('span')) mvh1.down('span').writeAttribute('title', options.tooltips.selectYear);
var mvh2 = Prototype.Selector.find(monthsViewHeader, 'th', 2);
if (mvh2 && mvh2.down('span')) mvh2.down('span').writeAttribute('title', options.tooltips.nextYear);
monthsView.select('.disabled').each(function(el){el.removeClassName('disabled');});
if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) {
mvh0.addClassName('disabled');
}
mvh1.update(viewDate.year());
if (!isValid(viewDate.clone().add(1, 'y'), 'y')) {
mvh2.addClassName('disabled');
}
months.each(function (el){el.removeClassName('active');});
if (date.isSame(viewDate, 'y') && !unset) {
Prototype.Selector.find(months, 'span', date.month()).addClassName('active');
}
months.each(function (month, index) {
if (!isValid(viewDate.clone().month(index), 'M')) {
month.addClassName('disabled');
}
});
},
updateYears = function () {
var yearsView = widget.select('.datepicker-years').first(),
yearsViewHeader = yearsView.select('th'),
startYear = viewDate.clone().subtract(5, 'y'),
endYear = viewDate.clone().add(6, 'y'),
html = '';
var yvh0 = Prototype.Selector.find(yearsViewHeader, 'th', 0);
if (yvh0 && yvh0.down('span')) yvh0.down('span').writeAttribute('title', options.tooltips.prevDecade);
var yvh1 = Prototype.Selector.find(yearsViewHeader, 'th', 1);
if (yvh1 && yvh1.down('span')) yvh1.down('span').writeAttribute('title', options.tooltips.selectDecade);
var yvh2 = Prototype.Selector.find(yearsViewHeader, 'th', 2);
if (yvh1 && yvh2.down('span')) yvh2.down('span').writeAttribute('title', options.tooltips.nextDecade);
yearsView.select('.disabled').each(function(el){el.removeClassName('disabled');});
if (options.minDate && options.minDate.isAfter(startYear, 'y')) {
yvh0.addClassName('disabled');
}
yvh1.update(startYear.year() + '-' + endYear.year());
if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) {
yvh2.addClassName('disabled');
}
while (!startYear.isAfter(endYear, 'y')) {
html += '<span data-action="selectYear" class="year' + (startYear.isSame(date, 'y') && !unset ? ' active' : '') + (!isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>';
startYear.add(1, 'y');
}
yearsView.select('td').each(function(td){ td.update(html);});
},
updateDecades = function () {
var decadesView = widget.select('.datepicker-decades').first(),
decadesViewHeader = decadesView.select('th'),
startDecade = moment({ y: viewDate.year() - (viewDate.year() % 100) - 1 }),
endDecade = startDecade.clone().add(100, 'y'),
startedAt = startDecade.clone(),
minDateDecade = false,
maxDateDecade = false,
endDecadeYear,
html = '';
var dvh0 = Prototype.Selector.find(decadesViewHeader, 'th', 0);
if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevCentury);
var dvh1 = Prototype.Selector.find(decadesViewHeader, 'th', 1);
var dvh2 = Prototype.Selector.find(decadesViewHeader, 'th', 2);
if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextCentury);
decadesView.select('.disabled').each(function(el){el.removeClassName('disabled');});
if (startDecade.isSame(moment({ y: 1900 })) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) {
dvh0.addClassName('disabled');
}
dvh1.update(startDecade.year() + '-' + endDecade.year());
if (startDecade.isSame(moment({ y: 2000 })) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) {
dvh2.addClassName('disabled');
}
while (!startDecade.isAfter(endDecade, 'y')) {
endDecadeYear = startDecade.year() + 12;
minDateDecade = options.minDate && options.minDate.isAfter(startDecade, 'y') && options.minDate.year() <= endDecadeYear;
maxDateDecade = options.maxDate && options.maxDate.isAfter(startDecade, 'y') && options.maxDate.year() <= endDecadeYear;
html += '<span data-action="selectDecade" class="decade' + (date.isAfter(startDecade) && date.year() <= endDecadeYear ? ' active' : '') +
(!isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>';
startDecade.add(12, 'y');
}
html += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even
decadesView.select('td').each(function(td){td.update(html);});
dvh1.update((startedAt.year() + 1) + '-' + (startDecade.year()));
},
fillDate = function () {
var daysView = widget.select('.datepicker-days').first(),
daysViewHeader = daysView.select('th'),
currentDate,
html = [],
row,
clsNames = [],
i;
if (!hasDate()) {
return;
}
var dvh0 = Prototype.Selector.find(daysViewHeader, 'th', 0);
if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevMonth);
var dvh1 = Prototype.Selector.find(daysViewHeader, 'th', 1);
if (dvh1 && dvh1.down('span')) dvh1.down('span').writeAttribute('title', options.tooltips.selectMonth);
var dvh2 = Prototype.Selector.find(daysViewHeader, 'th', 2);
if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextMonth);
daysView.select('.disabled').each(function(el) { el.removeClassName('disabled');});
dvh1.update(viewDate.format(options.dayViewHeaderFormat));
if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) {
dvh0.addClassName('disabled');
}
if (!isValid(viewDate.clone().add(1, 'M'), 'M')) {
dvh2.addClassName('disabled');
}
currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d');
for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks)
if (currentDate.weekday() === 0) {
row = new Element('tr');
if (options.calendarWeeks) {
row.insert('<td class="cw">' + currentDate.week() + '</td>');
}
html.push(row);
}
clsNames = ['day'];
if (currentDate.isBefore(viewDate, 'M')) {
clsNames.push('old');
}
if (currentDate.isAfter(viewDate, 'M')) {
clsNames.push('new');
}
if (currentDate.isSame(date, 'd') && !unset) {
clsNames.push('active');
}
if (!isValid(currentDate, 'd')) {
clsNames.push('disabled');
}
if (currentDate.isSame(getMoment(), 'd')) {
clsNames.push('today');
}
if (currentDate.day() === 0 || currentDate.day() === 6) {
clsNames.push('weekend');
}
notifyEvent({
type: 'dp:classify',
date: currentDate,
classNames: clsNames
});
row.insert('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="' + clsNames.join(' ') + '">' + currentDate.date() + '</td>');
currentDate.add(1, 'd');
}
var tbody = daysView.select('tbody').first().update('');
$A(html).each(function (it){
tbody.insert(it);
})
updateMonths();
updateYears();
updateDecades();
},
fillHours = function () {
var table = widget.select('.timepicker-hours table').first(),
currentHour = viewDate.clone().startOf('d'),
html = [],
row = new Element('tr');
if (viewDate.hour() > 11 && !use24Hours) {
currentHour.hour(12);
}
while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) {
if (currentHour.hour() % 4 === 0) {
row = new Element('tr');
html.push(row);
}
row.insert('<td data-action="selectHour" class="hour' + (!isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(use24Hours ? 'HH' : 'hh') + '</td>');
currentHour.add(1, 'h');
}
table.update('');
$A(html).each(function (r){table.insert(r);});
},
fillMinutes = function () {
var table = widget.select('.timepicker-minutes table').first(),
currentMinute = viewDate.clone().startOf('h'),
html = [],
row = new Element('tr'),
step = options.stepping === 1 ? 5 : options.stepping;
while (viewDate.isSame(currentMinute, 'h')) {
if (currentMinute.minute() % (step * 4) === 0) {
row = new Element('tr');
html.push(row);
}
row.insert('<td data-action="selectMinute" class="minute' + (!isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>');
currentMinute.add(step, 'm');
}
table.update('');
$A(html).each(function(r){table.insert(r);});
},
fillSeconds = function () {
var table = widget.select('.timepicker-seconds table').first(),
currentSecond = viewDate.clone().startOf('m'),
html = [],
row = new Element('tr');
if (!table) return;
while (viewDate.isSame(currentSecond, 'm')) {
if (currentSecond.second() % 20 === 0) {
row = new Element('tr');
html.push(row);
}
row.insert('<td data-action="selectSecond" class="second' + (!isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>');
currentSecond.add(5, 's');
}
table.update('');
$A(html).each(function(r){table.insert(r);});
},
fillTime = function () {
var toggle, newDate, timeComponents = widget.select('.timepicker span[data-time-component]');
if (!use24Hours) {
toggle = widget.select('.timepicker [data-action=togglePeriod]').first();
newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h');
toggle.update(date.format('A'));
if (isValid(newDate, 'h')) {
toggle.removeClassName('disabled');
} else {
toggle.addClassName('disabled');
}
}
timeComponents.each(function(tc){
if (tc.match('[data-time-component=hours]')){
tc.update(date.format(use24Hours ? 'HH' : 'hh'));
}
if (tc.match('[data-time-component=minute]')){
tc.update(date.format('mm'));
}
if (tc.match('[data-time-component=seconds]')){
tc.update(date.format(date.format('ss')));
}
})
if (isEnabled('h')) fillHours();
if (isEnabled('m')) fillMinutes();
if (isEnabled('s')) fillSeconds();
},
update = function () {
if (!widget) {
return;
}
fillDate();
fillTime();
},
setValue = function (targetMoment) {
var oldDate = unset ? null : date;
// case of calling setValue(null or false)
if (!targetMoment) {
unset = true;
input.setValue('');
input.store(date, '');
element.store('date', '');
notifyEvent({
type: 'dp:change',
date: false,
oldDate: oldDate
});
update();
return;
}
targetMoment = targetMoment.clone().locale(options.locale);
if (hasTimeZone()) {
targetMoment.tz(options.timeZone);
}
if (options.stepping !== 1) {
targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping)).seconds(0);
while (options.minDate && targetMoment.isBefore(options.minDate)) {
targetMoment.add(options.stepping, 'minutes');
}
}
if (isValid(targetMoment)) {
date = targetMoment;
viewDate = date.clone();
input.setValue(date.format(actualFormat));
element.store('date', date.format(actualFormat));
input.store('date', date.toISOString());
unset = false;
update();
notifyEvent({
type: 'dp:change',
date: date.clone(),
oldDate: oldDate
});
} else {
if (!options.keepInvalid) {
Form.Element.setValue(input, unset ? '' : date.format(actualFormat));
} else {
notifyEvent({
type: 'dp:change',
date: targetMoment,
oldDate: oldDate
});
}
notifyEvent({
type: 'dp:error',
date: targetMoment,
oldDate: oldDate
});
}
},
///
// Hides the widget. Possibly will emit dp:hide
//
hide = function () {
var transitioning = false;
if (!widget) {
return picker;
}
// Ignore event if in the middle of a picker transition
widget.select('.collapse').each(function (it) {
var collapseData = it.retrieve('collapse');
if (collapseData && collapseData.transitioning) {
transitioning = true;
return false;
}
return true;
});
if (transitioning) {
return picker;
}
if (component && component.hasClassName('btn')) {
component.toggleClassName('active');
}
widget.hide();
Event.stopObserving(window, 'resize', place);
widget.stopObserving('click', doAction);
widget.stopObserving('mousedown', falseFn);
widget.remove();
widget = false;
notifyEvent({
type: 'dp:hide',
date: date.clone()
});
input.blur();
viewDate = date.clone();
return picker;
},
clear = function () {
setValue(null);
},
parseInputDate = function (inputDate) {
if (options.parseInputDate === undefined) {
if (!moment.isMoment(inputDate) || inputDate instanceof Date) {
inputDate = getMoment(inputDate);
}
} else {
inputDate = options.parseInputDate(inputDate);
}
//inputDate.locale(options.locale);
return inputDate;
},
/********************************************************************************
*
* Widget UI interaction functions
*
********************************************************************************/
actions = {
next: function () {
var navFnc = datePickerModes[currentViewMode].navFnc;
viewDate.add(datePickerModes[currentViewMode].navStep, navFnc);
fillDate();
viewUpdate(navFnc);
},
previous: function () {
var navFnc = datePickerModes[currentViewMode].navFnc;
viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc);
fillDate();
viewUpdate(navFnc);
},
pickerSwitch: function () {
showMode(1);
},
selectMonth: function (e) {
//var month = $(e.target).closest('tbody').find('span').index($(e.target));
var month = $(e.target).previousSiblings().size();
viewDate.month(month);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()).month(viewDate.month()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('M');
},
selectYear: function (e) {
var year = parseInt($(e.target).innerText, 10) || 0;
viewDate.year(year);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('YYYY');
},
selectDecade: function (e) {
var year = parseInt($(e.target).readAttribute('data-selection'), 10) || 0;
viewDate.year(year);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('YYYY');
},
selectDay: function (e) {
var day = viewDate.clone();
if ($(e.target).match('.old')) {
day.subtract(1, 'M');
}
if ($(e.target).match('.new')) {
day.add(1, 'M');
}
setValue(day.date(parseInt($(e.target).innerText, 10)));
if (!hasTime() && !options.keepOpen && !options.inline) {
hide();
}
},
incrementHours: function () {
var newDate = date.clone().add(1, 'h');
if (isValid(newDate, 'h')) {
setValue(newDate);
}
},
incrementMinutes: function () {
var newDate = date.clone().add(options.stepping, 'm');
if (isValid(newDate, 'm')) {
setValue(newDate);
}
},
incrementSeconds: function () {
var newDate = date.clone().add(1, 's');
if (isValid(newDate, 's')) {
setValue(newDate);
}
},
decrementHours: function () {
var newDate = date.clone().subtract(1, 'h');
if (isValid(newDate, 'h')) {
setValue(newDate);
}
},
decrementMinutes: function () {
var newDate = date.clone().subtract(options.stepping, 'm');
if (isValid(newDate, 'm')) {
setValue(newDate);
}
},
decrementSeconds: function () {
var newDate = date.clone().subtract(1, 's');
if (isValid(newDate, 's')) {
setValue(newDate);
}
},
togglePeriod: function () {
setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'));
},
togglePicker: function (e) {
var $this = $(e.target),
$parent = $this.up('ul'),
expanded = $parent.select('.in').first(),
closed = $parent.select('.collapse:not(.in)').first(),
collapseData;
if (expanded) {
collapseData = expanded.retrieve('collapse');
if (collapseData && collapseData.transitioning) {
return;
}
expanded.removeClassName('in');
closed.addClassName('in');
if ($this.match('span')) {
$this.toggleClassName(options.icons.time + ' ' + options.icons.date);
} else {
$this.down('span').toggleClassName(options.icons.time + ' ' + options.icons.date);
}
// NOTE: uncomment if toggled state will be restored in show()
//if (component) {
// component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date);
//}
}
},
showPicker: function () {
widget.select('.timepicker > div:not(.timepicker-picker)').each(function(el){el.hide();});
widget.down('.timepicker .timepicker-picker').show();
},
showHours: function () {
widget.down('.timepicker .timepicker-picker').hide();
widget.down('.timepicker .timepicker-hours').show();
},
showMinutes: function () {
widget.down('.timepicker .timepicker-picker').hide();
widget.down('.timepicker .timepicker-minutes').show();
},
showSeconds: function () {
widget.down('.timepicker .timepicker-picker').hide();
widget.down('.timepicker .timepicker-seconds').show();
},
selectHour: function (e) {
var hour = parseInt($(e.target).innerText, 10);
if (!use24Hours) {
if (date.hours() >= 12) {
if (hour !== 12) {
hour += 12;
}
} else {
if (hour === 12) {
hour = 0;
}
}
}
setValue(date.clone().hours(hour));
actions.showPicker.call(picker);
},
selectMinute: function (e) {
setValue(date.clone().minutes(parseInt($(e.target).innerText, 10)));
actions.showPicker.call(picker);
},
selectSecond: function (e) {
setValue(date.clone().seconds(parseInt($(e.target).innerText, 10)));
actions.showPicker.call(picker);
},
clear: clear,
today: function () {
var todaysDate = getMoment();
if (isValid(todaysDate, 'd')) {
setValue(todaysDate);
}
},
close: hide
},
doAction = function (e) {
Event.stop(e);
var actionEl = e.findElement('[data-action]');
if (!actionEl) return false;
if ($(e.target).match('.disabled')){
return false;
}
actions[actionEl.readAttribute('data-action')].apply(picker, arguments);
return false;
},
///
// Shows the widget. Possibly will emit dp:show and dp:change
///
show = function () {
var currentMoment,
useCurrentGranularity = {
'year': function (m) {
return m.month(0).date(1).hours(0).seconds(0).minutes(0);
},
'month': function (m) {
return m.date(1).hours(0).seconds(0).minutes(0);
},
'day': function (m) {
return m.hours(0).seconds(0).minutes(0);
},
'hour': function (m) {
return m.seconds(0).minutes(0);
},
'minute': function (m) {
return m.seconds(0);
}
};
if (input.readAttribute('disabled') || (!options.ignoreReadonly && input.readAttribute('readonly')) || widget) {
return picker;
}
var val = input.retrieve('date');
if (!val){
val = $F(input);
val = moment(val.trim(), actualFormat);
}
else {
val = moment(val.trim());
}
if (val !== undefined) { //} && val.trim().length !== 0) {
setValue(parseInputDate(val));
} else if (unset && options.useCurrent && (options.inline || (input.match('input') && val.trim().length === 0))) {
currentMoment = getMoment();
if (typeof options.useCurrent === 'string') {
currentMoment = useCurrentGranularity[options.useCurrent](currentMoment);
}
setValue(currentMoment);
}
widget = getTemplate();
fillDow();
fillMonths();
widget.down('.timepicker-hours') && widget.down('.timepicker-hours').hide();
widget.down('.timepicker-minutes') && widget.down('.timepicker-minutes').hide();
widget.down('.timepicker-seconds') && widget.down('.timepicker-seconds').hide(); //ToDo: Enable this when safe
update();
showMode();
Event.observe(window, 'resize', place);
widget.observe('click', doAction); // this handles clicks on the widget
widget.observe('mousedown', falseFn);
if (component && component.hasClassName('btn')) {
component.toggleClassName('active');
}
place();
if (options.focusOnShow && !hasFocus(input)) {
//return elem === document.activeElement && ( elem.type || elem.href );
input.focus();
}
notifyEvent({
type: 'dp:show'
});
return picker;
},
///
// Shows or hides the widget
///
toggle = function () {
if (input.match('[disabled]')) return;
return (widget ? hide() : show());
},
keydown = function (e) {
var handler = null,
index,
index2,
pressedKeys = [],
pressedModifiers = {},
currentKey = e.which,
keyBindKeys,
allModifiersPressed,
pressed = 'p';
keyState[currentKey] = pressed;
for (index in keyState) {
if (keyState.hasOwnProperty(index) && keyState[index] === pressed) {
pressedKeys.push(index);
if (parseInt(index, 10) !== currentKey) {
pressedModifiers[index] = true;
}
}
}
for (index in options.keyBinds) {
if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') {
keyBindKeys = index.split(' ');
if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) {
allModifiersPressed = true;
for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) {
if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) {
allModifiersPressed = false;
break;
}
}
if (allModifiersPressed) {
handler = options.keyBinds[index];
break;
}
}
}
}
if (handler) {
handler.call(picker, widget);
e.stopPropagation();
e.preventDefault();
}
},
keyup = function (e) {
keyState[e.which] = 'r';
e.stopPropagation();
e.preventDefault();
},
change = function (e) {
var val = $F($(e.target)).trim(),
parsedDate = val ? parseInputDate(val) : null;
setValue(parsedDate);
e.stopImmediatePropagation();
return false;
},
attachDatePickerElementEvents = function () {
input.observe('change', change);
input.observe('blur', options.debug ? Prototype.emptyFunction : hide);
input.observe('keydown', keydown);
input.observe('keyup', keyup);
input.observe('focus', options.allowInputToggle ? show : Prototype.emptyFunction);
if (element.match('input')) {
input.observe('focus', show);
} else if (component) {
component.observe('click', toggle);
component.observe('mousedown', falseFn);
}
},/*
detachDatePickerElementEvents = function () {
input.off({
'change': change,
'blur': blur,
'keydown': keydown,
'keyup': keyup,
'focus': options.allowInputToggle ? hide : ''
});
if (element.is('input')) {
input.off({
'focus': show
});
} else if (component) {
component.off('click', toggle);
component.off('mousedown', false);
}
},
indexGivenDates = function (givenDatesArray) {
// Store given enabledDates and disabledDates as keys.
// This way we can check their existence in O(1) time instead of looping through whole array.
// (for example: options.enabledDates['2014-02-27'] === true)
var givenDatesIndexed = {};
$.each(givenDatesArray, function () {
var dDate = parseInputDate(this);
if (dDate.isValid()) {
givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true;
}
});
return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false;
},
indexGivenHours = function (givenHoursArray) {
// Store given enabledHours and disabledHours as keys.
// This way we can check their existence in O(1) time instead of looping through whole array.
// (for example: options.enabledHours['2014-02-27'] === true)
var givenHoursIndexed = {};
$.each(givenHoursArray, function () {
givenHoursIndexed[this] = true;
});
return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false;
},*/
initFormatting = function () {
var format = options.format || 'L LT';
actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) {
var newinput = date.localeData().longDateFormat(formatInput) || formatInput;
return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740
return date.localeData().longDateFormat(formatInput2) || formatInput2;
});
});
parseFormats = options.extraFormats ? options.extraFormats.slice() : [];
if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0){
parseFormats.push(actualFormat);
}
use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1);
if (isEnabled('y')){
minViewModeNumber = 2;
}
if (isEnabled('M')){
minViewModeNumber = 1;
}
if (isEnabled('d')){
minViewModeNumber = 0;
}
currentViewMode = Math.max(minViewModeNumber, currentViewMode);
if (!unset) {
setValue(date);
}
};
/********************************************************************************
*
* Public API functions
* =====================
*
* Important: Do not expose direct references to private objects or the options
* object to the outer world. Always return a clone when returning values or make
* a clone when setting a private variable.
*
********************************************************************************/
picker.destroy = function () {
///<summary>Destroys the widget and removes all attached event listeners</summary>
hide();
detachDatePickerElementEvents();
//element.removeData('DateTimePicker');
//element.removeData('date');
};
picker.toggle = toggle;
picker.show = show;
picker.hide = hide;
picker.disable = function () {
///<summary>Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
///If the widget was visible before that call it is hidden. Possibly emits dp:hide</summary>
hide();
if (component && component.hasClassName('btn')) {
component.addClassName('disabled');
}
input.prop('disabled', true);
return picker;
};
picker.enable = function () {
///<summary>Enables the input element, the component is attached to, by removing disabled attribute from it.</summary>
if (component && component.hasClassName('btn')) {
component.removeClassName('disabled');
}
input.prop('disabled', false);
return picker;
};
picker.ignoreReadonly = function (ignoreReadonly) {
if (arguments.length === 0) {
return options.ignoreReadonly;
}
if (typeof ignoreReadonly !== 'boolean') {
throw new TypeError('ignoreReadonly () expects a boolean parameter');
}
options.ignoreReadonly = ignoreReadonly;
return picker;
};
picker.options = function (newOptions) {
if (arguments.length === 0) {
return Object.extend({}, options);
}
if (!(newOptions instanceof Object)) {
throw new TypeError('options() options parameter should be an object');
}
Object.extend(options, newOptions);
$H(options).each(function (pair) {
if (picker[pair.key] !== undefined) {
picker[pair.key](pair.value);
} else {
throw new TypeError('option ' + key + ' is not recognized!');
}
});
return picker;
};
picker.date = function (newDate) {
///<signature helpKeyword="$.fn.datetimepicker.date">
///<summary>Returns the component's model current date, a moment object or null if not set.</summary>
///<returns type="Moment">date.clone()</returns>
///</signature>
///<signature>
///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param>
///</signature>
if (arguments.length === 0) {
if (unset) {
return null;
}
return date.clone();
}
if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
}
setValue(newDate === null ? null : parseInputDate(newDate));
return picker;
};
picker.format = function (newFormat) {
///<summary>test su</summary>
///<param name="newFormat">info about para</param>
///<returns type="string|boolean">returns foo</returns>
if (arguments.length === 0) {
return options.format;
}
if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat);
}
options.format = newFormat;
if (actualFormat) {
initFormatting(); // reinit formatting
}
return picker;
};
picker.timeZone = function (newZone) {
if (arguments.length === 0) {
return options.timeZone;
}
if (typeof newZone !== 'string') {
throw new TypeError('newZone() expects a string parameter');
}
options.timeZone = newZone;
return picker;
};
picker.dayViewHeaderFormat = function (newFormat) {
if (arguments.length === 0) {
return options.dayViewHeaderFormat;
}
if (typeof newFormat !== 'string') {
throw new TypeError('dayViewHeaderFormat() expects a string parameter');
}
options.dayViewHeaderFormat = newFormat;
return picker;
};
picker.extraFormats = function (formats) {
if (arguments.length === 0) {
return options.extraFormats;
}
if (formats !== false && !(formats instanceof Array)) {
throw new TypeError('extraFormats() expects an array or false parameter');
}
options.extraFormats = formats;
if (parseFormats) {
initFormatting(); // reinit formatting
}
return picker;
};
picker.disabledDates = function (dates) {
///<signature helpKeyword="$.fn.datetimepicker.disabledDates">
///<summary>Returns an array with the currently set disabled dates on the component.</summary>
///<returns type="array">options.disabledDates</returns>
///</signature>
///<signature>
///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledDates if such exist.</summary>
///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
///</signature>
if (arguments.length === 0) {
return (options.disabledDates ? Object.extend({}, options.disabledDates) : options.disabledDates);
}
if (!dates) {
options.disabledDates = false;
update();
return picker;
}
if (!(dates instanceof Array)) {
throw new TypeError('disabledDates() expects an array parameter');
}
options.disabledDates = indexGivenDates(dates);
options.enabledDates = false;
update();
return picker;
};
picker.enabledDates = function (dates) {
///<signature helpKeyword="$.fn.datetimepicker.enabledDates">
///<summary>Returns an array with the currently set enabled dates on the component.</summary>
///<returns type="array">options.enabledDates</returns>
///</signature>
///<signature>
///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary>
///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
///</signature>
if (arguments.length === 0) {
return (options.enabledDates ? Object.extend({}, options.enabledDates) : options.enabledDates);
}
if (!dates) {
options.enabledDates = false;
update();
return picker;
}
if (!(dates instanceof Array)) {
throw new TypeError('enabledDates() expects an array parameter');
}
options.enabledDates = indexGivenDates(dates);
options.disabledDates = false;
update();
return picker;
};
picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
if (arguments.length === 0) {
return options.daysOfWeekDisabled.splice(0);
}
if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
options.daysOfWeekDisabled = false;
update();
return picker;
}
if (!(daysOfWeekDisabled instanceof Array)) {
throw new TypeError('daysOfWeekDisabled() expects an array parameter');
}
options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
currentValue = parseInt(currentValue, 10);
if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
return previousValue;
}
if (previousValue.indexOf(currentValue) === -1) {
previousValue.push(currentValue);
}
return previousValue;
}, []).sort();
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'd')) {
date.add(1, 'd');
if (tries === 31) {
throw 'Tried 31 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
picker.maxDate = function (maxDate) {
if (arguments.length === 0) {
return options.maxDate ? options.maxDate.clone() : options.maxDate;
}
if ((typeof maxDate === 'boolean') && maxDate === false) {
options.maxDate = false;
update();
return picker;
}
if (typeof maxDate === 'string') {
if (maxDate === 'now' || maxDate === 'moment') {
maxDate = getMoment();
}
}
var parsedDate = parseInputDate(maxDate);
if (!parsedDate.isValid()) {
throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
}
if (options.minDate && parsedDate.isBefore(options.minDate)) {
throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
}
options.maxDate = parsedDate;
if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
setValue(options.maxDate);
}
if (viewDate.isAfter(parsedDate)) {
viewDate = parsedDate.clone().subtract(options.stepping, 'm');
}
update();
return picker;
};
picker.minDate = function (minDate) {
if (arguments.length === 0) {
return options.minDate ? options.minDate.clone() : options.minDate;
}
if ((typeof minDate === 'boolean') && minDate === false) {
options.minDate = false;
update();
return picker;
}
if (typeof minDate === 'string') {
if (minDate === 'now' || minDate === 'moment') {
minDate = getMoment();
}
}
var parsedDate = parseInputDate(minDate);
if (!parsedDate.isValid()) {
throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
}
if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
}
options.minDate = parsedDate;
if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
setValue(options.minDate);
}
if (viewDate.isBefore(parsedDate)) {
viewDate = parsedDate.clone().add(options.stepping, 'm');
}
update();
return picker;
};
picker.defaultDate = function (defaultDate) {
///<signature helpKeyword="$.fn.datetimepicker.defaultDate">
///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary>
///<returns type="Moment">date.clone()</returns>
///</signature>
///<signature>
///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary>
///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param>
///</signature>
if (arguments.length === 0) {
return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
}
if (!defaultDate) {
options.defaultDate = false;
return picker;
}
if (typeof defaultDate === 'string') {
if (defaultDate === 'now' || defaultDate === 'moment') {
defaultDate = getMoment();
} else {
defaultDate = getMoment(defaultDate);
}
}
var parsedDate = parseInputDate(defaultDate);
if (!parsedDate.isValid()) {
throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
}
if (!isValid(parsedDate)) {
throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
}
options.defaultDate = parsedDate;
if ((options.defaultDate && options.inline) || input.val().trim() === '') {
setValue(options.defaultDate);
}
return picker;
};
picker.locale = function (locale) {
if (arguments.length === 0) {
return options.locale;
}
if (!moment.localeData(locale)) {
throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
}
options.locale = locale;
options.tooltips = localeTooltips[locale] || options.locale;
date.locale(options.locale);
viewDate.locale(options.locale);
if (actualFormat) {
initFormatting(); // reinit formatting
}
if (widget) {
hide();
show();
}
return picker;
};
picker.stepping = function (stepping) {
if (arguments.length === 0) {
return options.stepping;
}
stepping = parseInt(stepping, 10);
if (isNaN(stepping) || stepping < 1) {
stepping = 1;
}
options.stepping = stepping;
return picker;
};
picker.useCurrent = function (useCurrent) {
var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
if (arguments.length === 0) {
return options.useCurrent;
}
if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
throw new TypeError('useCurrent() expects a boolean or string parameter');
}
if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
}
options.useCurrent = useCurrent;
return picker;
};
picker.collapse = function (collapse) {
if (arguments.length === 0) {
return options.collapse;
}
if (typeof collapse !== 'boolean') {
throw new TypeError('collapse() expects a boolean parameter');
}
if (options.collapse === collapse) {
return picker;
}
options.collapse = collapse;
if (widget) {
hide();
show();
}
return picker;
};
picker.icons = function (icons) {
if (arguments.length === 0) {
return Object.extend({}, options.icons);
}
if (!(icons instanceof Object)) {
throw new TypeError('icons() expects parameter to be an Object');
}
Object.extend(options.icons, icons);
if (widget) {
hide();
show();
}
return picker;
};
picker.tooltips = function (tooltips) {
if (arguments.length === 0) {
return Object.extend({}, options.tooltips);
}
if (!(tooltips instanceof Object)) {
throw new TypeError('tooltips() expects parameter to be an Object');
}
Object.extend(options.tooltips, tooltips);
if (widget) {
hide();
show();
}
return picker;
};
picker.useStrict = function (useStrict) {
if (arguments.length === 0) {
return options.useStrict;
}
if (typeof useStrict !== 'boolean') {
throw new TypeError('useStrict() expects a boolean parameter');
}
options.useStrict = useStrict;
return picker;
};
picker.sideBySide = function (sideBySide) {
if (arguments.length === 0) {
return options.sideBySide;
}
if (typeof sideBySide !== 'boolean') {
throw new TypeError('sideBySide() expects a boolean parameter');
}
options.sideBySide = sideBySide;
if (widget) {
hide();
show();
}
return picker;
};
picker.viewMode = function (viewMode) {
if (arguments.length === 0) {
return options.viewMode;
}
if (typeof viewMode !== 'string') {
throw new TypeError('viewMode() expects a string parameter');
}
if (viewModes.indexOf(viewMode) === -1) {
throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
}
options.viewMode = viewMode;
currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
showMode();
return picker;
};
picker.toolbarPlacement = function (toolbarPlacement) {
if (arguments.length === 0) {
return options.toolbarPlacement;
}
if (typeof toolbarPlacement !== 'string') {
throw new TypeError('toolbarPlacement() expects a string parameter');
}
if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
}
options.toolbarPlacement = toolbarPlacement;
if (widget) {
hide();
show();
}
return picker;
};
picker.widgetPositioning = function (widgetPositioning) {
if (arguments.length === 0) {
return Object.extend({}, options.widgetPositioning);
}
if (({}).toString.call(widgetPositioning) !== '[object Object]') {
throw new TypeError('widgetPositioning() expects an object variable');
}
if (widgetPositioning.horizontal) {
if (typeof widgetPositioning.horizontal !== 'string') {
throw new TypeError('widgetPositioning() horizontal variable must be a string');
}
widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
}
options.widgetPositioning.horizontal = widgetPositioning.horizontal;
}
if (widgetPositioning.vertical) {
if (typeof widgetPositioning.vertical !== 'string') {
throw new TypeError('widgetPositioning() vertical variable must be a string');
}
widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
}
options.widgetPositioning.vertical = widgetPositioning.vertical;
}
update();
return picker;
};
picker.calendarWeeks = function (calendarWeeks) {
if (arguments.length === 0) {
return options.calendarWeeks;
}
if (typeof calendarWeeks !== 'boolean') {
throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
}
options.calendarWeeks = calendarWeeks;
update();
return picker;
};
picker.showTodayButton = function (showTodayButton) {
if (arguments.length === 0) {
return options.showTodayButton;
}
if (typeof showTodayButton !== 'boolean') {
throw new TypeError('showTodayButton() expects a boolean parameter');
}
options.showTodayButton = showTodayButton;
if (widget) {
hide();
show();
}
return picker;
};
picker.showClear = function (showClear) {
if (arguments.length === 0) {
return options.showClear;
}
if (typeof showClear !== 'boolean') {
throw new TypeError('showClear() expects a boolean parameter');
}
options.showClear = showClear;
if (widget) {
hide();
show();
}
return picker;
};
picker.widgetParent = function (widgetParent) {
if (arguments.length === 0) {
return options.widgetParent;
}
if (typeof widgetParent === 'string') {
widgetParent = $(widgetParent);
}
if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof Element))) {
throw new TypeError('widgetParent() expects a string or a Element object parameter');
}
options.widgetParent = widgetParent;
if (widget) {
hide();
show();
}
return picker;
};
picker.keepOpen = function (keepOpen) {
if (arguments.length === 0) {
return options.keepOpen;
}
if (typeof keepOpen !== 'boolean') {
throw new TypeError('keepOpen() expects a boolean parameter');
}
options.keepOpen = keepOpen;
return picker;
};
picker.focusOnShow = function (focusOnShow) {
if (arguments.length === 0) {
return options.focusOnShow;
}
if (typeof focusOnShow !== 'boolean') {
throw new TypeError('focusOnShow() expects a boolean parameter');
}
options.focusOnShow = focusOnShow;
return picker;
};
picker.inline = function (inline) {
if (arguments.length === 0) {
return options.inline;
}
if (typeof inline !== 'boolean') {
throw new TypeError('inline() expects a boolean parameter');
}
options.inline = inline;
return picker;
};
picker.clear = function () {
clear();
return picker;
};
picker.keyBinds = function (keyBinds) {
if (arguments.length === 0) {
return options.keyBinds;
}
options.keyBinds = keyBinds;
return picker;
};
picker.getMoment = function (d) {
return getMoment(d);
};
picker.debug = function (debug) {
if (typeof debug !== 'boolean') {
throw new TypeError('debug() expects a boolean parameter');
}
options.debug = debug;
return picker;
};
picker.allowInputToggle = function (allowInputToggle) {
if (arguments.length === 0) {
return options.allowInputToggle;
}
if (typeof allowInputToggle !== 'boolean') {
throw new TypeError('allowInputToggle() expects a boolean parameter');
}
options.allowInputToggle = allowInputToggle;
return picker;
};
picker.showClose = function (showClose) {
if (arguments.length === 0) {
return options.showClose;
}
if (typeof showClose !== 'boolean') {
throw new TypeError('showClose() expects a boolean parameter');
}
options.showClose = showClose;
return picker;
};
picker.keepInvalid = function (keepInvalid) {
if (arguments.length === 0) {
return options.keepInvalid;
}
if (typeof keepInvalid !== 'boolean') {
throw new TypeError('keepInvalid() expects a boolean parameter');
}
options.keepInvalid = keepInvalid;
return picker;
};
picker.datepickerInput = function (datepickerInput) {
if (arguments.length === 0) {
return options.datepickerInput;
}
if (typeof datepickerInput !== 'string') {
throw new TypeError('datepickerInput() expects a string parameter');
}
options.datepickerInput = datepickerInput;
return picker;
};
picker.parseInputDate = function (parseInputDate) {
if (arguments.length === 0) {
return options.parseInputDate;
}
if (typeof parseInputDate !== 'function') {
throw new TypeError('parseInputDate() sholud be as function');
}
options.parseInputDate = parseInputDate;
return picker;
};
picker.disabledTimeIntervals = function (disabledTimeIntervals) {
///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals">
///<summary>Returns an array with the currently set disabled dates on the component.</summary>
///<returns type="array">options.disabledTimeIntervals</returns>
///</signature>
///<signature>
///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledDates if such exist.</summary>
///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
///</signature>
if (arguments.length === 0) {
return (options.disabledTimeIntervals ? Object.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
}
if (!disabledTimeIntervals) {
options.disabledTimeIntervals = false;
update();
return picker;
}
if (!(disabledTimeIntervals instanceof Array)) {
throw new TypeError('disabledTimeIntervals() expects an array parameter');
}
options.disabledTimeIntervals = disabledTimeIntervals;
update();
return picker;
};
picker.disabledHours = function (hours) {
///<signature helpKeyword="$.fn.datetimepicker.disabledHours">
///<summary>Returns an array with the currently set disabled hours on the component.</summary>
///<returns type="array">options.disabledHours</returns>
///</signature>
///<signature>
///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledHours if such exist.</summary>
///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param>
///</signature>
if (arguments.length === 0) {
return (options.disabledHours ? Object.extend({}, options.disabledHours) : options.disabledHours);
}
if (!hours) {
options.disabledHours = false;
update();
return picker;
}
if (!(hours instanceof Array)) {
throw new TypeError('disabledHours() expects an array parameter');
}
options.disabledHours = indexGivenHours(hours);
options.enabledHours = false;
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'h')) {
date.add(1, 'h');
if (tries === 24) {
throw 'Tried 24 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
picker.enabledHours = function (hours) {
///<signature helpKeyword="$.fn.datetimepicker.enabledHours">
///<summary>Returns an array with the currently set enabled hours on the component.</summary>
///<returns type="array">options.enabledHours</returns>
///</signature>
///<signature>
///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary>
///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param>
///</signature>
if (arguments.length === 0) {
return (options.enabledHours ? Object.extend({}, options.enabledHours) : options.enabledHours);
}
if (!hours) {
options.enabledHours = false;
update();
return picker;
}
if (!(hours instanceof Array)) {
throw new TypeError('enabledHours() expects an array parameter');
}
options.enabledHours = indexGivenHours(hours);
options.disabledHours = false;
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'h')) {
date.add(1, 'h');
if (tries === 24) {
throw 'Tried 24 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
/**
* Returns the component's model current viewDate, a moment object or null if not set. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.
* @param {Takes string, viewDate, moment, null parameter.} newDate
* @returns {viewDate.clone()}
*/
picker.viewDate = function (newDate) {
if (arguments.length === 0) {
return viewDate.clone();
}
if (!newDate) {
viewDate = date.clone();
return picker;
}
if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
}
viewDate = parseInputDate(newDate);
viewUpdate();
return picker;
};
// initializing element and component attributes
if (element.match('input')) {
input = element;
} else {
input = element.select(options.datepickerInput);
if (input.length === 0) {
input = element.select('input').first();
} else if (!input.match('input')) {
throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element');
}
}
if (element.hasClassName('input-group')) {
// in case there is more then one 'input-group-addon' Issue #48
if (element.select('.datepickerbutton').length === 0) {
component = element.select('.input-group-addon').first();
} else {
component = element.select('.datepickerbutton').first();
}
}
if (!options.inline && !input.match('input')) {
throw new Error('Could not initialize DateTimePicker without an input element');
}
// Set defaults for date here now instead of in var declaration
date = getMoment();
viewDate = date.clone();
Object.extend(options, dataToOptions());
picker.options(options);
initFormatting();
attachDatePickerElementEvents();
if (input.readAttribute('disabled')) {
picker.disable();
}
var val = input.retrieve('date');
if (!val) val = $F(input).trim();
else val = moment(val);
if (input.match('input') && val.length !== 0) {
setValue(parseInputDate(val));
}
else if (options.defaultDate && (input.readAttribute('placeholder') === undefined || input.readAttribute('placeholder') === null)) {
setValue(options.defaultDate);
}
if (options.inline) {
show();
}
return picker;
};
/********************************************************************************
*
* jQuery plugin constructor and defaults object
*
********************************************************************************/
/**
* See (http://jquery.com/).
* @name jQuery
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
*/
/**
* See (http://jquery.com/)
* @name fn
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
* @memberOf jQuery
*/
/**
* Show comments
* @class datetimepicker
* @memberOf jQuery.fn
*/
var dpDefaults = {
timeZone: '',
format: false,
dayViewHeaderFormat: 'MMMM YYYY',
extraFormats: false,
stepping: 1,
minDate: false,
maxDate: false,
useCurrent: true,
collapse: true,
locale: moment.locale(),
defaultDate: false,
disabledDates: false,
enabledDates: false,
icons: {
time: 'glyphicon glyphicon-time',
date: 'glyphicon glyphicon-calendar',
up: 'glyphicon glyphicon-chevron-up',
down: 'glyphicon glyphicon-chevron-down',
previous: 'glyphicon glyphicon-chevron-left',
next: 'glyphicon glyphicon-chevron-right',
today: 'glyphicon glyphicon-screenshot',
clear: 'glyphicon glyphicon-trash',
close: 'glyphicon glyphicon-remove'
},
tooltips: {
today: 'Go to today',
clear: 'Clear selection',
close: 'Close the picker',
selectMonth: 'Select Month',
prevMonth: 'Previous Month',
nextMonth: 'Next Month',
selectYear: 'Select Year',
prevYear: 'Previous Year',
nextYear: 'Next Year',
selectDecade: 'Select Decade',
prevDecade: 'Previous Decade',
nextDecade: 'Next Decade',
prevCentury: 'Previous Century',
nextCentury: 'Next Century',
pickHour: 'Pick Hour',
incrementHour: 'Increment Hour',
decrementHour: 'Decrement Hour',
pickMinute: 'Pick Minute',
incrementMinute: 'Increment Minute',
decrementMinute: 'Decrement Minute',
pickSecond: 'Pick Second',
incrementSecond: 'Increment Second',
decrementSecond: 'Decrement Second',
togglePeriod: 'Toggle Period',
selectTime: 'Select Time'
},
useStrict: false,
sideBySide: false,
daysOfWeekDisabled: false,
calendarWeeks: false,
viewMode: 'days',
toolbarPlacement: 'default',
showTodayButton: true,
showClear: false,
showClose: false,
widgetPositioning: {
horizontal: 'auto',
vertical: 'auto'
},
widgetParent: null,
ignoreReadonly: false,
keepOpen: false,
focusOnShow: true,
inline: false,
keepInvalid: false,
datepickerInput: '.datepickerinput',
keyBinds: {
up: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().subtract(7, 'd'));
} else {
this.date(d.clone().add(this.stepping(), 'm'));
}
},
down: function (widget) {
if (!widget) {
this.show();
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().add(7, 'd'));
} else {
this.date(d.clone().subtract(this.stepping(), 'm'));
}
},
'control up': function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().subtract(1, 'y'));
} else {
this.date(d.clone().add(1, 'h'));
}
},
'control down': function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().add(1, 'y'));
} else {
this.date(d.clone().subtract(1, 'h'));
}
},
left: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().subtract(1, 'd'));
}
},
right: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().add(1, 'd'));
}
},
pageUp: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().subtract(1, 'M'));
}
},
pageDown: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.down('.datepicker').visible()) {
this.date(d.clone().add(1, 'M'));
}
},
enter: function () {
this.hide();
},
escape: function () {
this.hide();
},
//tab: function (widget) { //this break the flow of the form. disabling for now
// var toggle = widget.find('.picker-switch a[data-action="togglePicker"]');
// if(toggle.length > 0) toggle.click();
//},
'control space': function (widget) {
if (!widget) {
return;
}
if (widget.down('.timepicker').visible()) {
widget.down('.btn[data-action="togglePeriod"]').click();
}
},
t: function () {
this.date(this.getMoment());
},
'delete': function () {
this.clear();
}
},
debug: false,
allowInputToggle: false,
disabledTimeIntervals: false,
disabledHours: false,
enabledHours: false,
viewDate: false
};
var localeTooltips = {
es: {
today: 'Hoy',
clear: 'Limpiar selección',
close: 'Cerrar',
selectMonth: 'Seleccionar mes',
prevMonth: 'Mes anterior',
nextMonth: 'Mes siguiente',
selectYear: 'Seleccionar año',
prevYear: 'Año anterior',
nextYear: 'Año siguiente',
selectDecade: 'Seleccionar década',
prevDecade: 'Década anterior',
nextDecade: 'Década siguiente',
prevCentury: 'Siglo siguiente',
nextCentury: 'Siglo anterior',
pickHour: 'Seleccionar hora',
incrementHour: 'Aumentar hora',
decrementHour: 'Disminuir hora',
pickMinute: 'Seleccionar minuto',
incrementMinute: 'Aumentar minuto',
decrementMinute: 'Disminuir minuto',
pickSecond: 'Seleccionar segundo',
incrementSecond: 'Aumentar segundo',
decrementSecond: 'Disminuir segundo',
togglePeriod: 'Toggle Period',
selectTime: 'Select Time'
}
};
Class.create('DateTimePicker', {
picker: null,
initialize: function (element, options) {
var thisOptions = Object.extend({}, dpDefaults);
thisOptions = Object.extend(thisOptions, options || {});
thisOptions.tooltips = localeTooltips[thisOptions.locale] || thisOptions.tooltips;
this.picker = dateTimePicker(element, thisOptions);
}
});
})();
|
boa-project/boa
|
src/boa/plugins/gui.ajax/res/js/core/DateTimePicker.class.js
|
JavaScript
|
agpl-3.0
| 113,199
|
importPackage(Packages.tools);
var returnTo = new Array(103000100, 103000310);
var rideTo = new Array(103000310, 103000100);
var trainRide = new Array(103000301, 103000302);
var myRide;
var returnMap;
var exitMap;
var map;
var onRide;
//Time Setting is in millisecond
var rideTime = 10 * 1000;
function init() {
rideTime = em.getTransportationTime(rideTime);
}
function setup(level, lobbyid) {
var eim = em.newInstance("KerningTrain_" + lobbyid);
return eim;
}
function afterSetup(eim) {}
function playerEntry(eim, player) {
if (player.getMapId() == returnTo[0]) {
myRide = 0;
} else {
myRide = 1;
}
exitMap = eim.getEm().getChannelServer().getMapFactory().getMap(rideTo[myRide]);
returnMap = eim.getMapFactory().getMap(returnTo[myRide]);
onRide = eim.getMapFactory().getMap(trainRide[myRide]);
player.changeMap(onRide, onRide.getPortal(0));
player.getClient().announce(MaplePacketCreator.getClock(rideTime / 1000));
player.getClient().announce(MaplePacketCreator.earnTitleMessage("The next stop is at Kerning " + (myRide == 0 ? "Square" : "Subway") + " Station. The exit is to your left."));
eim.schedule("timeOut", rideTime);
}
function timeOut(eim) {
end(eim);
}
function playerUnregistered(eim, player) {}
function playerExit(eim, player, success) {
eim.unregisterPlayer(player);
player.changeMap(success ? exitMap.getId() : returnMap.getId(), 0);
}
function end(eim) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i), true);
}
eim.dispose();
}
function playerDisconnected(eim, player) {
playerExit(eim, player, false);
}
function cancelSchedule() {}
function dispose(eim) {}
// ---------- FILLER FUNCTIONS ----------
function monsterValue(eim, mobid) {return 0;}
function disbandParty(eim, player) {}
function monsterKilled(mob, eim) {}
function scheduledTimeout(eim) {}
function changedLeader(eim, leader) {}
function leftParty(eim, player) {}
function clearPQ(eim) {}
function allMonstersDead(eim) {}
|
ronancpl/MapleSolaxiaV2
|
scripts/event/KerningTrain.js
|
JavaScript
|
agpl-3.0
| 2,133
|
{% extends "base.html" %}
{% load extension_icon %}
{% block title %}Unreviewed Extensions - {{ block.super }}{% endblock %}
{% block body %}
<h2>Unreviewed Extensions</h2>
<ul class="extensions">
{% for version in version_list %}
{% with version.extension as extension %}
<li class="extension">
<h3 class="extension-name"><a href="{% url 'review-version' pk=version.pk %}"><img src="{% extension_icon extension.icon %}" class="icon">{{ extension.name }}</a></h3>
<span class="version">(v{{ version.version }})</span>
<span class="author">by <a href="{% url 'auth-profile' user=extension.creator %}">{{ extension.creator }}</a></span>
<p class="description">{{ extension.first_line_of_description }}</p>
</li>
{% endwith %}
{% endfor %}
</ul>
{% endblock %}
|
GNOME/extensions-web
|
sweettooth/review/templates/review/list.html
|
HTML
|
agpl-3.0
| 768
|
// TriangleCanvas.js
import React from 'react';
import Trianglify from 'trianglify';
import './TriangleCanvas.scss';
/**
Canvas with Trianglify styling applied, equal in size to current window,
can be used as a sweet background.
Will automatically size to window's width and height.
@prop cellSize: cell_size option for Trianglify
@prop xColors: x_colors option for Trianglify
@prop yColors: y_colors option for Trianglify
note: more Trianglify options available https://github.com/qrohlf/trianglify
*/
const TriangleCanvas = React.createClass({
getDefaultProps() {
return {
cellSize: Trianglify.defaults.cell_size,
xColors: Trianglify.defaults.x_colors,
yColors: Trianglify.defaults.cell_size,
};
},
componentDidMount() {
this.renderCanvas();
},
renderCanvas() {
const canvas = document.getElementById('daCanvas');
const pattern = Trianglify({
width: window.innerWidth,
height: window.innerHeight,
cell_size: this.props.cellSize,
x_colors: this.props.xColors,
});
pattern.canvas(canvas);
},
render() {
return (
<div className="triangleCanvas">
<canvas className="canvasCanvas" id="daCanvas" />
<div className="canvasContent">{this.props.children}</div>
</div>
);
},
});
export default TriangleCanvas;
|
uclaradio/uclaradio
|
client/react/frontpage/components/TriangleCanvas.js
|
JavaScript
|
agpl-3.0
| 1,331
|
<?php
namespace App\Services\Immoware24;
use App\Models\RentDefinition;
use Carbon\Carbon;
use Exception;
class RentalContractsMapper extends Mapper
{
protected $tenants;
protected $phones;
protected $faxs;
protected $emails;
protected $SEPAMandate;
protected $unit;
protected $start, $end;
public function __construct($model, & $config)
{
parent::__construct($model, $config);
$this->tenants = $this->model->mieter;
$this->phones = $this->tenants->pluck('phones')->collapse()->unique();
$this->faxs = $this->tenants->pluck('faxs')->collapse()->unique();
$this->emails = $this->tenants->pluck('emails')->collapse()->unique();
$this->SEPAMandate = $this->currentSEPAMandate();
$this->unit = $this->model->einheit;
$this->start = $this->start($this->model->MIETVERTRAG_VON, $this->model->MIETVERTRAG_BIS);
$this->end = $this->end($this->model->MIETVERTRAG_VON, $this->model->MIETVERTRAG_BIS);
}
protected function currentSEPAMandate()
{
$until = $this->model->BIS;
if ($until === '0000-00-00') {
return $this->model->SEPAMandates()->active('=', Carbon::today())->first();
} else {
return $this->model->SEPAMandates()->active('=', $until)->first();
}
}
public function getOBJ_ID()
{
return $this->unit->haus->objekt->OBJEKT_ID;
}
public function getVE_ID()
{
return $this->unit->EINHEIT_ID;
}
public function getK_ID()
{
$tenantsId = implode(':', $this->tenants->pluck('id')->sort()->values()->all());
if (array_has($this->config['person-to-contact-ids'], $tenantsId)) {
return $this->config['person-to-contact-ids'][$tenantsId];
} else {
throw new Exception();
}
}
public function getTyp()
{
return "M";
}
public function getvon()
{
return $this->date($this->model->MIETVERTRAG_VON);
}
public function getbis()
{
if ($this->model->MIETVERTRAG_BIS === '0000-00-00') {
return "";
}
return $this->date($this->model->MIETVERTRAG_BIS);
}
public function getGewerbe()
{
$type = $this->unit->TYP;
switch ($type) {
case "Gewerbe":
return "G";
default:
return "N";
}
}
public function getLastschrift()
{
if (!empty($this->SEPAMandate)) {
return "1";
}
return "0";
}
public function getMahnsperre()
{
return "";
}
public function getUmlAusfWagnis()
{
return "";
}
public function getNotizen()
{
return "";
}
public function getSV_Brutto()
{
return "";
}
public function getSV_Fälligkeit()
{
return "";
}
public function getZ_Miete()
{
$basicRentDefinitions = $this->model->basicRentDefinitions($this->start, $this->end)
->where('KOSTENKATEGORIE', '!=', 'Untermieter Zuschlag')
->where('KOSTENKATEGORIE', '!=', 'Garagenmiete')
->where('KOSTENKATEGORIE', '!=', 'Stellplatzmiete');
$basicRent = RentDefinition::sumDefinitions(
$basicRentDefinitions,
$this->start,
$this->end
);
$basicRentDeductionDefinitions = $this->model->basicRentDeductionDefinitions($this->start, $this->end);
$basicRentDeduction = RentDefinition::sumDefinitions(
$basicRentDeductionDefinitions,
$this->start,
$this->end
);
return number_format($basicRent + $basicRentDeduction, 2, ',', '.');
}
public function getZ_BKV()
{
$operatingCostAdvanceDefinitions = $this->model->operatingCostAdvanceDefinitions($this->start, $this->end)
->where('KOSTENKATEGORIE', '!=', 'Kabel TV');
$operatingCostAdvances = RentDefinition::sumDefinitions(
$operatingCostAdvanceDefinitions,
$this->start,
$this->end
);
return number_format($operatingCostAdvances, 2, ',', '.');
}
public function getZ_HKV()
{
$heatingExpenseAdvanceDefinitions = $this->model->heatingExpenseAdvanceDefinitions($this->start, $this->end);
$heatingExpenseAdvances = RentDefinition::sumDefinitions(
$heatingExpenseAdvanceDefinitions,
$this->start,
$this->end
);
return number_format($heatingExpenseAdvances, 2, ',', '.');
}
public function getZ_Garage()
{
$garageRentDefinitions = $this->model->rentDefinitions($this->start, $this->end)
->where('KOSTENKATEGORIE', '=', 'Garagenmiete');
$garageRent = RentDefinition::sumDefinitions(
$garageRentDefinitions,
$this->start,
$this->end
);
return number_format($garageRent, 2, ',', '.');
}
public function getZ_Stellplatz()
{
$parkingSpaceRentDefinitions = $this->model->rentDefinitions($this->start, $this->end)
->where('KOSTENKATEGORIE', '=', 'Stellplatzmiete');
$parkingSpaceRent = RentDefinition::sumDefinitions(
$parkingSpaceRentDefinitions,
$this->start,
$this->end
);
return number_format($parkingSpaceRent, 2, ',', '.');
}
public function getZ_sonstMiete()
{
$miscRentDefinitions = $this->model->rentDefinitions($this->start, $this->end)
->where(function ($query) {
$query->where('KOSTENKATEGORIE', '=', 'Untermieter Zuschlag')
->orWhere('KOSTENKATEGORIE', '=', 'Kabel TV');
});
$miscRent = RentDefinition::sumDefinitions(
$miscRentDefinitions,
$this->start,
$this->end
);
return number_format($miscRent, 2, ',', '.');
}
public function getZ_Hausgeld()
{
return "";
}
public function getZ_Rücklage1()
{
return "";
}
public function getZ_Rücklage2()
{
return "";
}
public function getU_Wohnfläche()
{
if (!empty($this->unit)) {
return number_format(trim($this->unit->EINHEIT_QM), 2, ',', '.');
}
return "";
}
public function getU_Heizfläche()
{
if (!empty($this->unit)) {
return number_format(trim($this->unit->EINHEIT_QM), 2, ',', '.');
}
return "";
}
public function getU_KabelTV()
{
return "";
}
public function getU_Personen()
{
return $this->tenants->count();
}
public function getU_Einheiten()
{
return "";
}
public function getU_Garagen()
{
return "";
}
public function getU_Stellplätze()
{
return "";
}
public function getU_MEA()
{
return "";
}
public function getBK_ID()
{
if (!empty($this->SEPAMandate)) {
$id = 'sepa:'
. implode(':', $this->tenants->pluck('id')->sort()->values()->all())
. '|' . $this->SEPAMandate->M_ID;
if (array_has($this->config['bank-account-ids'], $id)) {
return $this->config['bank-account-ids'][$id];
} else {
$this->logger->error(
'Missing BK_ID for contract (id: '
. $this->model->MIETVERTRAG_ID . ' unit: ' . $this->model->einheit->EINHEIT_KURZNAME . ').'
);
throw new Exception();
}
}
return "";
}
public function getGläubigerID()
{
if (!empty($this->SEPAMandate)) {
return trim($this->SEPAMandate->GLAEUBIGER_ID);
}
return "";
}
public function getMandatRef()
{
if (!empty($this->SEPAMandate)) {
return trim($this->SEPAMandate->M_REFERENZ);
}
return "";
}
public function getMandatVon()
{
if (!empty($this->SEPAMandate)) {
return $this->date($this->SEPAMandate->M_ADATUM);
}
return "";
}
public function getMandatBis()
{
if (!empty($this->SEPAMandate)
&& $this->SEPAMandate->M_EDATUM !== '9999-12-31') {
return $this->date($this->SEPAMandate->M_EDATUM);
}
return "";
}
public function getMandatUnterschrift()
{
if (!empty($this->SEPAMandate)) {
return $this->date($this->SEPAMandate->M_UDATUM);
}
return "";
}
}
|
BerlusGmbH/Berlussimo
|
app/Services/Immoware24/RentalContractsMapper.php
|
PHP
|
agpl-3.0
| 8,701
|
OC.L10N.register(
"workflowengine",
{
"Saved" : "Bewaard",
"Saving failed:" : "Opslaan mislukt:",
"File MIME type" : "Mimetype bestand",
"is" : "is",
"is not" : "is niet",
"matches" : "komt overeen",
"does not match" : "komt niet overeen",
"Example: {placeholder}" : "Bijvoorbeeld: {placeholder}",
"File size (upload)" : "Bestandsgrootte (upload)",
"less" : "minder",
"less or equals" : "minder of gelijk",
"greater or equals" : "groter of gelijk",
"greater" : "groter",
"File system tag" : "Bestandssysteem markering",
"is tagged with" : "is gemarkeerd met",
"is not tagged with" : "is niet gemarkeerd met",
"Select tag…" : "Selecteer markering...",
"Request remote address" : "Vraag extern adres aan",
"matches IPv4" : "komt overeen met IPv4",
"does not match IPv4" : "komt niet overeen met IPv4",
"matches IPv6" : "komt overeen met IPv6",
"does not match IPv6" : "komt niet overeen met IPv6",
"Request time" : "Vraag tijd aan",
"between" : "tussen",
"not between" : "niet tussen",
"Start" : "Begin",
"End" : "Einde",
"Select timezone…" : "Selecteer tijdzone...",
"Request URL" : "Vraag URL aan",
"Predefined URLs" : "Voorgedefinieerde URL's",
"Files WebDAV" : "Bestanden WebDAV",
"Request user agent" : "Vraag gebruikersagent aan",
"Sync clients" : "Synchroniseer clients",
"Android client" : "Android client",
"iOS client" : "iOS client",
"Desktop client" : "Desktop client",
"User group membership" : "Gebruikersgroep lidmaatschap",
"is member of" : "is lid van",
"is not member of" : "is geen lid van",
"The given operator is invalid" : "De opgegeven operator is ongeldig",
"The given regular expression is invalid" : "De opgegeven reguliere expressie is ongeldig",
"The given file size is invalid" : "De opgegeven bestandsgrootte is ongeldig",
"The given tag id is invalid" : "De opgegeven markerings-id is ongeldig",
"The given IP range is invalid" : "De opgegeven IP-range is ongeldig",
"The given IP range is not valid for IPv4" : "De opgegeven IP-range is niet geldig voor IPv4",
"The given IP range is not valid for IPv6" : "De opgegeven IP-range is niet geldig voor IPv6",
"The given time span is invalid" : "De opgegeven tijdspanne is ongeldig",
"The given start time is invalid" : "De opgegeven begintijd is ongeldig",
"The given end time is invalid" : "De opgegeven eindtijd is ongeldig",
"The given group does not exist" : "De opgegeven groep bestaat niet",
"Check %s is invalid or does not exist" : "Controleer: %s is ongeldig of bestaat niet",
"Operation #%s does not exist" : "Bewerking #%s bestaat niet",
"Operation %s does not exist" : "Bewerking %s bestaat niet",
"Operation %s is invalid" : "Bewerking %s is ongeldig",
"Check %s does not exist" : "Controleer: %s bestaat niet",
"Check %s is invalid" : "Controleer: %s is ongeldig",
"Check #%s does not exist" : "Controleer: #%s bestaat niet",
"Workflow" : "Workflow",
"Files workflow engine" : "Betand workflow engine",
"Open documentation" : "Open documentatie",
"Add rule group" : "Groepsrol toevoegen",
"Short rule description" : "Korte rolbeschrijving",
"Add rule" : "Voeg rol toe",
"Reset" : "Reset",
"Save" : "Opslaan",
"Saving…" : "Opslaan...",
"Loading…" : "Laden...",
"Successfully saved" : "Succesvol opgeslagen",
"File mime type" : "Bestand mime type"
},
"nplurals=2; plural=(n != 1);");
|
pixelipo/server
|
apps/workflowengine/l10n/nl.js
|
JavaScript
|
agpl-3.0
| 3,565
|
<!DOCTYPE html>
<html lang="en"
>
<head>
<title>Articles by Cad Lab - CADLab (虎尾科大MDE)</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/*some stuff for output/input prompts*/
div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid}
div.cell.edit_mode{border-radius:4px;border:thin #008000 solid}
div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none}
div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em}
@media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em}
div.prompt:empty{padding-top:0;padding-bottom:0}
div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;}
div.inner_cell{width:90%;}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;}
div.input_prompt{color:navy;border-top:1px solid transparent;}
div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);}
div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;}
div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);}
div.output_prompt{color:darkred;}
a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;}
h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;}
/* end stuff for output/input prompts*/
.highlight-ipynb .hll { background-color: #ffffcc }
.highlight-ipynb { background: #f8f8f8; }
.highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */
.highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */
.highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */
.highlight-ipynb .o { color: #666666 } /* Operator */
.highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */
.highlight-ipynb .ge { font-style: italic } /* Generic.Emph */
.highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */
.highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */
.highlight-ipynb .go { color: #888888 } /* Generic.Output */
.highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */
.highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */
.highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */
.highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */
.highlight-ipynb .m { color: #666666 } /* Literal.Number */
.highlight-ipynb .s { color: #BA2121 } /* Literal.String */
.highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */
.highlight-ipynb .nb { color: #008000 } /* Name.Builtin */
.highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight-ipynb .no { color: #880000 } /* Name.Constant */
.highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */
.highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight-ipynb .nf { color: #0000FF } /* Name.Function */
.highlight-ipynb .nl { color: #A0A000 } /* Name.Label */
.highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight-ipynb .nv { color: #19177C } /* Name.Variable */
.highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */
.highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */
.highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */
.highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */
.highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */
.highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */
.highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */
.highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */
.highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */
.highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */
.highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */
.highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
div.entry-content {
overflow: visible;
padding: 8px;
}
.input_area {
padding: 0.2em;
}
a.heading-anchor {
white-space: normal;
}
.rendered_html
code {
font-size: .8em;
}
pre.ipynb {
color: black;
background: #f7f7f7;
border: none;
box-shadow: none;
margin-bottom: 0;
padding: 0;
margin: 0px;
font-size: 13px;
}
/* remove the prompt div from text cells */
div.text_cell .prompt {
display: none;
}
/* remove horizontal padding from text cells, */
/* so it aligns with outer body text */
div.text_cell_render {
padding: 0.5em 0em;
}
img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
</style>
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<script type="text/javascript">
init_mathjax = function() {
if (window.MathJax) {
// MathJax loaded
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
displayAlign: 'left', // Change this to 'center' to center equations.
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}}
}
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}
init_mathjax();
</script>
<meta name="author" content="kmol" />
<!-- Open Graph tags -->
<meta property="og:site_name" content="CADLab (虎尾科大MDE)" />
<meta property="og:type" content="website"/>
<meta property="og:title" content="CADLab (虎尾科大MDE)"/>
<meta property="og:url" content=".."/>
<meta property="og:description" content="CADLab (虎尾科大MDE)"/>
<!-- Bootstrap -->
<link rel="stylesheet" href="../theme/css/bootstrap.united.min.css" type="text/css"/>
<link href="../theme/css/font-awesome.min.css" rel="stylesheet">
<link href="../theme/css/pygments/monokai.css" rel="stylesheet">
<link href="../theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<link rel="stylesheet" href="../theme/css/style.css" type="text/css"/>
<link href="../feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="CADLab (虎尾科大MDE) ATOM Feed"/>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJava.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPython.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPhp.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCpp.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCSharp.js"></script>
<script type="text/javascript" src="https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushBash.js"></script>
<script type='text/javascript'>
(function(){
var corecss = document.createElement('link');
var themecss = document.createElement('link');
var corecssurl = "https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shCore.css";
if ( corecss.setAttribute ) {
corecss.setAttribute( "rel", "stylesheet" );
corecss.setAttribute( "type", "text/css" );
corecss.setAttribute( "href", corecssurl );
} else {
corecss.rel = "stylesheet";
corecss.href = corecssurl;
}
document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") );
var themecssurl = "https://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b";
if ( themecss.setAttribute ) {
themecss.setAttribute( "rel", "stylesheet" );
themecss.setAttribute( "type", "text/css" );
themecss.setAttribute( "href", themecssurl );
} else {
themecss.rel = "stylesheet";
themecss.href = themecssurl;
}
//document.getElementById("syntaxhighlighteranchor").appendChild(themecss);
document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") );
})();
SyntaxHighlighter.config.strings.expandSource = '+ expand source';
SyntaxHighlighter.config.strings.help = '?';
SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n';
SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: ';
SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: ';
SyntaxHighlighter.defaults['pad-line-numbers'] = false;
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="../" class="navbar-brand">
CADLab (虎尾科大MDE) </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="../pages/about/">
About
</a></li>
<li >
<a href="../category/can-kao.html">參考</a>
</li>
<li >
<a href="../category/dao-yin.html">導引</a>
</li>
<li >
<a href="../category/gui-hua.html">規劃</a>
</li>
<li >
<a href="../category/misc.html">Misc</a>
</li>
<li >
<a href="../category/zi-yuan.html">資源</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span>
<form class="navbar-search" action="../search.html">
<input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required>
</form></span>
</li>
<li><a href="../archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<article>
<h2><a href="../dian-nao-fu-zhu-she-ji-shi-dian-nao-geng-xin-jie-guo.html">電腦輔助設計室電腦更新結果</a></h2>
<div class="summary"><p>首先要感謝<a href="http://www.hicitron.com.tw/">采誠</a>與<a href="https://www.asus.com">華碩</a>公司, 對於 <a href="http://cadlab.mde.tw">CADLab</a> 電腦軟硬體所提供的各項規劃與安裝支援服務.</p>
<a class="btn btn-default btn-xs" href="../dian-nao-fu-zhu-she-ji-shi-dian-nao-geng-xin-jie-guo.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../chun-ipv6-huan-jing-xia-an-zhuang-jupyterhub.html">純 IPV6 環境下安裝 Jupyterhub</a></h2>
<div class="summary"><p><a href="https://github.com/jupyterhub/jupyterhub">https://github.com/jupyterhub/jupyterhub</a> 是一套支援多用戶的網際運算伺服器, 這裡展示如何在純 IPV6 的 Ubuntu 14.04 環境下進行安裝設定.</p>
<a class="btn btn-default btn-xs" href="../chun-ipv6-huan-jing-xia-an-zhuang-jupyterhub.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../chun-ipv6-huan-jing-xia-de-cmsimply.html">純 IPV6 環境下的 CMSimply</a></h2>
<div class="summary"><p>IPV6 是工業 4.0 的一項重要技術, 隨著電腦輔助設計室導入 IPV6, 作為網際程式教學用的 CMSimply 也必須配合轉到 IPV6 相容的環境.</p>
<a class="btn btn-default btn-xs" href="../chun-ipv6-huan-jing-xia-de-cmsimply.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../jupyterhub-oauth2-deng-ru-she-ding.html">Jupyterhub oauth2 登入設定</a></h2>
<div class="summary"><p>當機械設計工程師精熟了 Matlab 與 Mathematica 之後, 若想更進一步了解這些數值運算工具的整體架構, 可以試著在實體機或虛擬機器 (或 Docker 容器) 上架設自由開源的 Jupyterhub, 好按照各自研發團隊的需求, 打造永續的設計運算生態系統.</p>
<a class="btn btn-default btn-xs" href="../jupyterhub-oauth2-deng-ru-she-ding.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../rang-virtualbox-xu-ni-ji-qi-sui-zhu-ji-qi-dong.html">讓 Virtualbox 虛擬機器隨主機啟動</a></h2>
<div class="summary"><p>目前所使用的 Virtualbox 主體分別是 Windows 7 與 Ubuntu 14.04/16.04 等, 在 Windows 7 的虛擬機器可以透過 <a href="http://vboxvmservice.sourceforge.net/">http://vboxvmservice.sourceforge.net/</a>, 讓特定虛擬機器 (virtual machine), 隨著 Host 電腦的開啟而以 service 的方式啟用. 至於在 Ubuntu 14.04 或 16.04 操作系統中, 則可以在 /etc/init.d/ 目錄下建立一個啟動程序, 然後讓電腦在開關機時執行, 主要的指令是開機時, 利用 VBoxHeadless 啟動個別的虛擬機器, 且在關機時, 利用 VBoxManage controlvm 儲存各虛擬機器的運行狀態.</p>
<a class="btn btn-default btn-xs" href="../rang-virtualbox-xu-ni-ji-qi-sui-zhu-ji-qi-dong.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../tinymce4-shi-yong-dao-yin.html">Tinymce4 使用導引</a></h2>
<div class="summary"><p><a href="https://www.tinymce.com/">https://www.tinymce.com/</a> 版本為 4.3.13 community 版本, 使用授權為 Open Source LGPL 2.1.</p>
<a class="btn btn-default btn-xs" href="../tinymce4-shi-yong-dao-yin.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../ubuntu-1604-windows-7-yu-windows-10-xu-ni-ji-qi.html">Ubuntu 16.04, Windows 7 與 Windows 10 虛擬機器</a></h2>
<div class="summary"><p>Ubuntu 16.04 剛推出兩個月, Windows 10 則推出將近滿一年, 這兩個號稱創新度高的電腦操作系統, 經過幾個禮拜密集的測試, 在今年暑假即將更新的電腦輔助設計室所採購的電腦中, 初步決定都不積極採用, 而只在虛擬機器中提供測試之用.</p>
<a class="btn btn-default btn-xs" href="../ubuntu-1604-windows-7-yu-windows-10-xu-ni-ji-qi.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../virtualbox-de-ying-yong-yu-wang-lu-she-ding-er.html">Virtualbox 的應用與網路設定 (二)</a></h2>
<div class="summary"><p>透過 Virtualbox 的使用說明: <a href="https://www.virtualbox.org/manual/">https://www.virtualbox.org/manual/</a> 可以了解一個 Virtualbox 的虛擬機器, 若啟用 ICH9 Chipset, 最多可以<a href="https://www.virtualbox.org/manual/ch03.html#settings-motherboard">支援 36 片網路卡</a>.</p>
<a class="btn btn-default btn-xs" href="../virtualbox-de-ying-yong-yu-wang-lu-she-ding-er.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../cadlab-xin-dian-nao-xi-tong.html">CADLab 新電腦系統</a></h2>
<div class="summary"><p>CPU 選擇: <span style="background-color: #ffff00;">Intel i7-6700</span></p>
<p>Ram 選擇: <span style="background-color: #ffff00;">16GB (8GBx2) DDR4-3000 (至少還可再升級 8GBx2)</span></p>
<p>HD: <span style="background-color: #ffff00;">2TB (64MB) SATA III</span></p>
<p>Video Card: <span style="background-color: #ffff00;">NVIDIA GEFORCE GTX950 2GB GDDR5</span></p>
<p>NIC: <span style="background-color: #ffff00;">1Gbits/s*5 (除了主機板上的兩片網路卡之外 ,再加上 3 片外接式網路卡, 以便與各開機磁區中的虛擬機橋接出虛擬的多台連外伺服器)</span></p>
<p>參考:</p>
<p>i7: <a href="https://en.wikipedia.org/wiki/List_of_Intel_Core_i7_microprocessors">https://en.wikipedia.org/wiki/List_of_Intel_Core_i7_microprocessors</a></p>
<p>i7-6700: <a href="http://ark.intel.com/products/88196">http://ark.intel.com/products/88196</a></p>
<a class="btn btn-default btn-xs" href="../cadlab-xin-dian-nao-xi-tong.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="../dian-nao-fu-zhu-she-ji-shi-dian-nao-ci-qu-gui-hua.html">電腦輔助設計室電腦磁區規劃</a></h2>
<div class="summary"><div>希望能根據不同性質課程, 將軟體分為 3 個開機磁區:</div>
<ol>
<li>安裝所有老師提出的上課套件, 集中在第 1 磁區, 其中包括 CAD, CAE, CAM, 數值分析與自動控制相關所有套件.</li>
<li>只安裝 Solidworks, PTC Creo, AutoDesk Inventor, AutoCAD, A360, Ansys, Comsol, Matlab 與 Mathematica, 等 CAD, CAE 與數值分析相關套件.</li>
<li>只安裝操作系統, 加上無需安裝的綠色套件 (PTC, Creo, Comsol, Matlab 等).</li>
</ol>
<div>
<a class="btn btn-default btn-xs" href="../dian-nao-fu-zhu-she-ji-shi-dian-nao-ci-qu-gui-hua.html">more ...</a>
</div>
</article>
<hr/>
<ul class="pagination">
<li class="prev disabled"><a href="#">«</a></li>
<li class="active"><a
href="../author/cad-lab.html">1</a></li>
<li class=""><a
href="../author/cad-lab2.html">2</a></li>
<li class="next"><a
href="../author/cad-lab2.html">»</a></li>
</ul>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4>
<ul class="list-group" id="recentposts">
<li class="list-group-item">
<a href="../dian-nao-fu-zhu-she-ji-shi-dian-nao-geng-xin-jie-guo.html">
電腦輔助設計室電腦更新結果
</a>
</li>
<li class="list-group-item">
<a href="../chun-ipv6-huan-jing-xia-an-zhuang-jupyterhub.html">
純 IPV6 環境下安裝 Jupyterhub
</a>
</li>
<li class="list-group-item">
<a href="../chun-ipv6-huan-jing-xia-de-cmsimply.html">
純 IPV6 環境下的 CMSimply
</a>
</li>
<li class="list-group-item">
<a href="../jupyterhub-oauth2-deng-ru-she-ding.html">
Jupyterhub oauth2 登入設定
</a>
</li>
<li class="list-group-item">
<a href="../rang-virtualbox-xu-ni-ji-qi-sui-zhu-ji-qi-dong.html">
讓 Virtualbox 虛擬機器隨主機啟動
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="../categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a>
<ul class="list-group" id="categories">
<li class="list-group-item">
<a href="../category/can-kao.html">
<i class="fa fa-folder-open fa-lg"></i> 參考
</a>
</li>
<li class="list-group-item">
<a href="../category/dao-yin.html">
<i class="fa fa-folder-open fa-lg"></i> 導引
</a>
</li>
<li class="list-group-item">
<a href="../category/gui-hua.html">
<i class="fa fa-folder-open fa-lg"></i> 規劃
</a>
</li>
<li class="list-group-item">
<a href="../category/misc.html">
<i class="fa fa-folder-open fa-lg"></i> MISC
</a>
</li>
<li class="list-group-item">
<a href="../category/zi-yuan.html">
<i class="fa fa-folder-open fa-lg"></i> 資源
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="../tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
</ul>
</li>
<li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://getpelican.com/" target="_blank">
Pelican
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank">
pelican-bootstrap3
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/getpelican/pelican-plugins" target="_blank">
pelican-plugins
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/Tipue/Tipue-Search" target="_blank">
Tipue search
</a>
</li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2016 kmol
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="../theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="../theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="../theme/js/respond.min.js"></script>
</body>
</html>
|
cad-lab/blog
|
post/author/cad-lab.html
|
HTML
|
agpl-3.0
| 28,293
|
/*
* PHEX - The pure-java Gnutella-servent.
* Copyright (C) 2001 - 2007 Phex Development Group
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* --- SVN Information ---
* $Id: Range.java 3933 2007-09-21 18:35:24Z gregork $
*/
package phex.http;
public class Range {
public static final int NOT_SET = -1;
private long suffixLength;
/**
* The start offset of the download.
*/
private long startOffset;
/**
* The end offset of the download (inclusive)
*/
private long endOffset;
/**
* Creates a HTTPRange object for suffix lengths like '-500' which requests
* the last 500 bytes of a file.
*
* @param suffixLength the suffix length.
*/
public Range(long suffixLength) {
this.startOffset = NOT_SET;
this.endOffset = NOT_SET;
this.suffixLength = suffixLength;
}
/**
* Creates a HTTPRange object with a start and end offset. The end offset
* can be NOT_SET to form request like '100-'
*
* @param startOffset the start offset.
* @param endOffset the end offset.
* @param rating the rating
*/
public Range(long startOffset, long endOffset) {
this.startOffset = startOffset;
this.endOffset = endOffset;
this.suffixLength = NOT_SET;
}
/**
* Updates a HTTPRange object for suffix lengths like '-500' which requests
* the last 500 bytes of a file.
*
* @param suffixLength the suffix length.
*/
public void update(long suffix) {
this.startOffset = NOT_SET;
this.endOffset = NOT_SET;
this.suffixLength = suffix;
}
/**
* Updats a HTTPRange object with a start and end offset. The end offset
* can be NOT_SET to form request like '100-'
*
* @param startOffset the start offset.
* @param endOffset the end offset.
*/
public void update(long startOffset, long endOffset) {
this.startOffset = startOffset;
this.endOffset = endOffset;
this.suffixLength = NOT_SET;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("[Range: " + startOffset + '-' + endOffset + ']');
return buf.toString();
}
/**
* Returns the start offset of the download.
*
* @param fileSize the file size is needed in case of suffix byte range
* requests.
* @return
*/
public long getStartOffset(long fileSize) {
if (suffixLength == NOT_SET) {// we have absolute ranges.
return Math.min(startOffset, fileSize - 1);
} else {
return fileSize - suffixLength;
}
}
/**
* Returns the end offset (inclusive) of the download.
*
* @param fileSize the file size is needed in case of suffix byte range
* requests.
* @return
*/
public long getEndOffset(long fileSize) {
if (suffixLength == NOT_SET && endOffset != NOT_SET) {// we have absolut ranges.
return Math.min(endOffset, fileSize - 1);
} else {
return fileSize - 1;
}
}
public boolean isRangeSatisfiable(Range range, long fileSize) {
// a------a
// r--r
// r--r
// r--r
// r--r
long rangeStart = range.getStartOffset(fileSize);
return getStartOffset(fileSize) <= rangeStart
&& rangeStart <= getEndOffset(fileSize);
}
public String buildHTTPRangeString() {
if (suffixLength == NOT_SET) {
return String.valueOf(startOffset) + '-' + String.valueOf(
endOffset);
} else {
return '-' + String.valueOf(suffixLength);
}
}
public enum RangeAvailability {
/**
* Indicates that the range is available
*/
RANGE_AVAILABLE,
/**
* Indicates that the range is not available
*/
RANGE_NOT_AVAILABLE,
/**
* Indicates that the range is available
*/
RANGE_NOT_SATISFIABLE
}
}
|
deepstupid/phex
|
src/main/java/phex/http/Range.java
|
Java
|
agpl-3.0
| 4,812
|
using System.Collections.Generic;
namespace galaxy.core.misc.figuredata.types
{
class FigureSet
{
public SetType Type { get; set; }
public int PalletId { get; set; }
private Dictionary<int, Set> _sets;
public FigureSet(SetType type, int palletId)
{
this.Type = type;
this.PalletId = palletId;
this._sets = new Dictionary<int, Set>();
}
public Dictionary<int, Set> Sets
{
get { return this._sets; }
set { this._sets = value; }
}
}
}
|
helloimcasper/GalaxyEmulator
|
galaxy.core/misc/figuredata/types/FigureSet.cs
|
C#
|
agpl-3.0
| 583
|
/* vim: ts=2:sw=2:expandtab
*
* VHDE - The VHDL Diagram Editor
* Copyright (C) 2009-2017 Maurice van der Pot <griffon26@kfk4ever.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef _LAYOUT_ARCHITECTURE_H
#define _LAYOUT_ARCHITECTURE_H
#include <glibmm.h>
#include <stdio.h>
class INamedItem;
class LayoutComponent;
class LayoutInstance;
class LayoutSignal;
class LayoutArchitecture
{
private:
bool m_init;
std::vector<std::unique_ptr<LayoutInstance>> m_instances;
std::vector<std::unique_ptr<LayoutSignal>> m_signals;
INamedItem *m_pVHDLArchitecture;
public:
LayoutArchitecture();
virtual ~LayoutArchitecture();
LayoutArchitecture(const LayoutArchitecture&) = delete;
LayoutArchitecture& operator=(const LayoutArchitecture&) = delete;
/* These methods assume ownership of the component, instance and signal */
void init_addInstance(std::unique_ptr<LayoutInstance> pInstance);
void init_addSignal(std::unique_ptr<LayoutSignal> pSignal);
void init_done() { m_init = false; }
void removeInstance(LayoutInstance *pInstance);
void associateVHDLArchitecture(INamedItem *pArch);
/* Accessors */
const Glib::ustring &getName();
const std::vector<LayoutInstance *> getInstances();
const std::vector<LayoutSignal *> getSignals();
void write(std::ostream &stream, int indent);
};
#endif /* _LAYOUT_ARCHITECTURE_H */
|
Griffon26/vhde
|
src/layout/layout_architecture.h
|
C
|
agpl-3.0
| 2,043
|
/*
* Copyright (c) 2012 - 2020 Splice Machine, Inc.
*
* This file is part of Splice Machine.
* Splice Machine is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either
* version 3, or (at your option) any later version.
* Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.splicemachine.access.api;
import com.splicemachine.db.iapi.store.access.conglomerate.Conglomerate;
import com.splicemachine.storage.Partition;
import java.io.IOException;
import java.util.concurrent.Future;
/**
* @author Scott Fines
* Date: 12/28/15
*/
public interface PartitionCreator{
PartitionCreator withName(String name);
PartitionCreator withName(String name, Conglomerate.Priority priority);
PartitionCreator withDisplayNames(String[] displayNames);
/**
* Set the maximum size of a given subpartition for this overall partition,
* if the underlying architecture supports table-specific partition sizes.
*
* If the architecture does not support table-specific partition sizes, then
* this is a no-op.
*
* @param partitionSize the size of a partition
* @return a creator
*/
PartitionCreator withPartitionSize(long partitionSize);
PartitionCreator withCoprocessor(String coprocessor) throws IOException;
PartitionCreator withTransactionId(long txnId) throws IOException;
PartitionCreator withSplitKeys(byte[][] splitKeys);
PartitionCreator withCatalogVersion(String version);
Partition create() throws IOException;
Future<Partition> createAsync() throws IOException;
}
|
splicemachine/spliceengine
|
splice_access_api/src/main/java/com/splicemachine/access/api/PartitionCreator.java
|
Java
|
agpl-3.0
| 2,043
|
<?php
/**
* zCorrecteurs.fr est le logiciel qui fait fonctionner www.zcorrecteurs.fr
*
* Copyright (C) 2012-2019 Corrigraphie
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Zco\Bundle\ContentBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Zco\Bundle\ContentBundle\Domain\CategoryDAO;
use Zco\Bundle\ContentBundle\Search\Searchable\BlogSearchable;
use Zco\Bundle\ContentBundle\Search\Searchable\ForumSearchable;
use Zco\Bundle\ContentBundle\Search\SearchQuery;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
/**
* Contrôleur gérant la recherche sur le site.
*
* @author mwsaz <mwsaz@zcorrecteurs.fr>
*/
class SearchController extends Controller
{
/**
* Affichage du formulaire complet de recherche et des résultats.
*
* @param Request $request HTTP request.
* @return Response
*/
public function indexAction(Request $request)
{
$section = $request->query->get('section', 'forum');
$page = $request->query->get('page', 1);
// Configuration pour les trois actions (avant et après la recherche)
$CatsForum = CategoryDAO::ListerEnfants(CategoryDAO::GetIDCategorie('forum'), true, true);
$CatsBlog = CategoryDAO::ListerEnfants(CategoryDAO::GetIDCategorie('blog'), true, true);
\Page::$titre = 'Recherche';
$this->get('zco_core.resource_manager')->requireResources(array(
'@ZcoContentBundle/Resources/public/css/forum.css',
'@ZcoCoreBundle/Resources/public/css/tableaux_messages.css',
'@ZcoCoreBundle/Resources/public/css/zcode.css',
));
$_flags = array();
// Section du site concernée par la recherche
if ('forum' === $section) {
$searchable = new ForumSearchable();
} elseif ('blog' === $section) {
$searchable = new BlogSearchable();
} else {
return redirect(
'Votre catégorie de recherche est invalide.',
$this->generateUrl('zco_search_index'),
MSG_ERROR
);
}
if (!$request->query->has('recherche')) {
return $this->render('ZcoContentBundle:Search:index.html.php', compact(
'CatsForum', 'CatsBlog', '_flags'
));
}
$query = new SearchQuery();
$_flags['recherche'] = $request->query->get('recherche');
$query->setSearch($_flags['recherche']);
// Pagination.
$_flags['nb_resultats'] = $resultats = (int)$request->query->get('nb_resultats', 20);
$resultats = ($resultats <= 50 && $resultats >= 5) ? $resultats : 20;
$page = max(1, $page);
$_flags['nb_resultats'] = $resultats;
$query->setPage($page, $resultats);
// Mode de recherche.
$modes = [
'tous' => SearchQuery::MATCH_ALL,
'un' => SearchQuery::MATCH_ANY,
'phrase' => SearchQuery::MATCH_PHRASE
];
$mode = $request->query->get('mode', current($modes));
$mode = isset($modes[$mode]) ? $mode : current($modes);
$_flags['mode'] = $mode;
$query->setMatchMode($mode);
// Restriction de catégorie.
if ($request->query->has('categories')) {
$categoryIds = $request->query->get('categories') ?: [];
$query->setCategories($categoryIds);
$_flags['categories'] = $categoryIds;
}
// Critères de recherche spécifiques à une section.
if ($section == 'forum') {
$flags = array('ferme', 'resolu', 'postit');
foreach ($flags as $flg) {
if ($request->query->has($flg)) {
$_flags[$flg] = (bool)$request->query->get($flg);
if ($_flags[$flg]) {
$query->includeFlag('sujet_' . $flg);
} else {
$query->excludeFlag('sujet_' . $flg);
}
}
}
$_flags['auteur'] = $request->query->get('auteur', '');
if ($_flags['auteur']) {
$query->setAuthor($_flags['auteur']);
}
} elseif ($section == 'blog') {
// …
} elseif ($section == 'twitter') {
$_flags['auteur'] = $request->query->get('auteur', '');
if ($_flags['auteur']) {
$query->setAuthor($_flags['auteur']);
}
}
// Récupération des résultats
$pages = $Resultats = $CompterResultats = null;
try {
$res = $this->get('zco_search.search_service')->execute($query, $searchable);
$Resultats = $res->getResults();
$CompterResultats = $res->getTotalCount();
//TODO: fix pagination here.
$url = str_replace('91919191', '%s', $this->generateUrl('zco_search_index', array_merge(['section' => $section, 'page' => 91919191], $_flags)));
$pages = liste_pages($page, ceil($CompterResultats / $_flags['nb_resultats']), $url);
} catch (\Exception $e) {
$this->get('logger')->warn($e->getMessage());
$_SESSION['erreur'][] = 'Une erreur est survenue pendant la recherche. Merci de réessayer dans quelques instants.';
}
return $this->render('ZcoContentBundle:Search:index.html.php', compact(
'CatsForum', 'CatsBlog', '_flags',
'pages', 'CompterResultats', 'Resultats', 'section'
));
}
}
|
zcorrecteurs/monolith-www
|
src/Zco/Bundle/ContentBundle/Controller/SearchController.php
|
PHP
|
agpl-3.0
| 6,183
|
/*
* _ _ _
* | | | | | |
* | | __ _| |__ ___ ___ __ _| |_ Labcoat (R)
* | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel.
* | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc.
* |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved.
*
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version
* 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("ace/lib/oop");
var EventEmitter = require("ace/lib/event_emitter").EventEmitter;
var Editor = exports.Editor = function() {
this._buffers = [];
this._windows = [];
};
(function() {
oop.implement(this, EventEmitter);
this.addBuffer = function(buffer) {
this._buffers.push(buffer);
return this._buffers.length-1;
};
this.addWindow = function(win) {
this._windows.push(win);
return this._windows.length-1;
};
this.openInWindow = function(bufferId, winId) {
this._windows[winId || 0].setBuffer(this._buffers[bufferId]);
};
}).call(Editor.prototype);
});
|
precog/labcoat-legacy
|
js/ace/model/editor.js
|
JavaScript
|
agpl-3.0
| 3,492
|
/***************************************************************************
helpaboutform.cpp - description
-------------------
begin : Tue Apr 22 2003
copyright : (C) 2003 by Lalescu Liviu
email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************/
/***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include <QCoreApplication>
#include <QString>
#include "helpaboutform.h"
#include "timetable_defs.h"
#include "centerwidgetonscreen.h"
HelpAboutForm::HelpAboutForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
closePushButton->setDefault(true);
aboutTextBrowser->setReadOnly(true);
authorsTextBrowser->setReadOnly(true);
translatorsTextBrowser->setReadOnly(true);
referencesTextBrowser->setReadOnly(true);
thanksToTextBrowser->setReadOnly(true);
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
tabWidget->setCurrentIndex(0);
aboutTextBrowser->setOpenExternalLinks(true);
referencesTextBrowser->setOpenExternalLinks(true);
//Trick to have the translations handy for future releases
QString monthJan=QCoreApplication::translate("MonthsNames", "January");
Q_UNUSED(monthJan);
QString monthFeb=QCoreApplication::translate("MonthsNames", "February");
Q_UNUSED(monthFeb);
QString monthMar=QCoreApplication::translate("MonthsNames", "March");
Q_UNUSED(monthMar);
QString monthApr=QCoreApplication::translate("MonthsNames", "April");
Q_UNUSED(monthApr);
QString monthMay=QCoreApplication::translate("MonthsNames", "May");
Q_UNUSED(monthMay);
QString monthJun=QCoreApplication::translate("MonthsNames", "June");
Q_UNUSED(monthJun);
QString monthJul=QCoreApplication::translate("MonthsNames", "July");
Q_UNUSED(monthJul);
QString monthAug=QCoreApplication::translate("MonthsNames", "August");
Q_UNUSED(monthAug);
QString monthSep=QCoreApplication::translate("MonthsNames", "September");
Q_UNUSED(monthSep);
QString monthOct=QCoreApplication::translate("MonthsNames", "October");
Q_UNUSED(monthOct);
QString monthNov=QCoreApplication::translate("MonthsNames", "November");
Q_UNUSED(monthNov);
QString monthDec=QCoreApplication::translate("MonthsNames", "December");
Q_UNUSED(monthDec);
QString about=QString("");
about+=tr("FET is free software for automatically scheduling the timetable of a school, high-school or university.");
about+="<br /><br />";
about+=tr("Copyright (C) %1-%2 %3.", "%1 is the year of the first FET release, %2 is the current release year, %3 are the FET authors")
.arg(2002).arg(2019).arg("Liviu Lalescu, Volker Dirr");
about+="<br /><br />";
about+=tr("Version: %1 (%2 %3).", "%1 is the current FET version, %2 is the current release month, %3 is the current release year").arg(FET_VERSION)
.arg(QCoreApplication::translate("MonthsNames", "January")).arg(2019);
about+="<br /><br />";
about+=tr("Licensed under the GNU Affero General Public License version 3 or later.");
about+="<br /><br />";
about+=tr("FET homepage: %1", "%1 is the FET homepage").arg("<a href=\"https://lalescu.ro/liviu/fet/\">https://lalescu.ro/liviu/fet/</a>");
about+="<br />";
aboutTextBrowser->setHtml(about);
QString authors=QString("");
authors+=QString("Liviu Lalescu (https://lalescu.ro/liviu/)");
authors+="<br /><br />";
authors+=QString("Volker Dirr (https://www.timetabling.de/)");
authors+="<br />";
authors+=QString(" - ")+tr("XHTML timetable export.");
authors+="<br />";
authors+=QString(" - ")+tr("CSV import and export.");
authors+="<br />";
authors+=QString(" - ")+tr("Advanced statistics print/export.");
authors+="<br />";
authors+=QString(" - ")+tr("Speed improvements in the timetable generation.");
authors+="<br />";
authors+=QString(" - ")+tr("Locking the activities.");
authors+="<br />";
authors+=QString(" - ")+tr("Activity planning dialog.");
authors+="<br />";
authors+=QString(" - ")+tr("Print timetable dialog.");
authors+="<br />";
authorsTextBrowser->setHtml(authors);
QString translators=QString("");
translators+=QString("ar - ")+tr("Arabic translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, "
"section about Arabic translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Silver").arg("Silver").arg("https://lalescu.ro/liviu/fet/forum/").arg("Silver");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Benahmed Abdelkrim").arg("pmg9.81 AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("ca - ")+tr("Catalan translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, "
"section about Catalan translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg(QString::fromUtf8("Sílvia Lag")).arg(QString::fromUtf8("Sílvia")).arg("https://lalescu.ro/liviu/fet/forum/").arg("silvia");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Innocent De Marchi").arg("tangram.peces AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("cs - ")+tr("Czech translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Pavel Fric").arg("pavelfric AT seznam.cz");
translators+=QString("<br /><br /><br />");
translators+=QString("da - ")+tr("Danish translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("David Lamhauge").arg("davidlamhauge AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("de - ")+tr("German translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Volker Dirr").arg("https://www.timetabling.de/");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Robert Hairgrove").arg("code AT roberthairgrove.com");
translators+=QString("<br /><br /><br />");
translators+=QString("el - ")+tr("Greek translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Dimitrios Ropokis").arg("wamy80s AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, "
"section about Greek translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Dimitris Kanatas").arg("Dimitris Kanatas").arg("https://lalescu.ro/liviu/fet/forum/").arg("Dimitris Kanatas");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (to contact %2 visit FET forum - %3, "
"section about Greek translation, or contact forum user %4)" ,"%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Vangelis Karafillidis").arg("Vangelis Karafillidis").arg("https://lalescu.ro/liviu/fet/forum/").arg("Vangelis Karafillidis");
translators+=QString(" - ")+tr("rewrote the translation from zero");
translators+=QString("<br /><br /><br />");
translators+=QString("es - ")+tr("Spanish translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address")
.arg(QString::fromUtf8("José César Fernández López")).arg("cesar.fernandez.lopez AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address")
.arg(QString::fromUtf8("Emiliano Llano Díaz")).arg("compuvtt AT hotmail.com");
translators+=QString(" - ")+tr("rewrote the translation from zero");
translators+=QString("<br /><br /><br />");
translators+=QString("eu - ")+tr("Basque translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Asier Urio Larrea").arg("asieriko AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("fa - ")+tr("Persian translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Hamed SadeghiNeshat").arg("ha_sadeghi AT ce.sharif.edu");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("sally sat").arg("soory63 AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("fr - ")+tr("French translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Jerome Durand").arg("fetfr AT free.fr");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Patrick Fox").arg("patrick.fox AT laposte.net");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address")
.arg(QString::fromUtf8("Régis Bouguin")).arg("regis.bouguin AT laposte.net");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Pascal Cohen").arg("pacohen AT laposte.net");
translators+=QString(" - ")+tr("rewrote the translation from zero");
translators+=QString("<br /><br /><br />");
translators+=QString("gl - ")+tr("Galician translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (to contact %2 visit FET forum - %3, "
"section about Galician translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Juan Marcos Filgueira Gomis").arg("marcos.filgueira").arg("https://lalescu.ro/liviu/fet/forum/").arg("marcos.filgueira");
translators+=QString("<br /><br /><br />");
translators+=QString("he - ")+tr("Hebrew translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Yotam Medini").arg("yotam.medini AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("hu - ")+tr("Hungarian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ferenczi Viktor").arg("cx AT cx.hu");
translators+=QString("<br /><br /><br />");
translators+=QString("id - ")+tr("Indonesian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Nirwan Yus").arg("ny.unpar AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("it - ")+tr("Italian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Marco Barsotti").arg("mbarsan AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("ja - ")+tr("Japanese translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (to contact %2 visit FET forum - %3, "
"section about Japanese translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Taro Tada").arg("Taro Tada").arg("https://lalescu.ro/liviu/fet/forum/").arg("Taro Tada");
translators+=QString("<br /><br /><br />");
translators+=QString("lt - ")+tr("Lithuanian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Darius Staigys").arg("darius AT e-servisas.lt");
translators+=QString("<br /><br /><br />");
translators+=QString("mk - ")+tr("Macedonian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Zoran Zdravkovski").arg("zoran AT pmf.ukim.edu.mk");
translators+=QString("<br /><br /><br />");
translators+=QString("ms - ")+tr("Malay translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Abdul Hadi Kamel").arg("hadikamel AT perlis.uitm.edu.my");
translators+=QString("<br /><br /><br />");
translators+=QString("nl - ")+tr("Dutch translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Niels Fikse").arg("k.fikse AT student.utwente.nl");
translators+=QString("<br /><br /><br />");
translators+=QString("pl - ")+tr("Polish translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Radoslaw Pasiok").arg("zapala AT konto.pl");
translators+=QString("<br /><br /><br />");
translators+=QString("pt_BR - ")+tr("Brazilian Portuguese translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Werner Bruns").arg("werner.bruns AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address")
.arg(QString::fromUtf8("Frank Mártin")).arg("drfarofa AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Cloves das Neves").arg("clovesneves AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2). (Alternatively, to contact %3 visit FET forum - %4, "
"section about Brazilian Portuguese translation, or contact forum user %5)", "%1 is the name of the translator, %2 is his email or web address, "
"%3 is the short name of the translator, %4 is the address of the forum, %5 is forum user name of the translator")
.arg("Alexandre R. Soares").arg("alexrsoares AT zoho.com").arg("Alexandre R. Soares").arg("https://lalescu.ro/liviu/fet/forum/").arg("khemis");
translators+=QString("<br /><br /><br />");
translators+=QString("ro - ")+tr("Romanian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Liviu Lalescu").arg("https://lalescu.ro/liviu/");
translators+=QString("<br /><br /><br />");
translators+=QString("ru - ")+tr("Russian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ilya V. Paramonov").arg("ivparamonov AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("si - ")+tr("Sinhala translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Achini Duisna").arg("duisna1012 AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("sk - ")+tr("Slovak translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (to contact %2 visit FET forum - %3, "
"section about Slovak translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Ondrej Gregor").arg("Ondrej").arg("https://lalescu.ro/liviu/fet/forum/").arg("Ondrej");
translators+=QString("<br /><br /><br />");
translators+=QString("sq - ")+tr("Albanian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Artur Lugu").arg("ciaoartur AT yahoo.it");
translators+=QString("<br /><br /><br />");
translators+=QString("sr - ")+tr("Serbian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ivan Starchevicy").arg("ivanstar61 AT gmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Radan Putnik").arg("srastral AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("tr - ")+tr("Turkish translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Mehmet Gezmisoglu").arg("m_gezmisoglu AT hotmail.com");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Mahir Nacar").arg("mahirnacar AT email.com");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Yakup Kadri Demirci").arg("yakup AT engineer.com");
translators+=QString("<br /><br /><br />");
translators+=QString("uk - ")+tr("Ukrainian translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Andriy Melnyk").arg("melnyk.andriy AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("uz - ")+tr("Uzbek translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2, or visit FET forum - %3, "
"section about Uzbek translation, or contact forum user %4)", "%1 is the current translator, %2 is his email or web address, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Orzubek Eraliyev").arg("o.eraliyev AT gmail.com").arg("https://lalescu.ro/liviu/fet/forum/").arg("sarkor");
translators+=QString("<br /><br /><br />");
translators+=QString("vi - ")+tr("Vietnamese translation");
translators+=QString("<br /><br /> ");
translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, "
"section about Vietnamese translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, "
"%4 is the username of the translator").arg("Nguyen Truong Thang").arg("Thang").arg("https://lalescu.ro/liviu/fet/forum/").arg("NTThang");
translators+=QString("<br /><br /> ");
translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address")
.arg(QString::fromUtf8("Nguyễn Hữu Duyệt")).arg("nguyenhuuduyet AT gmail.com");
translators+=QString("<br /><br /><br />");
translators+=QString("zh_CN - ")+tr("Chinese Simplified translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("orange").arg("112260085 AT qq.com");
translators+=QString("<br /><br /><br />");
translators+=QString("zh_TW - ")+tr("Chinese Traditional translation");
translators+=QString("<br /><br /> ");
translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("James").arg("james AT cc.shu.edu.tw");
translators+=QString("<br />");
translatorsTextBrowser->setHtml(translators);
QString references=QString("");
references+=tr("You may find references for the algorithms and techniques used in this program on the FET documentation web page, %1")
.arg("<a href=\"https://lalescu.ro/liviu/fet/doc/\">https://lalescu.ro/liviu/fet/doc/</a>");
references+="<br />";
referencesTextBrowser->setHtml(references);
QString thanksTo=QString("");
thanksTo+=QString("(")+tr("chronologically")+QString("):");
thanksTo+=QString("<br /><br />");
thanksTo+=QString::fromUtf8("Costin Bădică");
thanksTo+=QString("<br />");
thanksTo+=QString("Carsten Niehaus");
thanksTo+=QString("<br />");
thanksTo+=QString("Imre Nagy");
thanksTo+=QString("<br />");
thanksTo+=QString("Sajith V. K.");
thanksTo+=QString("<br />");
thanksTo+=QString("Michael Towers");
thanksTo+=QString("<br />");
thanksTo+=QString("Antti Leppik");
thanksTo+=QString("<br />");
thanksTo+=QString("Ian Fantom");
thanksTo+=QString("<br />");
thanksTo+=QString("Simon Ghetti");
thanksTo+=QString("<br />");
thanksTo+=QString("Gibbon Tamba");
thanksTo+=QString("<br />");
thanksTo+=QString("Jerome Durand");
thanksTo+=QString("<br />");
thanksTo+=QString("Marek Jaszuk");
thanksTo+=QString("<br />");
thanksTo+=QString("Ramanathan Srinivasan");
thanksTo+=QString("<br />");
thanksTo+=QString("Vimal Joseph");
thanksTo+=QString("<br />");
thanksTo+=QString("Cristian Gherman");
thanksTo+=QString("<br />");
thanksTo+=QString("Nicholas Robinson");
thanksTo+=QString("<br />");
thanksTo+=QString("Radu Spineanu");
thanksTo+=QString("<br />");
thanksTo+=QString("Morten Piil");
thanksTo+=QString("<br />");
thanksTo+=QString("Sebastian Canagaratna");
thanksTo+=QString("<br />");
thanksTo+=QString("Abdul Hadi Kamel");
thanksTo+=QString("<br />");
thanksTo+=QString("Miguel Gea Milvaques");
thanksTo+=QString("<br />");
thanksTo+=QString("Frans de Bruijn");
thanksTo+=QString("<br />");
thanksTo+=QString("Radoslaw Pasiok");
thanksTo+=QString("<br />");
thanksTo+=QString("Daan Huntjens");
thanksTo+=QString("<br />");
thanksTo+=QString("Yush Yuen");
thanksTo+=QString("<br />");
thanksTo+=QString("Scott Sweeting");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Dragoș Petrașcu");
thanksTo+=QString("<br />");
thanksTo+=QString("Daniel S.");
thanksTo+=QString("<br />");
thanksTo+=QString("Gianluca Salvo");
thanksTo+=QString("<br />");
thanksTo+=QString("Sebastian O'Halloran");
thanksTo+=QString("<br />");
thanksTo+=QString("Mehmet Gezmisoglu");
thanksTo+=QString("<br />");
thanksTo+=QString("Tom Hosty");
thanksTo+=QString("<br />");
thanksTo+=QString("Niels Fikse");
thanksTo+=QString("<br />");
thanksTo+=QString("Simon Bohlin");
thanksTo+=QString("<br />");
thanksTo+=QString("Volker Dirr");
thanksTo+=QString("<br />");
thanksTo+=QString("Les Richardson");
thanksTo+=QString("<br />");
thanksTo+=QString("Gabi Danon");
thanksTo+=QString("<br />");
thanksTo+=QString("Manolo Par");
thanksTo+=QString("<br />");
thanksTo+=QString("Viktor Ferenczi");
thanksTo+=QString("<br />");
thanksTo+=QString("Patrick Fox");
thanksTo+=QString("<br />");
thanksTo+=QString("Andres Chandia");
thanksTo+=QString("<br />");
thanksTo+=QString("Zoran Zdravkovski");
thanksTo+=QString("<br />");
thanksTo+=QString("Constantin Romulus");
thanksTo+=QString("<br />");
thanksTo+=QString("L. W. Johnstone");
thanksTo+=QString("<br />");
thanksTo+=QString("Zsolt Udvari");
thanksTo+=QString("<br />");
thanksTo+=QString("mantas");
thanksTo+=QString("<br />");
thanksTo+=QString("moryus");
thanksTo+=QString("<br />");
thanksTo+=QString("bb");
thanksTo+=QString("<br />");
thanksTo+=QString("Maciej Deorowicz");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("José César Fernández López");
thanksTo+=QString("<br />");
thanksTo+=QString("Daniel Chiriac");
thanksTo+=QString("<br />");
thanksTo+=QString("Dimitrios Ropokis");
thanksTo+=QString("<br />");
thanksTo+=QString("Danail");
thanksTo+=QString("<br />");
thanksTo+=QString("Peter Ambroz");
thanksTo+=QString("<br />");
thanksTo+=QString("Nirwan Yus");
thanksTo+=QString("<br />");
thanksTo+=QString("Marco Barsotti");
thanksTo+=QString("<br />");
thanksTo+=QString("Silver");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Horațiu Hălmăjan");
thanksTo+=QString("<br />");
thanksTo+=QString("kdsayang");
thanksTo+=QString("<br />");
thanksTo+=QString("didit");
thanksTo+=QString("<br />");
thanksTo+=QString("Bobby Wise");
thanksTo+=QString("<br />");
thanksTo+=QString("Willy Henckert");
thanksTo+=QString("<br />");
thanksTo+=QString("Wilfred");
thanksTo+=QString("<br />");
thanksTo+=QString("W. D. John");
thanksTo+=QString("<br />");
thanksTo+=QString("Darius Staigys");
thanksTo+=QString("<br />");
thanksTo+=QString("George Miliotis [Ionio]");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Sílvia");
thanksTo+=QString("<br />");
thanksTo+=QString("Chafik Graiguer");
thanksTo+=QString("<br />");
thanksTo+=QString("Niels Stargardt");
thanksTo+=QString("<br />");
thanksTo+=QString("Cristian Balint");
thanksTo+=QString("<br />");
thanksTo+=QString("sherman");
thanksTo+=QString("<br />");
thanksTo+=QString("Azu Boba");
thanksTo+=QString("<br />");
thanksTo+=QString("Thomas Schwartz");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Cătălin Maican");
thanksTo+=QString("<br />");
thanksTo+=QString("Ilya V. Paramonov");
thanksTo+=QString("<br />");
thanksTo+=QString("Hamed SadeghiNeshat");
thanksTo+=QString("<br />");
thanksTo+=QString("Joan de Gracia");
thanksTo+=QString("<br />");
thanksTo+=QString("Massimo Mancini");
thanksTo+=QString("<br />");
thanksTo+=QString("Regina V. Kryvakovska");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("ßingen");
thanksTo+=QString("<br />");
thanksTo+=QString("Angela");
thanksTo+=QString("<br />");
thanksTo+=QString("T. Renganathan");
thanksTo+=QString("<br />");
thanksTo+=QString("Marco");
thanksTo+=QString("<br />");
thanksTo+=QString("sally sat");
thanksTo+=QString("<br />");
thanksTo+=QString("sstt2");
thanksTo+=QString("<br />");
thanksTo+=QString("Nikos Koutsoukos");
thanksTo+=QString("<br />");
thanksTo+=QString("pinco");
thanksTo+=QString("<br />");
thanksTo+=QString("Ben Bauer");
thanksTo+=QString("<br />");
thanksTo+=QString("Rodica Lalescu");
thanksTo+=QString("<br />");
thanksTo+=QString("Gigica Nedelcu");
thanksTo+=QString("<br />");
thanksTo+=QString("Paolo Cataldi");
thanksTo+=QString("<br />");
thanksTo+=QString("Gerrit Jan Veltink");
thanksTo+=QString("<br />");
thanksTo+=QString("Soyeb Aswat");
thanksTo+=QString("<br />");
thanksTo+=QString("Andriy Melnyk");
thanksTo+=QString("<br />");
thanksTo+=QString("Frans");
thanksTo+=QString("<br />");
thanksTo+=QString("m");
thanksTo+=QString("<br />");
thanksTo+=QString("Christoph Schilling");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Frank Mártin");
thanksTo+=QString("<br />");
thanksTo+=QString("Werner Bruns");
thanksTo+=QString("<br />");
thanksTo+=QString("aliponte");
thanksTo+=QString("<br />");
thanksTo+=QString("David Lamhauge");
thanksTo+=QString("<br />");
thanksTo+=QString("murad");
thanksTo+=QString("<br />");
thanksTo+=QString("Achini Duisna");
thanksTo+=QString("<br />");
thanksTo+=QString("Ondrej Gregor");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Karel Rodríguez Varona");
thanksTo+=QString("<br />");
thanksTo+=QString("Remus Turea");
thanksTo+=QString("<br />");
thanksTo+=QString("Joachim");
thanksTo+=QString("<br />");
thanksTo+=QString("Chichi Lalescu");
thanksTo+=QString("<br />");
thanksTo+=QString("Iftekhar Ahmad");
thanksTo+=QString("<br />");
thanksTo+=QString("DT");
thanksTo+=QString("<br />");
thanksTo+=QString("Yotam Medini");
thanksTo+=QString("<br />");
thanksTo+=QString("mohd");
thanksTo+=QString("<br />");
thanksTo+=QString("Dimitris Kanatas");
thanksTo+=QString("<br />");
thanksTo+=QString("waleed");
thanksTo+=QString("<br />");
thanksTo+=QString("aang");
thanksTo+=QString("<br />");
thanksTo+=QString("M K Lohumi");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Régis Bouguin");
thanksTo+=QString("<br />");
thanksTo+=QString("Ivan Starchevicy");
thanksTo+=QString("<br />");
thanksTo+=QString("Radan Putnik");
thanksTo+=QString("<br />");
thanksTo+=QString("Asti Widayanti");
thanksTo+=QString("<br />");
thanksTo+=QString("uni_instructor");
thanksTo+=QString("<br />");
thanksTo+=QString("liquid");
thanksTo+=QString("<br />");
thanksTo+=QString("Juan Marcos Filgueira Gomis");
thanksTo+=QString("<br />");
thanksTo+=QString("llantones");
thanksTo+=QString("<br />");
thanksTo+=QString("Christian Kemmer");
thanksTo+=QString("<br />");
thanksTo+=QString("Davide G. M. Salvetti");
thanksTo+=QString("<br />");
thanksTo+=QString("lalloso");
thanksTo+=QString("<br />");
thanksTo+=QString("drew");
thanksTo+=QString("<br />");
thanksTo+=QString("Fabio Piedimonte");
thanksTo+=QString("<br />");
thanksTo+=QString("K");
thanksTo+=QString("<br />");
thanksTo+=QString("skinkone");
thanksTo+=QString("<br />");
thanksTo+=QString("Jonathan Block");
thanksTo+=QString("<br />");
thanksTo+=QString("Nguyen Truong Thang");
thanksTo+=QString("<br />");
thanksTo+=QString("kdrosos");
thanksTo+=QString("<br />");
thanksTo+=QString("Ian Holden");
thanksTo+=QString("<br />");
thanksTo+=QString("Sarwan Bangar");
thanksTo+=QString("<br />");
thanksTo+=QString("Petros Nouvakis");
thanksTo+=QString("<br />");
thanksTo+=QString("mma");
thanksTo+=QString("<br />");
thanksTo+=QString("Orzubek Eraliyev");
thanksTo+=QString("<br />");
thanksTo+=QString("k1aas");
thanksTo+=QString("<br />");
thanksTo+=QString("nomad");
thanksTo+=QString("<br />");
thanksTo+=QString("Robert Sutcliffe");
thanksTo+=QString("<br />");
thanksTo+=QString("rjmillett");
thanksTo+=QString("<br />");
thanksTo+=QString("yasin dehghan");
thanksTo+=QString("<br />");
thanksTo+=QString("Daniel");
thanksTo+=QString("<br />");
thanksTo+=QString("Pietro");
thanksTo+=QString("<br />");
thanksTo+=QString("arivasm");
thanksTo+=QString("<br />");
thanksTo+=QString("AZ");
thanksTo+=QString("<br />");
thanksTo+=QString("Etlau");
thanksTo+=QString("<br />");
thanksTo+=QString("Nemo");
thanksTo+=QString("<br />");
thanksTo+=QString("Anton Anthofer");
thanksTo+=QString("<br />");
thanksTo+=QString("Danny Zitzman");
thanksTo+=QString("<br />");
thanksTo+=QString("geaplanet");
thanksTo+=QString("<br />");
thanksTo+=QString("Leandro Bueno");
thanksTo+=QString("<br />");
thanksTo+=QString("Laid Messaoudi");
thanksTo+=QString("<br />");
thanksTo+=QString("karim");
thanksTo+=QString("<br />");
thanksTo+=QString("hicham_idrissi");
thanksTo+=QString("<br />");
thanksTo+=QString("Davide Cottignoli");
thanksTo+=QString("<br />");
thanksTo+=QString("agemagician");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Vlăduț Frățiman");
thanksTo+=QString("<br />");
thanksTo+=QString("vlad2005");
thanksTo+=QString("<br />");
thanksTo+=QString("mouiata");
thanksTo+=QString("<br />");
thanksTo+=QString("rapsy");
thanksTo+=QString("<br />");
thanksTo+=QString("clouds");
thanksTo+=QString("<br />");
thanksTo+=QString("MarioMic");
thanksTo+=QString("<br />");
thanksTo+=QString("Cloves das Neves");
thanksTo+=QString("<br />");
thanksTo+=QString("pedrobordon");
thanksTo+=QString("<br />");
thanksTo+=QString("Tony Chan");
thanksTo+=QString("<br />");
thanksTo+=QString("Artur Lugu");
thanksTo+=QString("<br />");
thanksTo+=QString("plaldw");
thanksTo+=QString("<br />");
thanksTo+=QString("jimmyjim");
thanksTo+=QString("<br />");
thanksTo+=QString("Curtis Wilson");
thanksTo+=QString("<br />");
thanksTo+=QString("Mohamed Bahaj");
thanksTo+=QString("<br />");
thanksTo+=QString("Thomas Klausner");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Jörg Sonnenberger");
thanksTo+=QString("<br />");
thanksTo+=QString("Boubker");
thanksTo+=QString("<br />");
thanksTo+=QString("Alexey Loginov");
thanksTo+=QString("<br />");
thanksTo+=QString("_indianajones");
thanksTo+=QString("<br />");
thanksTo+=QString("russell");
thanksTo+=QString("<br />");
thanksTo+=QString("Nguyen Huu Tuyen");
thanksTo+=QString("<br />");
thanksTo+=QString("fromturkey");
thanksTo+=QString("<br />");
thanksTo+=QString("orange");
thanksTo+=QString("<br />");
thanksTo+=QString("nguyenhuuduyet");
thanksTo+=QString("<br />");
thanksTo+=QString("Vanyo Georgiev");
thanksTo+=QString("<br />");
thanksTo+=QString("bharatstank");
thanksTo+=QString("<br />");
thanksTo+=QString("alxgudea");
thanksTo+=QString("<br />");
thanksTo+=QString("andrealva");
thanksTo+=QString("<br />");
thanksTo+=QString("dotosouza");
thanksTo+=QString("<br />");
thanksTo+=QString("Bob Hairgrove");
thanksTo+=QString("<br />");
thanksTo+=QString("James");
thanksTo+=QString("<br />");
thanksTo+=QString("Khalilullah Yosufi");
thanksTo+=QString("<br />");
thanksTo+=QString("mercurialuser");
thanksTo+=QString("<br />");
thanksTo+=QString("azaer");
thanksTo+=QString("<br />");
thanksTo+=QString("chintu");
thanksTo+=QString("<br />");
thanksTo+=QString("khalafi");
thanksTo+=QString("<br />");
thanksTo+=QString("jillali elghazoui");
thanksTo+=QString("<br />");
thanksTo+=QString("Mohamed NAJARI");
thanksTo+=QString("<br />");
thanksTo+=QString("youssouf");
thanksTo+=QString("<br />");
thanksTo+=QString("Pascal Cohen");
thanksTo+=QString("<br />");
thanksTo+=QString("Asier Urio Larrea");
thanksTo+=QString("<br />");
thanksTo+=QString("Pavel Fric");
thanksTo+=QString("<br />");
thanksTo+=QString("Michel");
thanksTo+=QString("<br />");
thanksTo+=QString("MilesM");
thanksTo+=QString("<br />");
thanksTo+=QString("adso");
thanksTo+=QString("<br />");
thanksTo+=QString("locutusofborg");
thanksTo+=QString("<br />");
thanksTo+=QString("Maouhoub");
thanksTo+=QString("<br />");
thanksTo+=QString("flauta");
thanksTo+=QString("<br />");
thanksTo+=QString("Marco Vassura");
thanksTo+=QString("<br />");
thanksTo+=QString("Luigi Valbonesi");
thanksTo+=QString("<br />");
thanksTo+=QString("fernandolordao");
thanksTo+=QString("<br />");
thanksTo+=QString("Wizard");
thanksTo+=QString("<br />");
thanksTo+=QString("ant7");
thanksTo+=QString("<br />");
thanksTo+=QString("Lizio");
thanksTo+=QString("<br />");
thanksTo+=QString("Omar Ben Ali");
thanksTo+=QString("<br />");
thanksTo+=QString("Nguyen Trong Hieu");
thanksTo+=QString("<br />");
thanksTo+=QString("Arsenio Stabile");
thanksTo+=QString("<br />");
thanksTo+=QString("Vangelis Karafillidis");
thanksTo+=QString("<br />");
thanksTo+=QString("Handaya");
thanksTo+=QString("<br />");
thanksTo+=QString("Sudharshan K M");
thanksTo+=QString("<br />");
thanksTo+=QString("Nataraj Urs H D");
thanksTo+=QString("<br />");
thanksTo+=QString("Alexandre R. Soares");
thanksTo+=QString("<br />");
thanksTo+=QString("hudrea");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Udo Schütz");
thanksTo+=QString("<br />");
thanksTo+=QString("Jijo Jose");
thanksTo+=QString("<br />");
thanksTo+=QString("Fernando Poblete");
thanksTo+=QString("<br />");
thanksTo+=QString("Benahmed Abdelkrim");
thanksTo+=QString("<br />");
thanksTo+=QString("math user");
thanksTo+=QString("<br />");
thanksTo+=QString("ChicagoPianoTuner");
thanksTo+=QString("<br />");
thanksTo+=QString("MING-KIAN JONATHAN CEDRIC LEE KIM GNOK");
thanksTo+=QString("<br />");
thanksTo+=QString("daltinkurt");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Léo-Paul Roch");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Matthias Söllner");
thanksTo+=QString("<br />");
thanksTo+=QString("auriolar");
thanksTo+=QString("<br />");
thanksTo+=QString("dmcdonald");
thanksTo+=QString("<br />");
thanksTo+=QString("wahyuamin");
thanksTo+=QString("<br />");
thanksTo+=QString("abautu");
thanksTo+=QString("<br />");
thanksTo+=QString("Jan Losinski");
thanksTo+=QString("<br />");
thanksTo+=QString("mrtvillaret");
thanksTo+=QString("<br />");
thanksTo+=QString("alienglow");
thanksTo+=QString("<br />");
thanksTo+=QString("noddy11");
thanksTo+=QString("<br />");
thanksTo+=QString("JBoss");
thanksTo+=QString("<br />");
thanksTo+=QString("thanhnambkhn");
thanksTo+=QString("<br />");
thanksTo+=QString("Malamojka");
thanksTo+=QString("<br />");
thanksTo+=QString("canhathuongnhau");
thanksTo+=QString("<br />");
thanksTo+=QString("rodolforg");
thanksTo+=QString("<br />");
thanksTo+=QString("dasa");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Julio González Gil");
thanksTo+=QString("<br />");
thanksTo+=QString("Abou");
thanksTo+=QString("<br />");
thanksTo+=QString("Matsumoto");
thanksTo+=QString("<br />");
thanksTo+=QString("bart.leyen");
thanksTo+=QString("<br />");
thanksTo+=QString("math");
thanksTo+=QString("<br />");
thanksTo+=QString("s.lanore");
thanksTo+=QString("<br />");
thanksTo+=QString("Robinson A. Lemos");
thanksTo+=QString("<br />");
thanksTo+=QString("Maurino C. Maria");
thanksTo+=QString("<br />");
thanksTo+=QString("Valdo");
thanksTo+=QString("<br />");
thanksTo+=QString("sigit_yuwono");
thanksTo+=QString("<br />");
thanksTo+=QString("S Chandrasekar");
thanksTo+=QString("<br />");
thanksTo+=QString("utismetis");
thanksTo+=QString("<br />");
thanksTo+=QString("chernous");
thanksTo+=QString("<br />");
thanksTo+=QString("Roberto Bergonzini");
thanksTo+=QString("<br />");
thanksTo+=QString("sln_rj");
thanksTo+=QString("<br />");
thanksTo+=QString::fromUtf8("Emiliano Llano Díaz");
thanksTo+=QString("<br />");
thanksTo+=QString("mohammed");
thanksTo+=QString("<br />");
thanksTo+=QString("Taro Tada");
thanksTo+=QString("<br />");
thanksTo+=QString("V Paul C Charlesraj");
thanksTo+=QString("<br />");
thanksTo+=QString("Innocent De Marchi");
thanksTo+=QString("<br />");
thanksTo+=QString("Yakup Kadri Demirci");
thanksTo+=QString("<br />");
thanksTo+=QString("bachiri401");
thanksTo+=QString("<br />");
thanksTo+=QString("francescotorres");
thanksTo+=QString("<br />");
thanksTo+=QString("aisse");
thanksTo+=QString("<br />");
thanksTo+=QString("svenvanhal");
thanksTo+=QString("<br />");
thanksTo+=QString("Coralie");
thanksTo+=QString("<br />");
thanksTo+=QString("Diego Froner");
thanksTo+=QString("<br />");
thanksTo+=QString("pg788");
thanksTo+=QString("<br />");
thanksTo+=QString("Dietmar Deuster");
thanksTo+=QString("<br />");
thanksTo+=QString("Ahmed Ben Hassan");
thanksTo+=QString("<br />");
thanksTo+=QString("amin");
thanksTo+=QString("<br />");
thanksTo+=QString("Anthony Siaudeau");
thanksTo+=QString("<br />");
thanksTo+=QString("satellite2");
thanksTo+=QString("<br />");
thanksTo+=QString("Jude G");
thanksTo+=QString("<br />");
thanksToTextBrowser->setHtml(thanksTo);
}
HelpAboutForm::~HelpAboutForm()
{
saveFETDialogGeometry(this);
}
|
rodolforg/fet
|
src/interface/helpaboutform.cpp
|
C++
|
agpl-3.0
| 41,583
|
{% load i18n %}
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<input type="text" class="form-control name" name="challenge_name_{{ n }}"
placeholder="{% trans 'Challenge name' %}" value="{{ challenge.name }}"/>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<select id="type" class="type" name="challenge_type_{{ n }}">
<option value="p" {% if challenge.ctype == 'p' %}selected{% endif %}>{% trans "Player" %}</option>
<option value="np" {% if challenge.ctype == 'np' %}selected{% endif %}>{% trans "Position / Actor" %}</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<textarea class="form-control desc" name="challenge_desc_{{ n }}"
placeholder="{% trans 'Challenge description' %}">{{ challenge.desc }}</textarea>
<p class="help-block">{% trans "You can use here html" %}</p>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="text" class="form-control depend" name="challenge_depends_on_{{ n }}"
placeholder="{% trans 'Challenge depends' %}" value="{{ challenge.depends_on }}"/>
<p class="help-block">{% trans "Names separated by ','. To get this challenge the player should have all the challenges named here before" %}</p>
</div>
</div>
</div>
|
wadobo/socializa
|
backend/editor/templates/editor/forms/challenge.html
|
HTML
|
agpl-3.0
| 1,540
|
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa30;
import org.asqatasun.entity.audit.IndefiniteResult;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.entity.subject.Page;
import org.asqatasun.entity.subject.Site;
import org.asqatasun.rules.rgaa30.test.Rgaa30RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 12.3.2 of the referential Rgaa 3.0.
*
* @author jkowalczyk
*/
public class Rgaa30Rule120302Test extends Rgaa30RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa30Rule120302Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName("org.asqatasun.rules.rgaa30.Rgaa30Rule120302");
}
@Override
protected void setUpWebResourceMap() {
getWebResourceMap().put("Rgaa30.Test.12.03.02-4NA-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "rgaa30/Rgaa30Rule120302/Rgaa30.Test.12.03.02-3NMI-01.html"));
Site site = getWebResourceFactory().createSite("file:Site-NotTested");
getWebResourceMap().put("Rgaa30.Test.12.03.02-5NT-01", site);
Page page = getWebResourceFactory().createPage(getTestcasesFilePath() +
"rgaa30/Rgaa30Rule120302/Rgaa30.Test.12.03.02-3NMI-01.html");
site.addChild(page);
getWebResourceMap().put("Rgaa30.Test.12.03.02-5NT-01-page1",page);
page = getWebResourceFactory().createPage(getTestcasesFilePath() +
"rgaa30/Rgaa30Rule120302/Rgaa30.Test.12.03.02-3NMI-01.html");
site.addChild(page);
getWebResourceMap().put("Rgaa30.Test.12.03.02-5NT-01-page1",page);
}
@Override
protected void setProcess() {
ProcessResult pr = processPageTest("Rgaa30.Test.12.03.02-4NA-01");
assertTrue(pr instanceof IndefiniteResult);
assertEquals(getWebResourceMap().get("Rgaa30.Test.12.03.02-4NA-01"),pr.getSubject());
assertEquals("mock-result", pr.getValue());
process("Rgaa30.Test.12.03.02-5NT-01");
}
@Override
protected void setConsolidate() {
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa30.Test.12.03.02-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa30.Test.12.03.02-5NT-01").getValue());
}
}
|
dzc34/Asqatasun
|
rules/rules-rgaa3.0/src/test/java/org/asqatasun/rules/rgaa30/Rgaa30Rule120302Test.java
|
Java
|
agpl-3.0
| 3,319
|
<div class="subnav subnav--plain">
<header class="search-page-header">
<div class="filter-trigger" ng-click="openAdvanceSearch = !openAdvanceSearch" ng-class="{'filter-trigger--active': openAdvanceSearch}"><i class="icon-filter-large"></i></div>
<div sd-pagination data-items="items"></div>
<div class="searchbar-flex-handler"></div>
<div sd-legal-item-sortbar></div>
<div class="view-select">
<button tooltip="{{ :: 'switch to grid view' | translate }}" tooltip-placement="left" ng-show="view !== 'mgrid'" ng-click="setview('mgrid')"><i class="icon-th"></i></button>
<button tooltip="{{ :: 'switch to list view' | translate }}" tooltip-placement="left" ng-show="view !== 'compact'" ng-click="setview('compact')"><i class="icon-th-list"></i></button>
</div>
</header>
</div>
<section class="search main-section search-page-container" ng-class="{'sidebar-open': openAdvanceSearch}">
<div class="archive-sidebar"> <!-- Search widget -->
<div class="header">
<ul>
<li translate>Search</li>
</ul>
<div class="doopen" ng-click="openAdvanceSearch = false"><i class="icon-close-small"></i></div>
</div>
<div class="content">
<div data-context="context" >
<form>
<fieldset>
<div class="field">
<label for="search-story-id">{{:: 'GUID' | translate}}</label>
<div class="control">
<input type="text" id="search-story-id" ng-model="criteria._id" tabindex="1">
</div>
</div>
<div class="field">
<label for="search-unique-id">{{:: 'Unique Name' | translate}}</label>
<div class="control">
<input type="text" id="search-unique-id" ng-model="criteria.unique_name" tabindex="1">
</div>
</div>
<div class="field">
<label for="search-headline">{{:: 'Headline' | translate}}</label>
<div class="control">
<input type="text" id="search-headline" ng-model="criteria.headline" tabindex="2">
</div>
</div>
<div class="field">
<label for="search-slugline">{{:: 'Slugline' | translate}}</label>
<div class="control">
<input type="text" id="search-slugline" ng-model="criteria.slugline" tabindex="3">
</div>
</div>
<div class="field">
<label for="search-storytext">{{:: 'Story Text' | translate}}</label>
<div class="control">
<input type="text" id="search-storytext" ng-model="criteria.body_html" tabindex="4">
</div>
</div>
<div class="field" sd-date-param data-location="criteria.published_after">
<label for="published_after" translate>Published From</label>
<div sd-datepicker id="published_after" ng-model="criteria.published_after"></div>
</div>
<div class="field" sd-date-param data-location="criteria.published_before">
<label for="published_before" translate>Published Until</label>
<div sd-datepicker id="published_before" ng-model="criteria.published_before"></div>
</div>
</fieldset>
</form>
<div class="actions">
<button class="btn btn--primary pull-right" ng-click="search()" tabindex="7" translate>Go</button>
<button class="btn btn--primary pull-right" ng-click="clear()" tabindex="8" translate>Clear</button>
</div>
</div>
</div>
</div>
<div class="archive-content">
<div class="preview-layout" ng-class="{closed: !selected.preview}" >
<div class="list-pane {{ view || 'list' }}-view">
<div id="content-list" class="content" sd-updown data-items="items._items" data-select="preview(item)">
<div class="loading-indicator" ng-show="loading" translate>loading</div>
<div class="shadow-list-holder" sd-items-list></div>
</div>
</div>
<div id="item-preview" class="preview-pane content-item-preview" ng-show="selected.preview" ng-init="tab = 'content'">
<header>
<ul class="nav nav-tabs">
<li ng-class="{active: tab === 'content'}">
<button ng-click="tab = 'content'"><span translate>Content</span></button>
</li>
<li ng-class="{active: tab === 'metadata'}">
<button ng-click="tab = 'metadata'"><span translate>Metadata</span></button>
</li>
<li ng-class="{active: tab === 'history'}">
<button ng-click="tab = 'history'"><span translate>Item history</span></button>
</li>
</ul>
<button ng-click="preview(null)" class="close-preview">
<i class="icon-close-small"></i>
</button>
</header>
<div class="content" ng-if="selected.preview">
<div ng-if="tab === 'content'" sd-media-preview></div>
<div ng-if="tab === 'metadata'" sd-media-metadata data-item="selected.preview"></div>
<div ng-if="tab === 'history'" sd-versioning-history data-item="selected.preview"></div>
</div>
</div>
</div>
</div>
</section>
<div sd-media-view data-item="selected.view" data-items="items._items" ng-if="selected.view" data-close="closeLightbox()"></div>
|
thnkloud9/superdesk-client-core
|
scripts/apps/legal-archive/views/legal_archive.html
|
HTML
|
agpl-3.0
| 6,399
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_bio_engineer_creature_creature_rancor = object_draft_schematic_bio_engineer_creature_shared_creature_rancor:new {
templateType = DRAFTSCHEMATIC,
disableFactoryRun = true,
customObjectName = "Rancor",
craftingToolTab = 256, -- (See DraftSchematicObjectTemplate.h)
complexity = 30,
size = 1,
xpType = "crafting_bio_engineer_creature",
xp = 290,
assemblySkill = "bio_engineer_assembly",
experimentingSkill = "bio_engineer_experimentation",
customizationSkill = "bio_engineer_experimentation",
customizationOptions = {},
customizationStringNames = {},
customizationDefaults = {},
ingredientTemplateNames = {"craft_creature_ingredients_n", "craft_creature_ingredients_n", "craft_creature_ingredients_n"},
ingredientTitleNames = {"dna_template", "protein_base", "organic_nutrition_materials"},
ingredientSlotType = {1, 0, 0},
resourceTypes = {"object/tangible/component/dna/shared_dna_template_generic.iff", "creature_food", "flora_food"},
resourceQuantities = {1, 80, 70},
contribution = {100, 100, 100},
targetTemplate = "object/tangible/deed/pet_deed/rancor_deed.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_bio_engineer_creature_creature_rancor, "object/draft_schematic/bio_engineer/creature/creature_rancor.iff")
|
Tatwi/legend-of-hondo
|
MMOCoreORB/bin/scripts/object/draft_schematic/bio_engineer/creature/creature_rancor.lua
|
Lua
|
agpl-3.0
| 3,374
|
{% extends "/base.html" %}
{% set active_page = "applications" %}
{% set active_app = "all" %}
{% import "applications/_helpers.html" as helper %}
{% block content %}
{{ helper.render_loading(text=loading_text) }}
<div class="row">
<div class="col-sm-3" style="padding: 8px 0;">
{{ helper.render_app_local_nav(app, "tasks", current_user) }}
</div>
<div id="body" class="col-sm-9" style="min-height:400px;">
{{ helper.render_app_title(app, subtitle=_('Export All Tasks and Task Runs'))}}
<p>{{ _('You can export and download') }} <strong>{{ _('all the available') }}</strong> {{ _('Tasks and Task Runs \(the submitted answers by the users\) in CSV or JSON formats.') }}</p>
<div class="row">
<div id="csv" class="col-sm-6 well">
<h2>Export in CSV format</h2>
<a href={{url_for('app.export_to', short_name=app.short_name, type='task', format='csv')}} class="btn btn-large">{{ _('Tasks') }}</a>
<a href={{url_for('app.export_to', short_name=app.short_name, type='task_run', format='csv')}} class="btn btn-large">{{ _('Task Runs') }}</a>
</div>
<div id="json" class="col-sm-6 well">
<h2>Export in JSON format</h2>
<a href={{url_for('app.export_to', short_name=app.short_name, type='task', format='json')}} class="btn btn-large">{{ _('Tasks') }}</a>
<a href={{url_for('app.export_to', short_name=app.short_name, type='task_run', format='json')}} class="btn btn-large">{{ _('Task Runs') }}</a>
</div>
</div>
<div class="row">
{% if current_user.is_authenticated() and app.owner_id == current_user.id %}
<div id="ckan" class="col-sm-6 well">
{% if ckan_name %}
<h2>Export to the {{ckan_name}}</h2>
{% else %}
<h2>Export to a CKAN server</h2>
{% endif %}
<p><span class="label label-danger"><i class="icon-bullhorn"></i> IMPORTANT</span> This export option stills in beta mode and may fail in the CKAN server. If you get an error, please send an e-mail to info@pybossa.com</p>
{% if current_user.ckan_api %}
<a id="ckan_task" href="{{url_for('app.export_to', short_name=app.short_name, type='task', format='ckan')}}" class="btn btn-large">{{_('Tasks')}}</a>
<a id="ckan_task_run" href="{{url_for('app.export_to', short_name=app.short_name, type='task_run', format='ckan')}}" class="btn btn-large">{{_('Task Runs')}}</a>
{% else %}
<p id="ckan_warning">You don't have a Datahub.io API key in your {{BRAND}} account. Please, <a href="http://datahub.io/user/register">create an account</a> and copy/paste the API key in your profile in order to use this exporter.</p>
{% endif %}
</div>
{% endif %}
</div>
</div>
</div>
<script>
$("#ckan > a").off('click').on('click', function(){
$("#loading").show();
});
</script>
{% endblock %}
|
geotagx/geotagx-pybossa-archive
|
pybossa/templates/applications/export.html
|
HTML
|
agpl-3.0
| 3,097
|
/*
Copyright (C) 2017 by Claude SIMON (http://zeusw.org/epeios/contact.html).
This file is part of XDHq.
XDHq is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
XDHq is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with XDHq. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REGISTRY_INC_
# define REGISTRY_INC_
# include "sclr.h"
namespace registry {
using namespace sclr;
namespace parameter {
using namespace sclr::parameter;
extern rEntry Service;
}
namespace definition {
using namespace sclr::definition;
}
}
#endif
|
epeios-q37/epeios
|
tools/xdhq/wrappers/JRE/registry.h
|
C
|
agpl-3.0
| 1,034
|
import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellIcon } from 'interface';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { ThresholdStyle } from 'parser/core/ParseResults';
import BoringValue from 'parser/ui/BoringValueText';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import React from 'react';
import { SPELLS_WHICH_REMOVE_BOC } from '../../constants';
const debug = false;
const BOC_DURATION = 15000;
class BlackoutCombo extends Analyzer {
get dpsWasteThreshold() {
return {
actual: this.spellsBOCWasUsedOn[SPELLS.TIGER_PALM.id] / this.blackoutComboBuffs,
isLessThan: {
minor: 0.95,
average: 0.9,
major: 0.85,
},
style: ThresholdStyle.PERCENTAGE,
};
}
blackoutComboConsumed = 0;
blackoutComboBuffs = 0;
lastBlackoutComboCast = 0;
spellsBOCWasUsedOn = {};
statisticOrder = STATISTIC_ORDER.OPTIONAL();
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.BLACKOUT_COMBO_TALENT.id);
this.addEventListener(
Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF),
this.onApplyBuff,
);
this.addEventListener(
Events.refreshbuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF),
this.onRefreshBuff,
);
this.addEventListener(
Events.cast.by(SELECTED_PLAYER).spell(SPELLS_WHICH_REMOVE_BOC),
this.onCast,
);
}
onApplyBuff(event) {
debug && console.log('Blackout combo applied');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
onRefreshBuff(event) {
debug && console.log('Blackout combo refreshed');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
onCast(event) {
const spellId = event.ability.guid;
// BOC should be up
if (
this.lastBlackoutComboCast > 0 &&
this.lastBlackoutComboCast + BOC_DURATION > event.timestamp
) {
this.blackoutComboConsumed += 1;
if (this.spellsBOCWasUsedOn[spellId] === undefined) {
this.spellsBOCWasUsedOn[spellId] = 0;
}
this.spellsBOCWasUsedOn[spellId] += 1;
}
this.lastBlackoutComboCast = 0;
}
suggestions(when) {
const wastedPerc =
(this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
when(wastedPerc)
.isGreaterThan(0.1)
.addSuggestion((suggest, actual, recommended) =>
suggest(
<span>
You wasted {formatPercentage(actual)}% of your{' '}
<SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> procs. Try to use the procs as soon as
you get them so they are not overwritten.
</span>,
)
.icon(SPELLS.BLACKOUT_COMBO_BUFF.icon)
.actual(
t({
id: 'monk.brewmaster.suggestions.blackoutCombo.wasted',
message: `${formatPercentage(actual)}% unused`,
}),
)
.recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`)
.regular(recommended + 0.1)
.major(recommended + 0.2),
);
}
statistic() {
const wastedPerc =
(this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL()}
size="flexible"
tooltip={
<>
You got total <strong>{this.blackoutComboBuffs}</strong> Blackout Combo procs and used{' '}
<strong>{this.blackoutComboConsumed}</strong> of them.
<br />
Blackout combo buff usage:
<ul>
{Object.keys(this.spellsBOCWasUsedOn)
.sort((a, b) => this.spellsBOCWasUsedOn[b] - this.spellsBOCWasUsedOn[a])
.map((type) => (
<li key={type}>
<em>{SPELLS[type].name || 'Unknown'}</em> was used{' '}
{this.spellsBOCWasUsedOn[type]} time
{this.spellsBOCWasUsedOn[type] === 1 ? '' : 's'} (
{formatPercentage(this.spellsBOCWasUsedOn[type] / this.blackoutComboConsumed)}%)
</li>
))}
</ul>
</>
}
>
<BoringValue
label={
<>
<SpellIcon id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> Wasted Blackout Combo
</>
}
>
<>{formatPercentage(wastedPerc)}%</>
</BoringValue>
</Statistic>
);
}
}
export default BlackoutCombo;
|
anom0ly/WoWAnalyzer
|
analysis/monkbrewmaster/src/modules/spells/BlackoutCombo.js
|
JavaScript
|
agpl-3.0
| 4,812
|
/*
* Claudia Project
* http://claudia.morfeo-project.org
*
* (C) Copyright 2010 Telefonica Investigacion y Desarrollo
* S.A.Unipersonal (Telefonica I+D)
*
* See CREDITS file for info about members and contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License (AGPL) as
* published by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* If you want to use this software an plan to distribute a
* proprietary application in any way, and you are not licensing and
* distributing your source code under AGPL, you probably need to
* purchase a commercial license of the product. Please contact
* claudia-support@lists.morfeo-project.org for more information.
*/
package com.telefonica.claudia.slm.deployment.hwItems;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import org.hibernate.annotations.CollectionOfElements;
import com.telefonica.claudia.slm.deployment.VEEReplica;
import com.telefonica.claudia.slm.naming.DirectoryEntry;
import com.telefonica.claudia.slm.naming.FQN;
import com.telefonica.claudia.slm.naming.ReservoirDirectory;
@Entity
public class NIC implements DirectoryEntry {
@Id
@GeneratedValue
public long internalId;
private int id = 0;
private int throughput = 0;
@CollectionOfElements
private List<String> ipAddresses = new ArrayList<String>();
private byte[] macAddress = null;
@OneToOne(cascade={CascadeType.REFRESH, CascadeType.MERGE, CascadeType.PERSIST})
private NICConf nicConf = null;
@ManyToOne
private VEEReplica veeReplica = null;
@OneToOne(cascade={CascadeType.REFRESH, CascadeType.MERGE, CascadeType.PERSIST})
private FQN nicFQN = null;
public NIC() {}
public NIC(int id, NICConf nicConf, VEEReplica veeReplica) {
if(veeReplica == null)
throw new IllegalArgumentException("VEE replica cannot be null");
if(nicConf == null)
throw new IllegalArgumentException("NIC conf cannot be null");
this.id = id;
this.veeReplica = veeReplica;
this.nicConf = nicConf;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<String> getIPAddresses() {
return ipAddresses;
}
public void addIPAddress(String ipAddress) {
this.ipAddresses.add(ipAddress);
}
public byte[] getMacAddress() {
return macAddress;
}
public void setMacAddress(byte[] macAddress) {
this.macAddress = macAddress;
}
public int getThroughput() {
return throughput;
}
public void setThroughput(int throughput) {
this.throughput = throughput;
}
public VEEReplica getVEEReplica() {
return veeReplica;
}
public NICConf getNICConf() {
return nicConf;
}
public FQN getFQN() {
if(nicFQN == null)
nicFQN = ReservoirDirectory.getInstance().buildFQN(this);
return nicFQN;
}
@Override
public String toString() {
return getFQN().toString();
}
@Override
public int hashCode() {
return getFQN().hashCode();
}
@Override
public boolean equals(Object object) {
if(object == null)
return false;
if(!(object instanceof NIC))
return false;
return ((NIC)object).getFQN().equals(getFQN());
}
}
|
StratusLab/claudia
|
clotho/src/main/java/com/telefonica/claudia/slm/deployment/hwItems/NIC.java
|
Java
|
agpl-3.0
| 4,281
|
from LiSE import Engine
from LiSE.examples import kobold
from .util import ELiDEAppTest, window_with_widget, idle_until
class TestPythonEditor(ELiDEAppTest):
def setUp(self):
super().setUp()
with Engine(self.prefix) as eng:
kobold.inittest(eng)
def _get_actions_box(self):
app = self.app
idle_until(lambda: hasattr(app, 'mainscreen') and app.mainscreen.mainview and app.mainscreen.statpanel and hasattr(app.mainscreen, 'gridview'))
app.funcs.toggle()
idle_until(lambda: 'actions' in app.funcs.ids, 100, 'Never got actions box')
actions_box = app.funcs.ids.actions
idle_until(lambda: actions_box.editor, 100, 'Never got FuncEditor')
idle_until(lambda: actions_box.storelist, 100, 'Never got StoreList')
idle_until(lambda: actions_box.storelist.data, 100, 'Never got StoreList data')
return actions_box
def test_show_code(self):
app = self.app
win = window_with_widget(app.build())
actions_box = self._get_actions_box()
last = actions_box.storelist.data[-1]['name']
actions_box.storelist.selection_name = last
idle_until(lambda: 'funname' in actions_box.editor.ids, 100, 'Never got function input widget')
idle_until(lambda: actions_box.editor.ids.funname.hint_text, 100, "Never got function name")
idle_until(lambda: 'code' in actions_box.editor.ids, 100, "Never got code editor widget")
idle_until(lambda: actions_box.editor.ids.code.text, 100, "Never got source code")
def test_create_action(self):
app = self.app
win = window_with_widget(app.build())
actions_box = self._get_actions_box()
actions_box.editor.ids.funname.text = 'new_func'
actions_box.editor.ids.code.text = 'return "Hello, world!"'
app.stop()
with Engine(self.prefix) as eng:
assert hasattr(eng.action, 'new_func')
|
LogicalDash/LiSE
|
ELiDE/ELiDE/tests/test_python_editor.py
|
Python
|
agpl-3.0
| 1,944
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="generator" content="ApiGen 2.8.0" />
<meta name="robots" content="noindex" />
<title>File Component/Database/Component/Exception/ComponentException.php | Mark V</title>
<script type="text/javascript" src="resources/combined.js?4076080066"></script>
<script type="text/javascript" src="elementlist.js?2814603222"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?1143814050"/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic|Open+Sans:300' rel='stylesheet'
type='text/css' />
</head>
<body>
<div id="TopBar">
<ul>
<li><a href="http://derdu.github.io/MOC-Framework-Mark-V" title="DerDu"
onclick="window.open(this.href); return false;">Documentation</a></li>
<li><a href="https://github.com/DerDu/MOC-Framework-Mark-V" title="DerDu"
onclick="window.open(this.href); return false;">GitHub</a></li>
<li><a href="https://github.com/DerDu" title="DerDu" onclick="window.open(this.href); return false;">DerDu</a>
</li>
</ul>
</div>
<div id="Header">
<h1>MOC Framework</h1>
<p>Mark V</p>
</div>
<div id="Navigation">
<ul>
<li>
<a>Documentation</a>
</li>
</ul>
</div>
<div class="Channel">
<h1>Api Documentation</h1>
<div id="ChannelRelease">
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active main"><a href="namespace-MOC.html">MOC<span></span></a>
<ul>
<li class="active main"><a href="namespace-MOC.V.html">V<span></span></a>
<ul>
<li class="active main"><a href="namespace-MOC.V.Component.html">Component<span></span></a>
<ul>
<li class="active main"><a href="namespace-MOC.V.Component.Database.html">Database<span></span></a>
<ul>
<li class="active main"><a href="namespace-MOC.V.Component.Database.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Database.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Database.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="active main"><a href="namespace-MOC.V.Component.Database.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Database.Component.Exception.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Database.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Database.Component.Parameter.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Database.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Database.Vendor.html">Vendor</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Document.html">Document<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Document.Component.html">Component<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Bridge.Repository.html">Repository</a>
</li>
</ul>
</li>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Exception.Repository.html">Repository</a>
</li>
</ul>
</li>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Document.Component.Parameter.Repository.html">Repository</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Document.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Document.Vendor.html">Vendor</a>
</li>
</ul>
</li>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.html">Documentation<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Documentation.Component.html">Component<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Bridge.Repository.html">Repository</a>
</li>
</ul>
</li>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Exception.Repository.html">Repository</a>
</li>
</ul>
</li>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a
href="namespace-MOC.V.Component.Documentation.Component.Parameter.Repository.html">Repository</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Documentation.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Documentation.Vendor.html">Vendor</a>
</li>
</ul>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Router.html">Router<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Exception.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Router.Component.Parameter.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Router.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Router.Vendor.html">Vendor</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Template.html">Template<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Exception.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Component.Template.Component.Parameter.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Component.Template.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Component.Template.Vendor.html">Vendor</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Core.html">Core<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.html">AutoLoader<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Exception.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Component.Parameter.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Vendor.html">Vendor<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Vendor.Multiton.html">Multiton</a>
</li>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Vendor.Universal.html">Universal<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.AutoLoader.Vendor.Universal.NamespaceLoader.html">NamespaceLoader</a>
</li>
</ul></li></ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.html">FileSystem<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Exception.html">Exception<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Exception.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Parameter.html">Parameter<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Component.Parameter.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Vendor.html">Vendor<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.FileSystem.Vendor.Universal.html">Universal</a>
</li>
</ul></li></ul></li>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.html">HttpKernel<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Component.html">Component<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Component.Bridge.html">Bridge<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Component.Bridge.Repository.html">Repository</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Component.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Component.Parameter.html">Parameter</a>
</li>
</ul></li>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Exception.html">Exception</a>
</li>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Vendor.html">Vendor<span></span></a>
<ul>
<li class="main"><a href="namespace-MOC.V.Core.HttpKernel.Vendor.Universal.html">Universal</a>
</li>
</ul></li></ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-PHP.html">PHP</a>
</li>
</ul>
</div>
<hr />
<div id="elements">
<h3>Exceptions</h3>
<ul>
<li class="active"><a href="class-MOC.V.Component.Database.Component.Exception.ComponentException.html">ComponentException</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="text" />
<input type="submit" value="Search" class="Button" />
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-MOC.V.Component.Database.Component.Exception.html" title="Summary of MOC\V\Component\Database\Component\Exception"><span>Namespace</span></a>
</li>
<li>
<a href="class-MOC.V.Component.Database.Component.Exception.ComponentException.html" title="Summary of MOC\V\Component\Database\Component\Exception\ComponentException"><span>Class</span></a>
</li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
<li>
<a href="deprecated.html" title="List of deprecated elements"><span>Deprecated</span></a>
</li>
<li>
<a href="todo.html" title="Todo list"><span>Todo</span></a>
</li>
</ul>
<ul>
<li>
<a href="mark-v-api-documentation.zip" title="Download documentation as ZIP archive"><span>Download</span></a>
</li>
</ul>
</div>
<pre><code><span id="1" class="l"><a class="l" href="#1"> 1: </a><span class="xlang"><?php</span>
</span><span id="2" class="l"><a class="l" href="#2"> 2: </a><span class="php-keyword1">namespace</span> MOC\V\Component\Database\Component\Exception;
</span><span id="3" class="l"><a class="l" href="#3"> 3: </a>
</span><span id="4" class="l"><a class="l" href="#4"> 4: </a><span class="php-keyword1">use</span> MOC\V\Component\Database\Exception\DatabaseException;
</span><span id="5" class="l"><a class="l" href="#5"> 5: </a>
</span><span id="6" class="l"><a class="l" href="#6"> 6: </a><span class="php-comment">/**
</span></span><span id="7" class="l"><a class="l" href="#7"> 7: </a><span class="php-comment"> * Class ComponentException
</span></span><span id="8" class="l"><a class="l" href="#8"> 8: </a><span class="php-comment"> *
</span></span><span id="9" class="l"><a class="l" href="#9"> 9: </a><span class="php-comment"> * @package MOC\V\Component\Database\Component\Exception
</span></span><span id="10" class="l"><a class="l" href="#10">10: </a><span class="php-comment"> */</span>
</span><span id="11" class="l"><a class="l" href="#11">11: </a><span class="php-keyword1">class</span> <a id="ComponentException" href="#ComponentException">ComponentException</a> <span class="php-keyword1">extends</span> DatabaseException
</span><span id="12" class="l"><a class="l" href="#12">12: </a>{
</span><span id="13" class="l"><a class="l" href="#13">13: </a>
</span><span id="14" class="l"><a class="l" href="#14">14: </a> <span class="php-comment">/**
</span></span><span id="15" class="l"><a class="l" href="#15">15: </a><span class="php-comment"> * @param string $Message
</span></span><span id="16" class="l"><a class="l" href="#16">16: </a><span class="php-comment"> * @param int $Code
</span></span><span id="17" class="l"><a class="l" href="#17">17: </a><span class="php-comment"> * @param null $Previous
</span></span><span id="18" class="l"><a class="l" href="#18">18: </a><span class="php-comment"> */</span>
</span><span id="19" class="l"><a class="l" href="#19">19: </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="___construct" href="#___construct">__construct</a>( <span class="php-var">$Message</span> = <span class="php-quote">""</span>, <span class="php-var">$Code</span> = <span class="php-num">0</span>, <span class="php-var">$Previous</span> = <span class="php-keyword1">null</span> )
</span><span id="20" class="l"><a class="l" href="#20">20: </a> {
</span><span id="21" class="l"><a class="l" href="#21">21: </a>
</span><span id="22" class="l"><a class="l" href="#22">22: </a> parent::__construct( <span class="php-var">$Message</span>, <span class="php-var">$Code</span>, <span class="php-var">$Previous</span> );
</span><span id="23" class="l"><a class="l" href="#23">23: </a> }
</span><span id="24" class="l"><a class="l" href="#24">24: </a>}
</span><span id="25" class="l"><a class="l" href="#25">25: </a></span></code></pre>
<div id="footer">
Mark V API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div id="BottomBar">
<ul>
<li>Powered by <a href="http://github.com"
style="background: transparent url('resources/GitHub-Mark-Light-32px.png') no-repeat left center; padding-left: 42px; margin-left: 5px;">GitHub</a>
</li>
<li>
Mark V API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</li>
</ul>
</div>
</body>
</html>
|
KWZwickau/KREDA-Sphere
|
Library/MOC-V/Documentation/source-class-MOC.V.Component.Database.Component.Exception.ComponentException.html
|
HTML
|
agpl-3.0
| 18,407
|
$(document).ready(function () {
var pathArray = window.location.pathname.split( '/' );
var targetname = pathArray[pathArray.length -1];
$('#targetloglist').DataTable({
'paging' : true,
'lengthChange': false,
'searching' : true,
'ordering' : true,
'order' : [[0, "desc"]],
'info' : true,
'autoWidth' : true,
'deferRender' : true,
"language": {
"emptyTable": "No connection history for this target"
},
'ajax' : {
url : '/ajax/target/lastconnections/' + targetname,
dataSrc : 'data'
}
})
})
|
LibrIT/passhport
|
passhweb/app/static/librit/scripts/target_lastconnections.js
|
JavaScript
|
agpl-3.0
| 682
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- 2017-05-23 Tue 19:39 -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Bob Mottram" />
<meta name="description" content="How to use Scuttlebot"
/>
<meta name="keywords" content="freedombone, scuttlebot" />
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #eee;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: visible;
padding-top: 1.2em;
}
pre.src:before {
display: none;
position: absolute;
background-color: white;
top: -10px;
right: 10px;
padding: 3px;
border: 1px solid black;
}
pre.src:hover:before { display: inline;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { width: 90%; }
/*]]>*/-->
</style>
<link rel="stylesheet" type="text/css" href="freedombone.css" />
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012-2017 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="preamble" class="status">
<a name="top" id="top"></a>
</div>
<div id="content">
<div class="org-center">
<div class="figure">
<p><img src="images/logo.png" alt="logo.png" />
</p>
</div>
</div>
<center>
<h1>Scuttlebot</h1>
</center>
<p>
This is a type of <i>followbot</i> for the <a href="https://www.scuttlebutt.nz">Secure Scuttlebutt</a> peer-to-peer messaging system. It's purpose is to follow your friends and keep a log of their messages so that if you are offline for a while when you return you can sync with this system to get all of the missed messages. This avoid the problem common in messaging systems of <i>everyone needing to be online all of the time</i>.
</p>
<p>
The Secure Scuttlebutt system has message encryption, but no protection of the metadata. It lives only on the clearnet. So this system is more about ensuring that messages get correctly delivered and appear in the right chronological order in unreliable situations where network availability may be intermittent, rather than defending against surveillance adversaries.
</p>
<div id="outline-container-org46b8373" class="outline-2">
<h2 id="org46b8373">Installation</h2>
<div class="outline-text-2" id="text-org46b8373">
<p>
Log into your system with:
</p>
<div class="org-src-container">
<pre><code class="src src-bash">ssh myusername@mydomain -p 2222
</code></pre>
</div>
<p>
Using cursor keys, space bar and Enter key select <b>Administrator controls</b> and type in your password.
</p>
<p>
Select <b>Add/Remove Apps</b>. If Vim is selected then you might want to unselect and uninstall it first, then select <b>scuttlebot</b>.
</p>
<p>
Install your favourite Scuttlebutt client onto your laptop, then select <b>Join Pub</b>. ssh into your Freedombone system and go to the <b>Administrator control panel</b> then select <b>App settings</b> followed by <b>scuttlebot</b>. You can then create an invite and paste it into your client.
</p>
</div>
</div>
</div>
<div id="postamble" class="status">
<style type="text/css">
.back-to-top {
position: fixed;
bottom: 2em;
right: 0px;
text-decoration: none;
color: #000000;
background-color: rgba(235, 235, 235, 0.80);
font-size: 12px;
padding: 1em;
display: none;
}
.back-to-top:hover {
background-color: rgba(135, 135, 135, 0.50);
}
</style>
<div class="back-to-top">
<a href="#top">Back to top</a> | <a href="mailto:bob@freedombone.net">E-mail me</a>
</div>
</div>
</body>
</html>
|
bashrc/freedombone
|
website/EN/app_scuttlebot.html
|
HTML
|
agpl-3.0
| 11,724
|
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <cstdlib>
#include "openMVG/sfm/sfm.hpp"
#include "openMVG/system/timer.hpp"
#include "openMVG/cameras/Cameras_Common_command_line_helper.hpp"
#include <openMVG/geometry/box.hpp>
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
/// From 2 given image file-names, find the two corresponding index in the View list
bool computeIndexFromImageNames(
const SfM_Data & sfm_data,
const std::pair<std::string,std::string>& initialPairName,
Pair& initialPairIndex)
{
if (initialPairName.first == initialPairName.second)
{
std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl;
return false;
}
initialPairIndex = Pair(UndefinedIndexT, UndefinedIndexT);
/// List views filenames and find the one that correspond to the user ones:
for (Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
const std::string filename = stlplus::filename_part(v->s_Img_path);
if (filename == initialPairName.first)
{
initialPairIndex.first = v->id_view;
}
else{
if (filename == initialPairName.second)
{
initialPairIndex.second = v->id_view;
}
}
}
return (initialPairIndex.first != UndefinedIndexT &&
initialPairIndex.second != UndefinedIndexT);
}
bool saveIntrinsics(const SfM_Data & data, const std::string & path){
// Check and create path if necessary
if (!stlplus::folder_exists(path) && !stlplus::folder_create(path)) {
std::cerr << "\nCannot create output directory to write 'intrinsics_OpenMVG.txt'" << std::endl;
return false;
}
bool checkIntrinsics = false;
unsigned i = 0;
while (i < data.views.size() && checkIntrinsics == false){
const View & view = *(data.views.at(i));
if(data.IsPoseAndIntrinsicDefined(&view)){
// Get intrinsics from SfM data
const IntrinsicBase * baseintrinsics = data.intrinsics.at(view.id_intrinsic).get();
const Pinhole_Intrinsic_Radial_K3 & intrinsics = *(dynamic_cast<const Pinhole_Intrinsic_Radial_K3*>(baseintrinsics));
const std::vector<double> params = intrinsics.getParams();
if ( !checkIntrinsics ){
// Create the stream and check it is ok
std::ofstream stream(stlplus::create_filespec(path, "intrinsics_OpenMVG.txt").c_str(), std::ios::binary | std::ios::out);
if (!stream.is_open()) return false;
// Write intrinsics_OpenMVG.txt
stream << intrinsics.K() << std::endl;
stream << params[params.size()-3] << " " << params[params.size()-2] << " " << params[params.size()-1] << " " << std::endl;
stream.close();
checkIntrinsics = true;
}
}
i++;
}
return true;
}
bool saveSFM(const SfM_Data & data, const std::string & path){
// Check and create path if necessary
if (!stlplus::folder_exists(path) && !stlplus::folder_create(path)) {
std::cerr << "\nCannot create output sfm directory" << std::endl;
return false;
}
///// Camera files
for (unsigned i = 0; i < data.views.size(); ++i){
const View & view = *(data.views.at(i));
if(data.IsPoseAndIntrinsicDefined(&view)){
// Get current camera intrinsics and extrinsics from SfM data
const IntrinsicBase * baseintrinsics = data.intrinsics.at(view.id_intrinsic).get();
const Pinhole_Intrinsic_Radial_K3 & intrinsics = *(dynamic_cast<const Pinhole_Intrinsic_Radial_K3*>(baseintrinsics));
const geometry::Pose3 & extrinsics = data.poses.at(view.id_pose);
const std::vector<double> params = intrinsics.getParams();
// Pinhole_Intrinsic_Radial_K3 model format
// params[0] = focal
// params[1] = ppx
// params[2] = ppy
// params[3] = K1
// params[4] = K2
// params[5] = K3
// Set filename and path
std::ostringstream filename;
std::string fullname = data.views.at(i)->s_Img_path;
size_t lastindex = fullname.find_last_of(".");
std::string rawname = fullname.substr(0, lastindex);
filename << rawname + "_cam.txt";
// Create the stream and check it is ok
std::ofstream stream(stlplus::create_filespec(path, filename.str()), std::ios::binary | std::ios::out);
if (!stream.is_open()) return false;
// Write current camera file
stream << "1" << std::endl;
stream << intrinsics.w_ << " " << intrinsics.h_ << std::endl;
stream << intrinsics.K() << std::endl;
stream << extrinsics.rotation() << std::endl;
stream << extrinsics.translation() << std::endl;
stream << params[params.size()-3] << " " << params[params.size()-2] << " " << params[params.size()-1] << " " << std::endl;
stream.close();
}
}
///// Structure
{
// Create the stream and check it is ok
std::ofstream stream(stlplus::create_filespec(path, "structure_raw.ply").c_str(), std::ios::binary | std::ios::out);
if (!stream.is_open()) return false;
// Write structure in a ply file
stream << "ply" << std::endl;
stream << "format ascii 1.0" << std::endl;
stream << "element vertex " << data.structure.size() << std::endl;
stream << "property float x" << std::endl;
stream << "property float y" << std::endl;
stream << "property float z" << std::endl;
stream << "end_header" << std::endl;
Landmarks::const_iterator it;
for (it = data.structure.begin(); it != data.structure.end(); ++it) {
const Vec3 & P = it->second.X;
stream << P[0] << " " << P[1] << " " << P[2] << std::endl;
}
stream.close();
}
///// Bounding box
{
// Compute bounding box
Vec3 BBmin(1e10,1e10,1e10), BBmax(-1e10,-1e10,-1e10);
Landmarks::const_iterator it;
for (it = data.structure.begin(); it != data.structure.end(); ++it) {
const Vec3 & P = it->second.X;
for (unsigned i = 0; i < 3; ++i) {
if (P[i] < BBmin[i]) BBmin[i] = P[i];
else if (P[i] > BBmax[i]) BBmax[i] = P[i];
}
}
// Create the stream and check it is ok
std::ofstream stream(stlplus::create_filespec(path, "bbox_raw.txt").c_str(), std::ios::binary | std::ios::out);
if (!stream.is_open()) return false;
// Write bbox in a txt file
stream << BBmin[0] << " " << BBmin[1] << " " << BBmin[2] << "\n"
<< BBmax[0] << " " << BBmax[1] << " " << BBmax[2] << std::endl;
stream.close();
}
return true;
}
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Sequential/Incremental reconstruction" << std::endl
<< " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl
<< std::endl;
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sMatchesDir;
std::string sOutDir = "";
std::pair<std::string,std::string> initialPairString("","");
std::string sIntrinsic_refinement_options = "ADJUST_ALL";
int i_User_camera_model = PINHOLE_CAMERA_RADIAL3;
bool b_use_motion_priors = false;
cmd.add( make_option('i', sSfM_Data_Filename, "input_file") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('a', initialPairString.first, "initialPairA") );
cmd.add( make_option('b', initialPairString.second, "initialPairB") );
cmd.add( make_option('c', i_User_camera_model, "camera_model") );
cmd.add( make_option('f', sIntrinsic_refinement_options, "refineIntrinsics") );
cmd.add( make_switch('P', "prior_usage") );
try {
if (argc == 1) throw std::string("Invalid parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to a SfM_Data scene\n"
<< "[-m|--matchdir] path to the matches that corresponds to the provided SfM_Data scene\n"
<< "[-o|--outdir] path where the output data will be stored\n"
<< "\n[Optional]\n"
<< "[-a|--initialPairA] filename of the first image (without path)\n"
<< "[-b|--initialPairB] filename of the second image (without path)\n"
<< "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n"
<< "\t 1: Pinhole \n"
<< "\t 2: Pinhole radial 1\n"
<< "\t 3: Pinhole radial 3 (default)\n"
<< "\t 4: Pinhole radial 3 + tangential 2\n"
<< "\t 5: Pinhole fisheye\n"
<< "[-f|--refineIntrinsics] Intrinsic parameters refinement option\n"
<< "\t ADJUST_ALL -> refine all existing parameters (default) \n"
<< "\t NONE -> intrinsic parameters are held as constant\n"
<< "\t ADJUST_FOCAL_LENGTH -> refine only the focal length\n"
<< "\t ADJUST_PRINCIPAL_POINT -> refine only the principal point position\n"
<< "\t ADJUST_DISTORTION -> refine only the distortion coefficient(s) (if any)\n"
<< "\t -> NOTE: options can be combined thanks to '|'\n"
<< "\t ADJUST_FOCAL_LENGTH|ADJUST_PRINCIPAL_POINT\n"
<< "\t\t-> refine the focal length & the principal point position\n"
<< "\t ADJUST_FOCAL_LENGTH|ADJUST_DISTORTION\n"
<< "\t\t-> refine the focal length & the distortion coefficient(s) (if any)\n"
<< "\t ADJUST_PRINCIPAL_POINT|ADJUST_DISTORTION\n"
<< "\t\t-> refine the principal point position & the distortion coefficient(s) (if any)\n"
<< "[-P|--prior_usage] Enable usage of motion priors (i.e GPS positions) (default: false)\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (i_User_camera_model < PINHOLE_CAMERA ||
i_User_camera_model > PINHOLE_CAMERA_FISHEYE ) {
std::cerr << "\n Invalid camera type" << std::endl;
return EXIT_FAILURE;
}
const cameras::Intrinsic_Parameter_Type intrinsic_refinement_options =
cameras::StringTo_Intrinsic_Parameter_Type(sIntrinsic_refinement_options);
// Load input SfM_Data scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Init the regions_type from the image describer file (used for image regions extraction)
using namespace openMVG::features;
const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json");
std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer);
if (!regions_type)
{
std::cerr << "Invalid: "
<< sImage_describer << " regions type file." << std::endl;
return EXIT_FAILURE;
}
// Features reading
std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>();
if (!feats_provider->load(sfm_data, sMatchesDir, regions_type)) {
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>();
if // Try to read the two matches file formats
(
!(matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.txt")) ||
matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.bin")))
)
{
std::cerr << std::endl
<< "Invalid matches file." << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
{
if (!stlplus::folder_create(sOutDir))
{
std::cerr << "\nCannot create the output directory" << std::endl;
}
}
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
openMVG::system::Timer timer;
SequentialSfMReconstructionEngine sfmEngine(
sfm_data,
sOutDir,
stlplus::create_filespec(sOutDir, "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Configure reconstruction parameters
sfmEngine.Set_Intrinsics_Refinement_Type(intrinsic_refinement_options);
sfmEngine.SetUnknownCameraType(EINTRINSIC(i_User_camera_model));
b_use_motion_priors = cmd.used('P');
sfmEngine.Set_Use_Motion_Prior(b_use_motion_priors);
// Handle Initial pair parameter
if (!initialPairString.first.empty() && !initialPairString.second.empty())
{
Pair initialPairIndex;
if(!computeIndexFromImageNames(sfm_data, initialPairString, initialPairIndex))
{
std::cerr << "Could not find the initial pairs <" << initialPairString.first
<< ", " << initialPairString.second << ">!\n";
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if (sfmEngine.Process())
{
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "SfMReconstruction_Report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfM_Data to disk." << std::endl;
Save(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "sfm_data", ".bin"),
ESfM_Data(ALL));
Save(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "cloud_and_poses", ".ply"),
ESfM_Data(ALL));
//-- Save sfm files for 3D reconstruction
saveIntrinsics(sfmEngine.Get_SfM_Data(), sOutDir);
saveSFM(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "sfm"));
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
|
rogermm14/rec3D
|
modifications_openmvg/main_IncrementalSfM.cpp
|
C++
|
agpl-3.0
| 14,201
|
DELETE FROM `weenie` WHERE `class_Id` = 32705;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (32705, 'ace32705-aluvianspearman', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (32705, 1, 16) /* ItemType - Creature */
, (32705, 2, 31) /* CreatureType - Human */
, (32705, 6, -1) /* ItemsCapacity */
, (32705, 7, -1) /* ContainersCapacity */
, (32705, 16, 32) /* ItemUseable - Remote */
, (32705, 25, 40) /* Level */
, (32705, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */
, (32705, 95, 8) /* RadarBlipColor - Yellow */
, (32705, 113, 2) /* Gender - Female */
, (32705, 133, 4) /* ShowableOnRadar - ShowAlways */
, (32705, 134, 16) /* PlayerKillerStatus - RubberGlue */
, (32705, 188, 1) /* HeritageGroup - Aluvian */
, (32705, 307, 5) /* DamageRating */
, (32705, 8007, 0) /* PCAPRecordedAutonomousMovement */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (32705, 1, True ) /* Stuck */
, (32705, 19, False) /* Attackable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (32705, 54, 3) /* UseRadius */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (32705, 1, 'Aluvian Spearman') /* Name */
, (32705, 5, 'Soldier') /* Template */
, (32705, 8006, 'BwA9AA0AIukn/glC1C3aQgDXoztP7kEAAAAAQAAAAAD//39/zczMPgAAcEEAAAAAFDvRPw==') /* PCAPRecordedCurrentMotionState */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (32705, 1, 0x0200004E) /* Setup */
, (32705, 2, 0x09000001) /* MotionTable */
, (32705, 3, 0x20000001) /* SoundTable */
, (32705, 6, 0x0400007E) /* PaletteBase */
, (32705, 8, 0x06001036) /* Icon */
, (32705, 9, 0x05001053) /* EyesTexture */
, (32705, 10, 0x0500107E) /* NoseTexture */
, (32705, 11, 0x050010AE) /* MouthTexture */
, (32705, 15, 0x04001FC0) /* HairPalette */
, (32705, 16, 0x040004AE) /* EyesPalette */
, (32705, 17, 0x040002BA) /* SkinPalette */
, (32705, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */
, (32705, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */
, (32705, 8005, 100419) /* PCAPRecordedPhysicsDesc - CSetup, MTable, Children, STable, Position, Movement */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (32705, 8040, 0xE922000D, 37.3076, 109.1681, 0.005, -0.697133, 0, 0, -0.716941) /* PCAPRecordedLocation */
/* @teleloc 0xE922000D [37.307600 109.168100 0.005000] -0.697133 0.000000 0.000000 -0.716941 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (32705, 8000, 0xDBA634D7) /* PCAPRecordedObjectIID */;
INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`)
VALUES (32705, 1, 150, 0, 0) /* Strength */
, (32705, 2, 80, 0, 0) /* Endurance */
, (32705, 3, 60, 0, 0) /* Quickness */
, (32705, 4, 150, 0, 0) /* Coordination */
, (32705, 5, 60, 0, 0) /* Focus */
, (32705, 6, 60, 0, 0) /* Self */;
INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`)
VALUES (32705, 1, 50, 0, 0, 90) /* MaxHealth */
, (32705, 3, 70, 0, 0, 150) /* MaxStamina */
, (32705, 5, 10, 0, 0, 70) /* MaxMana */;
INSERT INTO `weenie_properties_create_list` (`object_Id`, `destination_Type`, `weenie_Class_Id`, `stack_Size`, `palette`, `shade`, `try_To_Bond`)
VALUES (32705, 2, 23698, 1, 0, 0, False) /* Create Spear (23698) for Wield */
, (32705, 2, 32698, 1, 0, 0, False) /* Create Shield of Strathelar (32698) for Wield */;
INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (32705, 67109562, 0, 24)
, (32705, 67109964, 92, 4)
, (32705, 67110003, 72, 8)
, (32705, 67110063, 32, 8)
, (32705, 67110337, 64, 8)
, (32705, 67110337, 40, 24)
, (32705, 67113922, 136, 16)
, (32705, 67113922, 174, 66)
, (32705, 67113922, 80, 12)
, (32705, 67113922, 116, 12)
, (32705, 67113922, 96, 12)
, (32705, 67113922, 168, 6)
, (32705, 67113922, 160, 8)
, (32705, 67113922, 240, 10)
, (32705, 67116984, 24, 8);
INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (32705, 0, 83889072, 83886685)
, (32705, 0, 83889342, 83889386)
, (32705, 0, 83894171, 83894171)
, (32705, 1, 83887064, 83886241)
, (32705, 1, 83894182, 83894182)
, (32705, 2, 83887066, 83887055)
, (32705, 2, 83894182, 83894182)
, (32705, 3, 83894184, 83894184)
, (32705, 4, 83894184, 83894184)
, (32705, 5, 83887064, 83886241)
, (32705, 5, 83894182, 83894182)
, (32705, 6, 83887066, 83887055)
, (32705, 6, 83894182, 83894182)
, (32705, 7, 83894184, 83894184)
, (32705, 8, 83894184, 83894184)
, (32705, 9, 83887070, 83886781)
, (32705, 9, 83887062, 83886686)
, (32705, 9, 83894176, 83894176)
, (32705, 9, 83894178, 83894178)
, (32705, 10, 83887069, 83886782)
, (32705, 10, 83894174, 83894174)
, (32705, 11, 83887067, 83891213)
, (32705, 11, 83894172, 83894172)
, (32705, 12, 83894179, 83894179)
, (32705, 13, 83887069, 83886782)
, (32705, 13, 83894173, 83894173)
, (32705, 13, 83894175, 83894175)
, (32705, 14, 83887067, 83891213)
, (32705, 14, 83894172, 83894172)
, (32705, 14, 83894185, 83894185)
, (32705, 15, 83894179, 83894179)
, (32705, 16, 83886232, 83890685)
, (32705, 16, 83886668, 83890259)
, (32705, 16, 83886837, 83890312)
, (32705, 16, 83886684, 83890340);
INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`)
VALUES (32705, 0, 16788097)
, (32705, 1, 16788083)
, (32705, 2, 16788085)
, (32705, 3, 16788081)
, (32705, 4, 16788088)
, (32705, 5, 16788087)
, (32705, 6, 16788086)
, (32705, 7, 16788082)
, (32705, 8, 16788089)
, (32705, 9, 16788080)
, (32705, 10, 16788090)
, (32705, 11, 16788084)
, (32705, 12, 16788094)
, (32705, 13, 16788099)
, (32705, 14, 16788092)
, (32705, 15, 16788095)
, (32705, 16, 16788093)
, (32705, 21, 16777708)
, (32705, 22, 16777708);
|
ACEmulator/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/Creature/Human/32705 Aluvian Spearman.sql
|
SQL
|
agpl-3.0
| 6,857
|
<?php
/**
* plentymarkets shopware connector
* Copyright © 2013 plentymarkets GmbH
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License, supplemented by an additional
* permission, and of our proprietary license can be found
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "plentymarkets" is a registered trademark of plentymarkets GmbH.
* "shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, titles and interests in the
* above trademarks remain entirely with the trademark owners.
*
* @copyright Copyright (c) 2013, plentymarkets GmbH (http://www.plentymarkets.com)
* @author Daniel Bächtle <daniel.baechtle@plentymarkets.com>
*/
/**
* I am a generated class and am required for communicating with plentymarkets.
*/
class PlentySoapResponse_AddItemAttributeValueSets
{
/**
* @var ArrayOfPlentysoapresponsemessage
*/
public $ResponseMessages;
/**
* @var boolean
*/
public $Success;
}
|
k-30/plentymarkets-shopware-connector
|
Components/Soap/Models/PlentySoapResponse/AddItemAttributeValueSets.php
|
PHP
|
agpl-3.0
| 1,498
|
# -*- coding: utf-8 -*-
import minimongo
import osm
import pymongo.collection
import logging
import re
import stitch
def is_area(way):
return len(way.nodes)\
and way.nodes[0] == way.nodes[-1]\
and ('area' in way.tags and way.tags['area'] == 'yes'\
or (not 'highway' in way.tags\
and not 'barrier' in way.tags))
def get_poly(nodes):
"""Get poly from a list of node ids"""
poly = []
for nodeid in nodes:
for node in osm.Node.collection.find({"_id": nodeid}):
poly.append((node.lon, node.lat))
return poly
def truish(x):
return x == "yes" or x == "true" or x == "1"
def falsish(x):
return x == "no" or x == "false" or x == "0"
class Sink(object):
def processWay(self, way):
poly = get_poly(way.nodes)
if is_area(way):
if Area.connection.planet.multipolygon_ways.find({"_id": way._id}).count():
#logging.debug("Skipping way %d as it belongs to a multipolygon relation", way._id)
return
parea = Area()
parea.id = way._id
parea.outer = poly
parea.tags = way.tags
parea.save()
else:
typ = Way.type_from_tags(way.tags)
if not typ is None:
pway = Way(way._id, poly, typ)
pway.attr_from_tags(way.tags)
pway.save()
else:
pline = Line(way._id, poly, way.tags)
pline.save()
def processNode(self, node):
pass
def processRelation(self, relation):
typ = relation.tags.get('type', None)
if typ == 'multipolygon':
self.processRelationMultiPolygon(relation)
def processRelationMultiPolygon(self, rel):
"""http://wiki.openstreetmap.org/wiki/Relation:multipolygon"""
memids = []
#logging.debug("%d members", len(rel.members))
#logging.debug("relation %d", rel._id)
#if len(rel.members)> 50:
# logging.debug('processRelationMultiPolygon: big rel')
# logging.debug("processing %d members", len(rel.members))
# logging.debug(rel._id)
# logging.debug(rel.tags)
outer_stitch = stitch.Stitch(rel['_id'], True)
inner_stitch = stitch.Stitch(rel['_id'], True)
for m in rel.members:
try:
if m['type'] == 'way':
way = osm.Way.collection.find_one({"_id": m['ref']})
if way:
#logging.debug(way._id)
try:
if m['role'] == 'outer':
outer_stitch.add_id(get_poly(way.nodes), way._id)
elif m['role'] == 'inner':
inner_stitch.add_id(get_poly(way.nodes), way._id)
except RuntimeError,e:
print e, 'way id: ', way['_id'], 'relation id', rel['_id']
memids.append(way['_id'])
try:
Area.connection.planet.multipolygon_ways.insert({"_id": way._id}, safe=True)
except pymongo.errors.DuplicateKeyError:
pass
else:
logging.debug("cound't find way id: %d in multipolygon relation id %d", m['ref'], rel._id)
if m['role'] == 'outer':
outer_stitch.dontClose()
elif m['role'] == 'inner':
inner_stitch.autoClose()
except KeyError:
logging.warn("processRelationMultiPolygon: KeyError")
return
parea = Area()
parea.id = rel._id
try:
parea.outer = outer_stitch.getPolygons()
except RuntimeError, e:
logging.warn("processRelationMultiPolygon exception: rel {0}: {1}".format(rel["_id"], e))
logging.warn(memids)
try:
parea.inner = inner_stitch.getPolygons()
except RuntimeError, e:
logging.warn("processRelationMultiPolygon exception: rel {0}: {1}".format(rel["_id"], e))
logging.warn(memids)
parea.tags = rel.tags
parea.memids = memids
parea.save()
#logging.debug("done")
def processMember(self, member):
pass
class Area(minimongo.Model):
class Meta:
database = 'planet'
# def __init__(self, initial=None, **kw):
# super(Area, self).__init__(initial, **kw)
#
# def __init__(self, id, outer, inner, tags):
# # might not be unique, can't use _id as we save areas from Ways and from Relations
# self.id = id
# self.outer = outer
# self.inner = inner
# self.tags = tags
#
class Line(minimongo.Model):
class Meta:
database = 'planet'
def __init__(self, id, poly, tags):
self._id = id
self.poly = poly
self.tags = tags
class Way(minimongo.Model):
class Meta:
database = 'planet'
HW_MOTORWAY = 0
HW_MOTORWAY_LINK = 1
HW_TRUNK = 2
HW_TRUNK_LINK = 3
HW_PRIMARY = 4
HW_PRIMARY_LINK = 5
HW_SECONDARY = 6
HW_SECONDARY_LINK = 7
HW_TERTIARY = 8
HW_TERTIARY_LINK = 9
HW_LIVING_STREET = 10
HW_PEDESTRIAN = 11
HW_RESIDENTIAL = 12
HW_UNCLASSIFIED = 13
HW_SERVICE = 14
HW_TRACK = 15
HW_BUS_GUIDEWAY = 16
HW_RACEWAY = 17
HW_ROAD = 18
HW_PATH = 19
HW_FOOTWAY = 20
HW_CYCLEWAY = 21
HW_BRIDLEWAY = 22
HW_STEPS = 23
HW_PROPOSED = 24
HW_CONSTRUCTION = 25
def __init__(self, id, poly, typ):
self._id = id
self.poly = poly
self.t = typ
@staticmethod
def type_from_tags(tags):
if tags.has_key('highway'):
try:
val = tags['highway']
attr = 'HW_{0}'.format(val.upper())
hw = getattr(Way, attr)
return hw
except AttributeError:
pass
except UnicodeEncodeError:
pass
return None
def attr_from_tags(self, tags):
self.car_forward = True
self.car_backward = True
self.bike = True
if tags.has_key('oneway'):
ow = tags['oneway']
if truish(ow):
self.car_backward = False
elif ow == "-1":
self.car_backward = True
#elif falsish(ow):
# pass
if tags.has_key('roundabout'):
self.roundabout = True
if not tags.has_key('oneway'):
self.car_backward = False
if self.t == Way.HW_MOTORWAY or self.t == Way.HW_MOTORWAY_LINK and not tags.has_key('oneway'):
self.car_forward = True
self.car_backward = False
if tags.has_key('maxspeed'):
s = tags['maxspeed']
m = re.match('\s*(\d+)\s*(\w*)\s*', s)
if m:
self.speedlimit = float(m.group(1))
if m.group(2) == 'mph':
self.speedlimit *= 1.609344
# TODO: no_thru
if self.t >= Way.HW_PATH:
self.car_forward = False
self.car_backward = False
# bikes
if self.t <= Way.HW_MOTORWAY_LINK\
or self.t == Way.HW_FOOTWAY\
or self.t == Way.HW_STEPS:
self.bike = False
if truish(tags.get('bicycle', False)):
self.bike = True
|
larroy/osmtransform
|
planet/__init__.py
|
Python
|
agpl-3.0
| 7,567
|
<?php
/*
* Fusio
* A web-application to create dynamically RESTful APIs
*
* Copyright (C) 2015-2020 Christoph Kappestein <christoph.kappestein@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Fusio\Impl\Event\Plan\Contract;
use Fusio\Impl\Authorization\UserContext;
use Fusio\Impl\Event\EventAbstract;
use Fusio\Model\Backend\Plan_Contract_Update;
use PSX\Record\RecordInterface;
/**
* UpdatedEvent
*
* @author Christoph Kappestein <christoph.kappestein@gmail.com>
* @license http://www.gnu.org/licenses/agpl-3.0
* @link http://fusio-project.org
*/
class UpdatedEvent extends EventAbstract
{
/**
* @var Plan_Contract_Update
*/
private $contract;
/**
* @var RecordInterface
*/
private $existing;
/**
* @param Plan_Contract_Update $contract
* @param RecordInterface $existing
* @param UserContext $context
*/
public function __construct(Plan_Contract_Update $contract, RecordInterface $existing, UserContext $context)
{
parent::__construct($context);
$this->contract = $contract;
$this->existing = $existing;
}
/**
* @return Plan_Contract_Update
*/
public function getContract(): Plan_Contract_Update
{
return $this->contract;
}
/**
* @return RecordInterface
*/
public function getExisting(): RecordInterface
{
return $this->existing;
}
}
|
k42b3/fusio-impl
|
src/Event/Plan/Contract/UpdatedEvent.php
|
PHP
|
agpl-3.0
| 2,052
|
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation
#
# This file is part of TriSano.
#
# TriSano is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# TriSano is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt.
Then /^the encounter should be struck\-through$/ do
@browser.is_element_present("//table[@id='encounters']//td[@class='struck-through'][text()='#{@encounter.participations_encounter.user.uid}']").should be_true
end
When /^I click the encounter parent link$/ do
parent_event_name = @encounter.parent_event.party.full_name
@browser.click("link=#{parent_event_name}")
wait_for_element_present(:text, "Demographic")
end
When /^I click the "([^\"]*)" link and accept the confirmation$/ do |link|
@browser.click("link=#{link}")
get_confirmation()
wait_for_element_present(:text, "uccessfully")
end
|
JayBoyer/new-trisano
|
webapp/features/enhanced_step_definitions/event_encounter_delete_steps.rb
|
Ruby
|
agpl-3.0
| 1,391
|
// puzzleSEQ: A graphical framework for CLIP / HT-Seq data analysis
// Copyright (C) 2015 Lukáš Bednařík (l.bednarik@gmail.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef PROCESSMAKEFILE_H
#define PROCESSMAKEFILE_H
#include "abstractProcess.h"
class ProcessMakefile : public AbstractProcess
{
Q_OBJECT
public:
ProcessMakefile(const QString & pwd, QObject * parent = 0);
void run();
private:
QStringList _arguments; ///< Compilation parameters
};
#endif // DATAMAKEFILE_H
|
puzzleSEQ/server
|
com/process/src/processMakefile.h
|
C
|
agpl-3.0
| 1,108
|
<?php
/*
* FUPS: Forum user-post scraper. An extensible PHP framework for scraping and
* outputting the posts of a specified user from a specified forum/board
* running supported forum software. Can be run as either a web app or a
* commandline script.
*
* Copyright (C) 2013-2015 Laird Shaw.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* File : common.php.
* Description: Contains defines and functions shared between FUPS scripts.
*/
// These are not defines because we want it to be possible to override them
// in settings.php, and this is also why they occur before the require of
// settings.php.
if (isset($_SERVER['REQUEST_URI'])) {
list($tmp) = explode('?', $_SERVER['REQUEST_URI'], 2);
$fups_url_base = ($tmp[strlen($tmp)-1] == '/' ? $tmp : dirname($tmp));
if ($fups_url_base[strlen($fups_url_base)-1] != '/') {
$fups_url_base .= '/';
}
} else $fups_url_base = '';
$fups_url_homepage = $fups_url_base;
$fups_url_ajax_get_status = $fups_url_base.'ajax-get-status.php';
$fups_url_cancel = $fups_url_base.'cancel.php';
$fups_url_delete_files = $fups_url_base.'delete-files.php';
$fups_url_enter_options = $fups_url_base.'enter-options.php';
$fups_url_notify_email_address = $fups_url_base.'notify-email-address.php';
$fups_url_run = $fups_url_base.'run.php';
require_once __DIR__.'/settings.php';
// Check before doing anything else that FUPS_CMDLINE_PHP_PATH is valid.
// This is especially important under Windows because if we supply an invalid command
// to "start" (generated by make_php_exec_cmd() below), it pops up an invisible
// error message which causes a hang until PHP timeout.
// If not Windows, assume a UNIX-like "which" command is present, otherwise use
// a custom batch file.
$cmd = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? __DIR__.'\\would_run.bat' : 'which').' '.escapeshellarg(FUPS_CMDLINE_PHP_PATH);
exec($cmd, $dummy, $res);
if ($res !== 0) {
exit('Fatal error: The value defined in settings.php for FUPS_CMDLINE_PHP_PATH, "'.FUPS_CMDLINE_PHP_PATH.'", does not appear to be runnable given the current working directory and your path. Exiting.');
}
define('FUPS_DONE_STR' , 'DONE' );
define('FUPS_FAILED_STR' , 'EXITING' );
define('FUPS_CANCELLED_STR' , 'CANCELLED');
define('FUPS_MAX_TOKEN_ATTEMPTS' , 10);
define('FUPS_FALLBACK_FUPS_CHAIN_DURATION', 1200);
function format_html($html) {
$flags = defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : (ENT_COMPAT | ENT_HTML401);
return str_replace("\n", "<br />\n", htmlspecialchars($html, $flags));
}
function make_cancellation_filename($token) {
return FUPS_DATADIR.$token.'.cancel.txt';
}
function make_cookie_filename($token_or_settings_filename) {
return FUPS_DATADIR.sanitise_filename($token_or_settings_filename).'.cookies.txt';
}
function make_errs_filename($token) {
return FUPS_DATADIR.$token.'.errs.txt';
}
function make_errs_admin_filename($token) {
return FUPS_DATADIR.$token.'.errs.admin.txt';
}
function make_output_dirname($token, $for_web = false, $appendix = '') {
return ($for_web ? FUPS_OUTPUTDIR_WEB : FUPS_OUTPUTDIR).$token.$appendix.'/';
}
// $output_dirname must end in a slash
function make_output_filename($output_dirname, $appendix) {
return $output_dirname.'fups.output'.$appendix;
}
function make_output_info_filename($token) {
return FUPS_DATADIR.$token.'.output-info.json';
}
function make_php_exec_cmd($params) {
$args = '';
$prefix = '';
$redirect = '1>/dev/null';
$bg_token = '&';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$prefix = 'start /b ';
$redirect = '1>NUL';
$bg_token = '';
}
if (isset($params['token'])) {
if ($args) $args .= ' ';
$args .= '-t '.escapeshellarg($params['token']);
$errs_fname = make_errs_filename($params['token']);
$redirect = ' 1>>'.$errs_fname.' 2>&1';
}
if (isset($params['settings_filename'])) {
if ($args) $args .= ' ';
$args .= '-i '.escapeshellarg($params['settings_filename']);
}
if (isset($params['output_filename'])) {
if ($args) $args .= ' ';
$args .= '-o '.escapeshellarg($params['output_filename']);
}
if (isset($params['chained']) && $params['chained'] == true) {
if ($args) $args .= ' ';
$args .= '-c';
}
if (isset($params['quiet']) && $params['quiet'] == true) {
if ($args) $args .= ' ';
$args .= '-q';
}
$fups_path = realpath(__DIR__.'/fups.php');
if ($fups_path === false) {
$fups_path = 'fups.php';
}
// Early return possible
return $prefix.FUPS_CMDLINE_PHP_PATH.' -d max_execution_time=0 '.$fups_path.' '.$args.' '.$redirect.' '.$bg_token;
}
function try_run_bg_proc($cmd) {
$res = popen($cmd, 'r');
$ret = $res !== false;
pclose($res);
return $ret;
}
function sanitise_filename($filename) {
$tmp = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $filename);
$sanitised = ($tmp !== null ? $tmp : $filename);
$sanitised2 = str_replace('..', '__', $sanitised);
return $sanitised2;
}
function make_serialize_filename($token_or_settings_filename) {
return FUPS_DATADIR.sanitise_filename($token_or_settings_filename).'.serialize.txt';
}
function make_settings_filename($token) {
return FUPS_DATADIR.$token.'.settings.txt';
}
function make_status_filename($token) {
return FUPS_DATADIR.$token.'.status.txt';
}
function validate_token($token, &$err) {
$err = '';
if (strlen($token) <> 32) {
$err = 'A fatal error occurred: token is malformed (length).';
} else {
$malformed_char = false;
for ($i = 0; $i < strlen($token); $i++) {
$ch = $token[$i];
if (!($ch >= '0' && $ch <= '9') && !($ch >= 'a' && $ch <= 'z')) {
$malformed_char = true;
break;
}
}
if ($malformed_char) {
$err = 'A fatal error occurred: token is malformed (character).';
}
}
return $err == '';
}
function get_failed_done_cancelled($status, &$done, &$cancelled, &$failed) {
$failed = (substr($status, -strlen(FUPS_FAILED_STR)) == FUPS_FAILED_STR);
$done = (substr($status, -strlen(FUPS_DONE_STR)) == FUPS_DONE_STR);
$cancelled = (substr($status, -strlen(FUPS_CANCELLED_STR)) == FUPS_CANCELLED_STR);
}
function show_delete($token, $had_success = false) {
global $fups_url_delete_files;
?>
<p>For your privacy, you might wish to delete from this web server all session and output files associated with this request, especially if you have supplied a login username and password (files that store your username and password details are not publicly visible, but it is wise to delete them anyway).<?php echo FUPS_ROUTINE_DELETION_POLICY; ?></p>
<?php if ($had_success) { ?>
<p>Be sure to do this only <strong>after</strong> you have clicked the above "View result" link, and saved the contents at that page, because they will no longer be accessible after clicking the following link.</p>
<?php } ?>
<p><a href="<?php echo $fups_url_delete_files; ?>?token=<?php echo htmlspecialchars(urlencode($token)); ?>">Delete all files</a> associated with your scrape from my web server - this includes your settings, including your password if you entered one.</p>
<?php
}
function output_update_html($token, $status, $done, $cancelled, $failed, $err, $errs, $errs_admin = false, $ajax = false) {
global $fups_url_cancel, $fups_url_notify_email_address, $fups_url_run;
if ($err) {
?>
<div class="fups_error"><?php echo format_html($err); ?></div>
<?php
return;
}
?>
<h3>Status</h3>
<div id="fups_div_status">
<?php echo htmlspecialchars($status); ?>
</div>
<?php
if ($done) {
$output_info = json_decode(file_get_contents(make_output_info_filename($token)), true);
if ($output_info == null) {
?>
<p>We are sorry, but an unexpected error occurred. The scraping process completed, and the output was created, however we were unable to decode the list of output files. Please feel free to <a href="<?php echo FUPS_CONTACT_URL; ?>">contact me</a> for help with accessing your output files, quoting token "<?php echo $token; ?>".</p>
<?php
} else {
?>
<p>Success! Your posts were retrieved and the output is ready. The following output files are available:</p>
<table style="border-collapse: collapse;">
<tr><th style="border: 1px solid black;">Description</th><th style="border: 1px solid black;">View/download file (opens in a new window)</th><th style="border: 1px solid black;">File size</th></tr>
<?php
foreach ($output_info as $opv) {
?>
<tr><td style="border: 1px solid black;"><?php echo $opv['description']; ?></td><td style="border: 1px solid black;"><a target="_blank" href="<?php echo $opv['url']; ?>">View/download file</a></td><td style="border: 1px solid black;"><?php echo number_format($opv['size']).' bytes'; ?></td></tr>
<?php
}
?>
</table>
<p>If you're wondering what to do next, here are some possible steps:</p>
<ol>
<li>Click on the "View/download file" link beside the HTML file which is sorted according to your preference. This will open up a new window/tab for that file. Switch to this window/tab if necessary, and then save the page, e.g. in Firefox click the "File" menu option and under that click "Save Page As". Select the directory/folder and filename you wish to save this output as (remember this location for the next step).</li>
<li>Start up a word processor such as LibreOffice/OpenOffice or Microsoft Word. Open up in that word processor the HTML file that you saved in the previous step, e.g. click the "File" menu option and under that click "Open", then select the file you saved in the previous step. You are now free to edit the file as you like. You can now (if you so desire) save the file in a friendlier format than HTML, a format such as your editor's default format, e.g. in LibreOffice, click the "File" menu option and then click "Save As" or "Export", and choose the format you desire.</li>
</ol>
<?php
show_delete($token, true);
}
} else if ($cancelled) {
?>
<p>Cancelled by your request.</p>
<?php
show_delete($token, false);
} else if ($failed) {
?>
<p>The script appears to have exited due to an error; the error message is shown below. I have been notified of this error by email; if you would like me to get back to you if/when I have fixed the error, then please enter your email address into the following box and press the button to notify me of it.</p>
<div>
<form method="post" action="<?php echo $fups_url_notify_email_address; ?>">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<label for="email_address.id">Your contact email address:</label><br />
<input type="text" name="email_address" id="email_address.id" /><br />
<label for="message.id">Any message you'd like to include (leaving this blank is fine):</label><br />
<textarea rows="5" cols="80" name="message" id="message.id"></textarea><br />
<input type="submit" value="Notify the FUPS maintainer" />
</form>
</div>
<p>Alternatively, feel free to retry or to <a href="<?php echo FUPS_CONTACT_URL; ?>">contact me</a> manually about this error, quoting your run token of "<?php echo $token; ?>".</p>
<?php
show_delete($token, false);
} else {
$same_status = (isset($_GET['last_status']) && $status == $_GET['last_status']);
?>
<p>
<a href="<?php echo $fups_url_run.'?token='.$token.($same_status ? '&last_status='.htmlspecialchars(urlencode($status)) : '').($ajax ? '&ajax=yes' : ''); ?>"><?php echo ($ajax ? 'Refresh page' : 'Check progress'); ?></a><?php if ($ajax): echo ' (it should not be necessary to click this link unless something goes wrong)'; endif; ?>.
<?php if ($same_status) { ?>
(It appears that progress has halted unexpectedly - the current status is the same as the previous status. It is likely that an error has caused the process to exit before finishing. We are sorry about this failure. In case you want to be sure that progress has indeed halted, you are welcome to click the preceding link, but otherwise, this page will no longer automatically refresh.)
<?php
show_delete($token, false);
} else { ?>
<?php echo (!$ajax ? 'Your browser should automatically refresh this page every '.FUPS_META_REDIRECT_DELAY.' seconds or so to update progress, but if you don\'t want to wait, you\'re welcome to click the link. ' : ''); ?>If you have changed your mind about wanting to run this script through to the end, <strong>please</strong> click this <a href="<?php echo $fups_url_cancel; ?>?token=<?php echo $token.($ajax ? '&ajax=yes' : ''); ?>">cancel</a> link rather than just closing this page - clicking the cancel link will free up the resources (in particular a background process) associated with your task.
<?php } ?>
</p>
<?php
}
$paren_msg_will_be_emailed = '(Unless a mailing error occurs, these will be emailed to me as-is if/when FUPS finishes running, with your token, "'.htmlspecialchars($token).'", included in the email\'s subject)';
$paren_msg_emailed = '(Unless a mailing error occurred, these have been emailed to me as-is, with your token, "'.htmlspecialchars($token).'", included in the email\'s subject)';
if ($errs) {
?>
<h3>Errors</h3>
<p><?php echo ($done || $failed ? $paren_msg_emailed : $paren_msg_will_be_emailed); ?></p>
<?php
$len = strlen($errs);
if ($len > FUPS_MAX_ERROR_FILE_EMAIL_LENGTH) {
$errs = substr($errs, 0, FUPS_MAX_ERROR_FILE_EMAIL_LENGTH);
$trunc_msg = '[Truncated from '.number_format($len).' bytes to '.number_format(FUPS_MAX_ERROR_FILE_EMAIL_LENGTH).' bytes]';
?>
<p><?php echo $trunc_msg; ?></p>
<?php
}
?>
<div class="fups_error">
<?php echo format_html($errs); ?>
</div>
<?php
if ($errs_admin && ($done || $failed)) {
// The toggle_ext_errs() Javascript function below is defined in run.php
?>
<p><a href="javascript:toggle_ext_errs();">Show/hide extended error messages</a> <?php echo $paren_msg_emailed; ?></p>
<div id="id_ext_err" style="display: none;">
<h3>Extended error messages</h3>
<?php
$len = strlen($errs_admin);
if ($len > FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH) {
$errs_admin = substr($errs_admin, 0, FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH);
$trunc_msg = '[Truncated from '.number_format($len).' bytes to '.number_format(FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH).' bytes]';
?>
<p><?php echo $trunc_msg; ?></p>
<?php
}
?>
<div class="fups_error"><?php echo format_html($errs_admin); ?></div>
</div>
<?php }
}
// Early return possible
}
// Utility functions follow
// Helper function for arrays_combos()
function get_arrays_combos_r($arrays, $depth, $combo, &$combos) {
foreach ($arrays[$depth] as $item) {
$combo[$depth] = $item;
if ($depth == count($arrays) - 1) {
$combos[] = $combo;
} else get_arrays_combos_r($arrays, $depth + 1, $combo, $combos);
}
}
// Returns an array of all array combinations generated
// by taking a single element from each of the arrays
// in $arrays.
function arrays_combos($arrays) {
$ret = array();
$combo = array_fill(0, count($arrays), null);
get_arrays_combos_r($arrays, 0, $combo, $ret);
return $ret;
}
|
ezeql/fups
|
common.php
|
PHP
|
agpl-3.0
| 15,661
|
<?php
//*****************************************************************************
// This will allow occurrences of a database table to be deleted.
// The identity of the selected occurrence(s) is passed from the previous screen.
//*****************************************************************************
$table_id = 'mnu_role'; // table id
$screen = 'mnu_role.detail.screen.inc'; // file identifying screen structure
require 'std.delete1.inc'; // activate page controller
?>
|
apmuthu/radicore
|
radicore/menu/mnu_role(del1).php
|
PHP
|
agpl-3.0
| 526
|
<?php
include_once "lib/functions.php";
include_once "colpr-config.php";
if (!isset($_SESSION["usuario"])){
header( 'Location: login.php' );
}else{
$user=autentificado();
// Propuestas en orden cronológico del usuario
$consultaPropuestasUsuario =
'SELECT u.nombre, u.apellidos, p.id, p.titulo, p.comentarios, p.sum_likes, p.positivos, p.negativos, p.sector, p.barrio
FROM users AS u join prog_propuestas AS p ON (`autor_id` = u.id)
WHERE `autor_id` = :usuario_id
ORDER BY p.id;';
$arrayusuario = array(':usuario_id'=>$user['id']);
// Propuestas votadas en orden cronológico del usuario
$consultaVotadasUsuario =
'SELECT u.nombre, u.apellidos, p.id, p.titulo, p.comentarios, p.sum_likes, p.positivos, p.negativos, p.sector, p.barrio
FROM users AS u join prog_propuestas AS p ON (`autor_id` = u.id)
JOIN prog_likes_propuesta AS lp ON (p.id = lp.propuesta_id)
WHERE lp.usuario_id = :usuario_id
ORDER BY p.id DESC;';
/*echo $consultaVotadasUsuario;
return;*/
$datos = array('user'=>$user,
'propusuario'=>listarpreparada($arrayusuario, $consultaPropuestasUsuario),
'votosusuario'=>listarpreparada($arrayusuario, $consultaVotadasUsuario),
'openProps'=>$openProps, // Indica si se pueden hacer nuevas propuestas
'ipr'=>getRealIpAddr(), // La IP desde la que se ha hecho la consulta
'lang'=>$lang); //FIXME: Mirar si el lang se puede leer desde la plantilla twig
/*foreach($datos as $key => $value)
{
echo $key." has the value ***". $value."***<br />\n";
var_dump($value);
}
return;*/
$template = $twig->loadTemplate('perfil.html');
echo $template->render($datos);
}
|
mperezfr/collaborative-documents
|
perfil.php
|
PHP
|
agpl-3.0
| 1,691
|