text,length,is_long_context,metric_val,label_metric
"= v1.Service
{product-author}
{product-version}
:data-uri:
:icons:
:toc: macro
:toc-title:
:toclevels: 2
toc::[]
== Description
[%hardbreaks]
Service is a named abstraction of software service (for example, mysql) consisting of local port (for example 3306) that the proxy listens on, and the selector that determines which pods will answer requests sent through the proxy.
== Object Schema
Expand or mouse-over a field for more information about it.
++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
initializers:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
clusterIP:
externalIPs:
- [string]:
externalName:
externalTrafficPolicy:
healthCheckNodePort:
loadBalancerIP:
loadBalancerSourceRanges:
- [string]:
ports:
- name:
nodePort:
port:
protocol:
targetPort:
selector:
[string]:
sessionAffinity:
type:
status:
loadBalancer:
ingress:
- hostname:
ip:
++++
== Operations
[[Post-api-v1-services]]
=== Create a Service
Create a Service
==== HTTP request
----
POST /api/v1/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X POST \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/api/v1/services <<'EOF'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Service
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Post-api-v1-namespaces-namespace-services]]
=== Create a Service in a namespace
Create a Service
==== HTTP request
----
POST /api/v1/namespaces/$NAMESPACE/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X POST \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services <<'EOF'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Service
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-api-v1-namespaces-namespace-services-name]]
=== Get a Service in a namespace
Read the specified Service
==== HTTP request
----
GET /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
|export|Should this value be exported. Export strips fields that a user can not specify.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-api-v1-services]]
=== Get all Services
List or watch objects of kind Service
==== HTTP request
----
GET /api/v1/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/services
----
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ServiceList
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-api-v1-namespaces-namespace-services]]
=== Get all Services in a namespace
List or watch objects of kind Service
==== HTTP request
----
GET /api/v1/namespaces/$NAMESPACE/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ServiceList
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-api-v1-watch-namespaces-namespace-services-name]]
=== Watch a Service in a namespace
Watch changes to an object of kind Service
==== HTTP request
----
GET /api/v1/watch/namespaces/$NAMESPACE/services/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/watch/namespaces/$NAMESPACE/services/$NAME
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-api-v1-watch-services]]
=== Watch all Services
Watch individual changes to a list of Service
==== HTTP request
----
GET /api/v1/watch/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/watch/services
----
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-api-v1-watch-namespaces-namespace-services]]
=== Watch all Services in a namespace
Watch individual changes to a list of Service
==== HTTP request
----
GET /api/v1/watch/namespaces/$NAMESPACE/services HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/watch/namespaces/$NAMESPACE/services
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Put-api-v1-namespaces-namespace-services-name]]
=== Update a Service in a namespace
Replace the specified Service
==== HTTP request
----
PUT /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME <<'EOF'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Service
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Patch-api-v1-namespaces-namespace-services-name]]
=== Patch a Service in a namespace
Partially update the specified Service
==== HTTP request
----
PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json-patch+json'
{
...
}
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json-patch+json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME <<'EOF'
{
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Patch
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* application/json-patch+json
* application/merge-patch+json
* application/strategic-merge-patch+json
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Delete-api-v1-namespaces-namespace-services-name]]
=== Delete a Service in a namespace
Delete a Service
==== HTTP request
----
DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X DELETE \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Status
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-api-v1-namespaces-namespace-services-name-status]]
=== Get status of a Service in a namespace
Read status of the specified Service
==== HTTP request
----
GET /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Put-api-v1-namespaces-namespace-services-name-status]]
=== Update status of a Service in a namespace
Replace status of the specified Service
==== HTTP request
----
PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status <<'EOF'
{
""kind"": ""Service"",
""apiVersion"": ""v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Service
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Patch-api-v1-namespaces-namespace-services-name-status]]
=== Patch status of a Service in a namespace
Partially update status of the specified Service
==== HTTP request
----
PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json-patch+json'
{
...
}
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json-patch+json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status <<'EOF'
{
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Patch
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Service
|401 Unauthorized|
|===
==== Consumes
* application/json-patch+json
* application/merge-patch+json
* application/strategic-merge-patch+json
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Options-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy OPTIONS request to a Service in a namespace
Connect OPTIONS requests to proxy of Service
==== HTTP request
----
OPTIONS /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X OPTIONS \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Post-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy POST request to a Service in a namespace
Connect POST requests to proxy of Service
==== HTTP request
----
POST /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X POST \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Head-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy HEAD request to a Service in a namespace
Connect HEAD requests to proxy of Service
==== HTTP request
----
HEAD /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X HEAD \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Get-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy GET request to a Service in a namespace
Connect GET requests to proxy of Service
==== HTTP request
----
GET /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Put-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy PUT request to a Service in a namespace
Connect PUT requests to proxy of Service
==== HTTP request
----
PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Patch-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy PATCH request to a Service in a namespace
Connect PATCH requests to proxy of Service
==== HTTP request
----
PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Delete-api-v1-namespaces-namespace-services-name-proxy]]
=== Proxy DELETE request to a Service in a namespace
Connect DELETE requests to proxy of Service
==== HTTP request
----
DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X DELETE \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Options-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy OPTIONS request to a Service in a namespace (with path)
Connect OPTIONS requests to proxy of Service
==== HTTP request
----
OPTIONS /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X OPTIONS \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Post-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy POST request to a Service in a namespace (with path)
Connect POST requests to proxy of Service
==== HTTP request
----
POST /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X POST \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Head-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy HEAD request to a Service in a namespace (with path)
Connect HEAD requests to proxy of Service
==== HTTP request
----
HEAD /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X HEAD \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Get-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy GET request to a Service in a namespace (with path)
Connect GET requests to proxy of Service
==== HTTP request
----
GET /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Put-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy PUT request to a Service in a namespace (with path)
Connect PUT requests to proxy of Service
==== HTTP request
----
PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Patch-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy PATCH request to a Service in a namespace (with path)
Connect PATCH requests to proxy of Service
==== HTTP request
----
PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
[[Delete-api-v1-namespaces-namespace-services-name-proxy-path]]
=== Proxy DELETE request to a Service in a namespace (with path)
Connect DELETE requests to proxy of Service
==== HTTP request
----
DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X DELETE \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the Service
|namespace|object name and auth scope, such as for teams and projects
|path|path to the resource
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|string
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* \\*/*
",16149,True,2942.3405229067885,median
"//Copyright (c) 2010, Charles Strahan
//
//All rights reserved.
//
// Original Showdown Copyright (c) 2007, John Fraser
//
//All rights reserved.
//
// Original Markdown copyright (c) 2004, John Gruber
//
//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 ""Markdown"" nor the names of its contributors may
//be used to endorse or promote products derived from this software
//without specific prior written permission.
//
// This software is provided by the copyright holders and contributors ""as
//is"" and any express or implied warranties, including, but not limited
//to, the implied warranties of merchantability and fitness for a
//particular purpose are disclaimed. In no event shall the copyright owner
//or contributors be liable for any direct, indirect, incidental, special,
//exemplary, or consequential damages (including, but not limited to,
// procurement of substitute goods or services; loss of use, data, or
// profits; or business interruption) however caused and on any theory of
//liability, whether in contract, strict liability, or tort (including
// negligence or otherwise) arising in any way out of the use of this
//software, even if advised of the possibility of such damage.
//
// Showdown.as -- An ActionScript port of showdown.js
//
// Copyright (c) 2010 Charles Strahan.
//
// Original Showdown Copyright (c) 2007 John Fraser.
//
//
// Original Markdown Copyright (c) 2004-2005 John Gruber
//
//
// Redistributable under a BSD-style open source license.
// See license.txt for more information.
//
// Usage:
//
// var text = ""Markdown *rocks*."";
// var html = Showdown.makeHtml(text);
//
package {
public class Showdown
{
// Global hashes, used by various utility routines
private static var g_urls:Array;
private static var g_titles:Array;
private static var g_html_blocks:Array;
private static var g_extensions:Array = new Array();
;
// Used to track when we're inside an ordered or unordered list
// (see _ProcessListItems() for details):
private static var g_list_level:Number = 0;
public static function addExtension(extension):void
{
if (g_extensions.indexOf(extension) == -1)
g_extensions.push(extension);
}
public static function makeHtml(text:String):String
{
// Clear the global hashes. If we don't clear these, you get conflicts
// from other articles when generating a page which contains more than
// one article (e.g. an index page that shows the N most recent
// articles):
g_urls = new Array();
g_titles = new Array();
g_html_blocks = new Array();
// attacklab: Replace ~ with ~T
// This lets us use tilde as an escape char to avoid md5 hashes
// The choice of character is arbitray; anything that isn't
// magic in Markdown will work.
text = text.replace(/~/g,""~T"");
// attacklab: Replace $ with ~D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\\$/g,""~D"");
// Standardize line endings
text = text.replace(/\\r\\n/g,""\\n""); // DOS to Unix
text = text.replace(/\\r/g,""\\n""); // Mac to Unix
// Make sure text begins and ends with a couple of newlines:
text = ""\\n\\n"" + text + ""\\n\\n"";
// Convert all tabs to spaces.
text = _Detab(text);
// Strip any lines consisting only of spaces and tabs.
// This makes subsequent regexen easier to write, because we can
// match consecutive blank lines with /\\n+/ instead of something
// contorted like /[ \\t]*\\n+/ .
text = text.replace(/^[ \\t]+$/mg,"""");
// Execute all extensions on processed text.
for (var i=0; i? // url = $2
[ \\t]*
\\n? // maybe one newline
[ \\t]*
(?:
(\\n*) // any lines skipped = $3 attacklab: lookbehind removed
[""(]
(.+?) // title = $4
["")]
[ \\t]*
)? // title is optional
(?:\\n+|$)
/gm,
function(){...});
*/
var text = text.replace(/^[ ]{0,3}\\[(.+)\\]:[ \\t]*\\n?[ \\t]*(\\S+?)>?[ \\t]*\\n?[ \\t]*(?:(\\n*)[""(](.+?)["")][ \\t]*)?(?:\\n+|\\Z)/gm,
function (wholeMatch,m1,m2,m3,m4) {
m1 = m1.toLowerCase();
g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
if (m3) {
// Oops, found blank lines, so it's not a title.
// Put back the parenthetical statement we stole.
return m3+m4;
} else if (m4) {
g_titles[m1] = m4.replace(/""/g,""""");
}
// Completely remove the definition from the text
return """";
}
);
return text;
}
private static function _HashHTMLBlocks(text) {
// attacklab: Double up blank lines to reduce lookaround
text = text.replace(/\\n/g,""\\n\\n"");
// Hashify HTML blocks:
// We only want to do this for block-level HTML tags, such as headers,
// lists, and tables. That's because we still want to wrap
s around
// ""paragraphs"" that are wrapped in non-block-level tags, such as anchors,
// phrase emphasis, and spans. The list of tags we're looking for is
// hard-coded:
var block_tags_a = ""p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del""
var block_tags_b = ""p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math""
// First, look for nested blocks, e.g.:
//
//
// tags for inner block must be indented.
//
//
//
// The outermost tags must start at the left margin for this to match, and
// the inner nested divs must be indented.
// We need to do this before the next, more liberal match, because the next
// match will start at the first `
` and stop at the first `
`.
// attacklab: This regex can be expensive when it fails.
/*
var text = text.replace(/
( // save in $1
^ // start of line (with /m)
<($block_tags_a) // start tag = $2
\\b // word break
// attacklab: hack around khtml/pcre bug...
[^\\r]*?\\n // any number of lines, minimally matching
\\2> // the matching end tag
[ \\t]* // trailing spaces/tabs
(?=\\n+) // followed by a newline
) // attacklab: there are sentinel newlines at end of document
/gm,function(){...}};
*/
text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\\b[^\\r]*?\\n<\\/\\2>[ \\t]*(?=\\n+))/gm,hashElement);
//
// Now match more liberally, simply from `\\n` to `\\n`
//
/*
var text = text.replace(/
( // save in $1
^ // start of line (with /m)
<($block_tags_b) // start tag = $2
\\b // word break
// attacklab: hack around khtml/pcre bug...
[^\\r]*? // any number of lines, minimally matching
.*\\2> // the matching end tag
[ \\t]* // trailing spaces/tabs
(?=\\n+) // followed by a newline
) // attacklab: there are sentinel newlines at end of document
/gm,function(){...}};
*/
text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\\b[^\\r]*?.*<\\/\\2>[ \\t]*(?=\\n+)\\n)/gm,hashElement);
// Special case just for . It was easier to make a special case than
// to make the other regex more complicated.
/*
text = text.replace(/
( // save in $1
\\n\\n // Starting after a blank line
[ ]{0,3}
(<(hr) // start tag = $2
\\b // word break
([^<>])*? //
\\/?>) // the matching end tag
[ \\t]*
(?=\\n{2,}) // followed by a blank line
)
/g,hashElement);
*/
text = text.replace(/(\\n[ ]{0,3}(<(hr)\\b([^<>])*?\\/?>)[ \\t]*(?=\\n{2,}))/g,hashElement);
// Special case for standalone HTML comments:
/*
text = text.replace(/
( // save in $1
\\n\\n // Starting after a blank line
[ ]{0,3} // attacklab: g_tab_width - 1
[ \\t]*
(?=\\n{2,}) // followed by a blank line
)
/g,hashElement);
*/
text = text.replace(/(\\n\\n[ ]{0,3}[ \\t]*(?=\\n{2,}))/g,hashElement);
// PHP and ASP-style processor instructions (...?> and <%...%>)
/*
text = text.replace(/
(?:
\\n\\n // Starting after a blank line
)
( // save in $1
[ ]{0,3} // attacklab: g_tab_width - 1
(?:
<([?%]) // $2
[^\\r]*?
\\2>
)
[ \\t]*
(?=\\n{2,}) // followed by a blank line
)
/g,hashElement);
*/
text = text.replace(/(?:\\n\\n)([ ]{0,3}(?:<([?%])[^\\r]*?\\2>)[ \\t]*(?=\\n{2,}))/g,hashElement);
// attacklab: Undo double lines (see comment at top of this function)
text = text.replace(/\\n\\n/g,""\\n"");
return text;
}
private static function hashElement(wholeMatch,m1,m2,m3,m4) {
var blockText = m1;
// Undo double lines
blockText = blockText.replace(/\\n\\n/g,""\\n"");
blockText = blockText.replace(/^\\n/,"""");
// strip trailing blank lines
blockText = blockText.replace(/\\n+$/g,"""");
// Replace the element text with a marker (""~KxK"" where x is its key)
blockText = ""\\n\\n~K"" + (g_html_blocks.push(blockText)-1) + ""K\\n\\n"";
return blockText;
};
private static function _RunBlockGamut(text) {
//
// These are all the transformations that form block-level
// tags like paragraphs, headers, and list items.
//
text = _DoHeaders(text);
// Do Horizontal Rules:
var key = hashBlock("""");
text = text.replace(/^[ ]{0,2}([ ]?\\*[ ]?){3,}[ \\t]*$/gm,key);
text = text.replace(/^[ ]{0,2}([ ]?\\-[ ]?){3,}[ \\t]*$/gm,key);
text = text.replace(/^[ ]{0,2}([ ]?\\_[ ]?){3,}[ \\t]*$/gm,key);
text = _DoLists(text);
text = _DoCodeBlocks(text);
text = _DoBlockQuotes(text);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
//
"");});
text = text.replace(/^(.+)[ \\t]*\\n-+[ \\t]*\\n+/gm,
function(matchFound,m1){return hashBlock(""
"" + _RunSpanGamut(m1) + ""
"");});
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
/*
text = text.replace(/
^(\\#{1,6}) // $1 = string of #'s
[ \\t]*
(.+?) // $2 = Header text
[ \\t]*
\\#* // optional closing #'s (not counted)
\\n+
/gm, function() {...});
*/
text = text.replace(/^(\\#{1,6})[ \\t]*(.+?)[ \\t]*\\#*\\n+/gm,
function(wholeMatch,m1,m2) {
var h_level = m1.length;
return hashBlock("""" + _RunSpanGamut(m2) + """");
});
return text;
}
private static function _DoLists(text) {
//
// Form HTML ordered (numbered) and unordered (bulleted) lists.
//
// attacklab: add sentinel to hack around khtml/safari bug:
// http://bugs.webkit.org/show_bug.cgi?id=11231
text += ""~0"";
// Re-usable pattern to match any entirel ul or ol list:
/*
var whole_list = /
( // $1 = whole list
( // $2
[ ]{0,3} // attacklab: g_tab_width - 1
([*+-]|\\d+[.]) // $3 = first list item marker
[ \\t]+
)
[^\\r]+?
( // $4
~0 // sentinel for workaround; should be $
|
\\n{2,}
(?=\\S)
(?! // Negative lookahead for another list item marker
[ \\t]*
(?:[*+-]|\\d+[.])[ \\t]+
)
)
)/g
*/
var whole_list = /^(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm;
if (g_list_level) {
text = text.replace(whole_list,function(wholeMatch,m1,m2) {
var list = m1;
var list_type = (m2.search(/[*+-]/g)>-1) ? ""ul"" : ""ol"";
// Turn double returns into triple returns, so that we can make a
// paragraph for the last item in a list, if necessary:
list = list.replace(/\\n{2,}/g,""\\n\\n\\n"");;
var result = _ProcessListItems(list);
// Trim any trailing whitespace, to put the closing `$list_type>`
// up on the preceding line, to get it past the current stupid
// HTML block parser. This is a hack to work around the terrible
// hack that is the HTML block parser.
result = result.replace(/\\s+$/,"""");
result = ""<""+list_type+"">"" + result + """"+list_type+"">\\n"";
return result;
});
} else {
whole_list = /(\\n\\n|^\\n?)(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/g;
text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
var runup = m1;
var list = m2;
var list_type = (m3.search(/[*+-]/g)>-1) ? ""ul"" : ""ol"";
// Turn double returns into triple returns, so that we can make a
// paragraph for the last item in a list, if necessary:
var list = list.replace(/\\n{2,}/g,""\\n\\n\\n"");;
var result = _ProcessListItems(list);
result = runup + ""<""+list_type+"">\\n"" + result + """"+list_type+"">\\n"";
return result;
});
}
// attacklab: strip sentinel
text = text.replace(/~0/,"""");
return text;
}
private static function _ProcessListItems(list_str) {
//
// Process the contents of a single ordered or unordered list, splitting it
// into individual list items.
//
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. ""1."" or ""a."".
g_list_level++;
// trim trailing blank lines:
list_str = list_str.replace(/\\n{2,}$/,""\\n"");
// attacklab: add sentinel to emulate \\z
list_str += ""~0"";
/*
list_str = list_str.replace(/
(\\n)? // leading line = $1
(^[ \\t]*) // leading whitespace = $2
([*+-]|\\d+[.]) [ \\t]+ // list marker = $3
([^\\r]+? // list item text = $4
(\\n{1,2}))
(?= \\n* (~0 | \\2 ([*+-]|\\d+[.]) [ \\t]+))
/gm, function(){...});
*/
list_str = list_str.replace(/(\\n)?(^[ \\t]*)([*+-]|\\d+[.])[ \\t]+([^\\r]+?(\\n{1,2}))(?=\\n*(~0|\\2([*+-]|\\d+[.])[ \\t]+))/gm,
function(wholeMatch,m1,m2,m3,m4){
var item = m4;
var leading_line = m1;
var leading_space = m2;
if (leading_line || (item.search(/\\n{2,}/)>-1)) {
item = _RunBlockGamut(_Outdent(item));
}
else {
// Recursion for sub-lists:
item = _DoLists(_Outdent(item));
item = item.replace(/\\n$/,""""); // chomp(item)
item = _RunSpanGamut(item);
}
return ""
` blocks.
//
/*
text = text.replace(text,
/(?:\\n\\n|^)
( // $1 = the code block -- one or more lines, starting with a space/tab
(?:
(?:[ ]{4}|\\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
.*\\n+
)+
)
(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0)) // attacklab: g_tab_width
/g,function(){...});
*/
// attacklab: sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug
text += ""~0"";
text = text.replace(/(?:\\n\\n|^)((?:(?:[ ]{4}|\\t).*\\n+)+)(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0))/g,
function(wholeMatch,m1,m2) {
var codeblock = m1;
var nextChar = m2;
codeblock = _EncodeCode( _Outdent(codeblock));
codeblock = _Detab(codeblock);
codeblock = codeblock.replace(/^\\n+/g,""""); // trim leading newlines
codeblock = codeblock.replace(/\\n+$/g,""""); // trim trailing whitespace
codeblock = ""
"" + codeblock + ""\\n
"";
return hashBlock(codeblock) + nextChar;
}
);
// attacklab: strip sentinel
text = text.replace(/~0/,"""");
return text;
}
private static function hashBlock(text) {
text = text.replace(/(^\\n+|\\n+$)/g,"""");
return ""\\n\\n~K"" + (g_html_blocks.push(text)-1) + ""K\\n\\n"";
}
private static function _DoCodeSpans(text:String) {
//
// * Backtick quotes are used for spans.
//
// * You can use multiple backticks as the delimiters if you want to
// include literal backticks in the code span. So, this input:
//
// Just type ``foo `bar` baz`` at the prompt.
//
// Will translate to:
//
//
Just type foo `bar` baz at the prompt.
//
// There's no arbitrary limit to the number of backticks you
// can use as delimters. If you need three consecutive backticks
// in your code, use four for delimiters, etc.
//
// * You can use spaces to get literal backticks at the edges:
//
// ... type `` `bar` `` ...
//
// Turns to:
//
// ... type `bar` ...
//
/*
text = text.replace(/
(^|[^\\\\]) // Character before opening ` can't be a backslash
(`+) // $2 = Opening run of `
( // $3 = The code block
[^\\r]*?
[^`] // attacklab: work around lack of lookbehind
)
\\2 // Matching closer
(?!`)
/gm, function(){...});
*/
text = text.replace(/(^|[^\\\\])(`+)([^\\r]*?[^`])\\2(?!`)/gm,
function(wholeMatch,m1,m2,m3,m4) {
var c = m3;
c = c.replace(/^([ \\t]*)/g,""""); // leading whitespace
c = c.replace(/[ \\t]*$/g,""""); // trailing whitespace
c = _EncodeCode(c);
return m1+""""+c+"""";
});
return text;
}
private static function _EncodeCode(text:String) {
//
// Encode/escape certain characters inside Markdown code runs.
// The point is that in code, these characters are literals,
// and lose their special Markdown meanings.
//
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text.replace(/&/g,""&"");
// Do the angle bracket song and dance:
text = text.replace(//g,"">"");
// Now, escape characters that are magic in Markdown:
text = escapeCharacters(text,""\\*_{}[]\\\\"",false);
// jj the line above breaks this:
//---
//* Item
// 1. Subitem
// special char: *
//---
return text;
}
private static function _DoItalicsAndBold(text:String) {
// must go first:
text = text.replace(/(\\*\\*|__)(?=\\S)([^\\r]*?\\S[*_]*)\\1/g,
""$2"");
text = text.replace(/(\\*|_)(?=\\S)([^\\r]*?\\S)\\1/g,
""$2"");
return text;
}
private static function _DoBlockQuotes(text:String) {
/*
text = text.replace(/
( // Wrap whole match in $1
(
^[ \\t]*>[ \\t]? // '>' at the start of a line
.+\\n // rest of the first line
(.+\\n)* // subsequent consecutive lines
\\n* // blanks
)+
)
/gm, function(){...});
*/
text = text.replace(/((^[ \\t]*>[ \\t]?.+\\n(.+\\n)*\\n*)+)/gm,
function(wholeMatch,m1) {
var bq = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
// ""----------bug"".replace(/^-/g,"""") == ""bug""
bq = bq.replace(/^[ \\t]*>[ \\t]?/gm,""~0""); // trim one level of quoting
// attacklab: clean up hack
bq = bq.replace(/~0/g,"""");
bq = bq.replace(/^[ \\t]+$/gm,""""); // trim whitespace-only lines
bq = _RunBlockGamut(bq); // recurse
bq = bq.replace(/(^|\\n)/g,""$1 "");
// These leading spaces screw with
content, so we need to fix that:
bq = bq.replace(
/(\\s*
[^\\r]+?<\\/pre>)/gm,
function(wholeMatch,m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
pre = pre.replace(/^ /mg,""~0"");
pre = pre.replace(/~0/g,"""");
return pre;
});
return hashBlock(""
\\n"" + bq + ""\\n
"");
});
return text;
}
private static function _FormParagraphs(text:String) {
//
// Params:
// $text - string to process with html
tags
//
// Strip leading and trailing lines:
text = text.replace(/^\\n+/g,"""");
text = text.replace(/\\n+$/g,"""");
var grafs:Array = text.split(/\\n{2,}/g);
var grafsOut:Array = new Array();
//
// Wrap
tags.
//
var end = grafs.length;
for (var i=0; i= 0) {
grafsOut.push(str);
}
else if (str.search(/\\S/) >= 0) {
str = _RunSpanGamut(str);
str = str.replace(/^([ \\t]*)/g,""
"");
str += ""
""
grafsOut.push(str);
}
}
//
// Unhashify HTML blocks
//
end = grafsOut.length;
for (var i=0; i= 0) {
var firstGroup:String = (/~K(\\d+)K/).exec(grafsOut[i])[1];
var blockText = g_html_blocks[firstGroup];
blockText = blockText.replace(/\\$/g,""$$$$""); // Escape any dollar signs
grafsOut[i] = grafsOut[i].replace(/~K\\d+K/,blockText);
}
}
return grafsOut.join(""\\n\\n"");
}
private static function _EncodeAmpsAndAngles(text:String) {
// Smart processing for ampersands and angle brackets that need to be encoded.
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/g,""&"");
// Encode naked <'s
text = text.replace(/<(?![a-z\\/?\\$!])/gi,""<"");
return text;
}
private static function _EncodeBackslashEscapes(text:String) {
//
// Parameter: String.
// Returns: The string, with after processing the following backslash
// escape sequences.
//
// attacklab: The polite way to do this is with the new
// escapeCharacters() function:
//
// text = escapeCharacters(text,""\\\\"",true);
// text = escapeCharacters(text,""`*_{}[]()>#+-.!"",true);
//
// ...but we're sidestepping its use of the (slow) RegExp constructor
// as an optimization for Firefox. This function gets called a LOT.
text = text.replace(/\\\\(\\\\)/g,escapeCharacters_callback);
text = text.replace(/\\\\([`*_{}\\[\\]()>#+-.!])/g,escapeCharacters_callback);
return text;
}
private static function _DoAutoLinks(text:String) {
text = text.replace(/<((https?|ftp|dict):[^'"">\\s]+)>/gi,""$1"");
// Email addresses:
/*
text = text.replace(/
<
(?:mailto:)?
(
[-.\\w]+
\\@
[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+
)
>
/gi, _DoAutoLinks_callback());
*/
text = text.replace(/<(?:mailto:)?([-.\\w]+\\@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>/gi,
function(wholeMatch,m1) {
return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
}
);
return text;
}
private static function _EncodeEmailAddress(addr:String) {
//
// Input: an email address, e.g. ""foo@example.com""
//
// Output: the email address as a mailto link, with each character
// of the address encoded as either a decimal or hex entity, in
// the hopes of foiling most address harvesting spam bots. E.g.:
//
// foo
// @example.com
//
// Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
// mailing list:
//
// attacklab: why can't javascript speak hex?
function char2hex(ch:String) {
var hexDigits = '0123456789ABCDEF';
var dec = ch.charCodeAt(0);
return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
}
var encode = [
function(ch){return """"+ch.charCodeAt(0)+"";"";},
function(ch){return """"+char2hex(ch)+"";"";},
function(ch){return ch;}
];
addr = ""mailto:"" + addr;
addr = addr.replace(/./g, function(ch) {
if (ch == ""@"") {
// this *must* be encoded. I insist.
ch = encode[Math.floor(Math.random()*2)](ch);
} else if (ch !="":"") {
// leave ':' alone (to spot mailto: later)
var r = Math.random();
// roughly 10% raw, 45% hex, 45% dec
ch = (
r > .9 ? encode[2](ch) :
r > .45 ? encode[1](ch) :
encode[0](ch)
);
}
return ch;
});
addr = """" + addr + """";
addr = addr.replace(/"">.+:/g,""\\"">""); // strip the mailto: from the visible part
return addr;
}
private static function _UnescapeSpecialChars(text:String) {
//
// Swap back in all the special characters we've hidden.
//
text = text.replace(/~E(\\d+)E/g,
function(wholeMatch,m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
}
);
return text;
}
private static function _Outdent(text:String) {
//
// Remove one level of line-leading tabs or spaces
//
// attacklab: hack around Konqueror 3.5.4 bug:
// ""----------bug"".replace(/^-/g,"""") == ""bug""
text = text.replace(/^(\\t|[ ]{1,4})/gm,""~0""); // attacklab: g_tab_width
// attacklab: clean up hack
text = text.replace(/~0/g,"""")
return text;
}
private static function _Detab(text:String) {
// attacklab: Detab's completely rewritten for speed.
// In perl we could fix it by anchoring the regexp with \\G.
// In javascript we're less fortunate.
// expand first n-1 tabs
text = text.replace(/\\t(?=\\t)/g,"" ""); // attacklab: g_tab_width
// replace the nth with two sentinels
text = text.replace(/\\t/g,""~A~B"");
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/~B(.+?)~A/g,
function(wholeMatch,m1,m2) {
var leadingText = m1;
var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
// there *must* be a better way to do this:
for (var i=0; i;
private var trackHighlightButtons: Vector.;
private var markerComponents: Vector.;
private var focusedThumbIndex: uint = 0;
private var animatedThumb: SliderThumb;
//-------------------------------------------------------------------------------------------------
public function MultiThumbSliderBase()
{
super();
thumbs = new Vector.();
trackHighlightButtons = new Vector.();
markerComponents = new Vector.();
if(!newMinimum)
minimum = DEFAULT_MINIMUM;
if(!newMaximum)
maximum = DEFAULT_MAXIMUM;
this.addEventListener( FlexEvent.CREATION_COMPLETE, creationCompleteHandler );
}
//-------------------------------------------------------------------------------------------------
//------------------------------ PROPERTIES - START -------------------------------------------------------------------
private var minimumChanged: Boolean = false;
private var newMinimum: Number;
public function get minimum(): Number
{
if(minimumChanged)
return newMinimum;
else if(valueBasedLayout)
return valueBasedLayout.minimum;
else
return 0;
}
public function set minimum(value: Number): void
{
if(value != minimum)
{
newMinimum = value;
minimumChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var maximumChanged: Boolean = false;
private var newMaximum: Number;
public function get maximum(): Number
{
if(maximumChanged)
return newMaximum;
if(valueBasedLayout)
return valueBasedLayout.maximum;
else
return 0;
}
public function set maximum(value: Number): void
{
if(value != maximum)
{
newMaximum = value;
maximumChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var snapIntervalChanged: Boolean = false;
private var _snapInterval: Number = DEFAULT_SNAP_INTERVAL;
public function get snapInterval(): Number
{
return _snapInterval;
}
public function set snapInterval(value: Number): void
{
if(value != _snapInterval)
{
_snapInterval = value;
snapIntervalChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var dataProviderChanged:Boolean;
private var _dataProvider: IList = new ArrayCollection();
[Bindable(""dataProviderChanged"")]
[Inspectable(category=""Data"")]
public function get dataProvider():IList
{
return _dataProvider;
}
public function set dataProvider( value:IList ):void
{
if( value != _dataProvider )
{
if (dataProvider)
dataProvider.removeEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler );
_dataProvider = value;
reactToDataProviderUpdate();
if (dataProvider)
dataProvider.addEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler, false, 0, true );
dispatchEvent(new Event(""dataProviderChanged""));
dataProviderChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var markersChanged: Boolean = false;
private var _markers: Array = new Array();
// Contains the values for which ""markers"" will be created on the track.
// These will just be labels on the track, indicating the value at that point.
// These markers will not be movable and their values will not be part of the ""values"" array.
public function get markers(): Array
{
return _markers;
}
public function set markers(value: Array): void
{
if( value != _markers )
{
_markers = value;
markersChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var allowOverlapChanged: Boolean = false;
private var _allowOverlap: Boolean = DEFAULT_ALLOW_OVERLAP;
public function get allowOverlap(): Boolean
{
return _allowOverlap;
}
public function set allowOverlap(value: Boolean): void
{
if(value != _allowOverlap)
{
_allowOverlap = value;
allowOverlapChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private var _allowDuplicateValues: Boolean = true;
public function get allowDuplicateValues(): Boolean
{
return _allowDuplicateValues;
}
public function set allowDuplicateValues(value: Boolean): void
{
if(value != _allowDuplicateValues)
{
_allowDuplicateValues = value;
if( ! _allowDuplicateValues )
removeDataProviderDuplicateValues();
}
}
//-------------------------------------------------------------------------------------------------
private var accentColorsChanged: Boolean = false;
private var _accentColors:Array;
[Bindable]
public function get accentColors(): Array
{
return _accentColors;
}
public function set accentColors(colors:Array):void
{
_accentColors = colors;
accentColorsChanged = true;
invalidateProperties();
}
//-------------------------------------------------------------------------------------------------
private var showTrackHighlightChanged: Boolean = false;
private var _showTrackHighlight:Boolean = true;
[Bindable]
public function get showTrackHighlight():Boolean
{
return _showTrackHighlight;
}
public function set showTrackHighlight(show:Boolean):void
{
_showTrackHighlight = show;
showTrackHighlightChanged = true;
invalidateProperties();
}
//-------------------------------------------------------------------------------------------------
private var _defaultTrackHighlightLabel: String = ""Label"";
public function get defaultTrackHighlightLabel():String
{
return _defaultTrackHighlightLabel;
}
public function set defaultTrackHighlightLabel( value: String ):void
{
_defaultTrackHighlightLabel = value;
}
//-------------------------------------------------------------------------------------------------
//----------------------------------
// valueField
//----------------------------------
/**
* @private
*/
private var _valueField:String = ""value"";
/**
* @private
*/
private var valueFieldChanged:Boolean;
[Inspectable(category=""Data"", defaultValue=""value"")]
/**
* The name of the field in the data provider items to display
* as the value.
*
* If valueField is set to an empty string (""""), no field will
* be considered on the data provider to represent value.
*
* @default ""value""
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get valueField():String
{
return _valueField;
}
/**
* @private
*/
public function set valueField(value:String):void
{
if (value == _valueField)
return;
_valueField = value;
valueFieldChanged = true;
invalidateProperties();
}
//-------------------------------------------------------------------------------------------------
//----------------------------------
// fixedValueField
//----------------------------------
/**
* @private
*/
private var _fixedValueField:String = ""fixedValue"";
/**
* @private
*/
private var fixedValueFieldChanged:Boolean;
[Inspectable(category=""Data"", defaultValue=""fixedValue"")]
/**
* The name of the field in the data provider items to display
* as the fixedValue.
*
* If fixedValueField is set to an empty string (""""), no field will
* be considered on the data provider to represent fixedValue.
*
* @default ""fixedValue""
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get fixedValueField():String
{
return _fixedValueField;
}
/**
* @private
*/
public function set fixedValueField(value:String):void
{
if (value == _fixedValueField)
return;
_fixedValueField = value;
fixedValueFieldChanged = true;
invalidateProperties();
}
//-------------------------------------------------------------------------------------------------
//----------------------------------
// labelField
//----------------------------------
/**
* @private
*/
private var _labelField:String = ""label"";
/**
* @private
*/
private var labelFieldChanged:Boolean;
[Inspectable(category=""Data"", defaultValue=""label"")]
/**
* The name of the field in the data provider items to display
* as the label.
*
* If labelField is set to an empty string (""""), no field will
* be considered on the data provider to represent label.
*
* @default ""label""
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get labelField():String
{
return _labelField;
}
/**
* @private
*/
public function set labelField(value:String):void
{
if (value == _labelField)
return;
_labelField = value;
labelFieldChanged = true;
invalidateProperties();
}
//------------------------------ PROPERTIES - END -------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
protected function creationCompleteHandler( event: FlexEvent ): void
{
// When the track highlights are created on initialization, the position and dimensions are set wrong
// because the dimensions of the ""track"" component itself are not yet finalized. So, re-calculating the properties of the
// track highlights when the track component has been fully created.
for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons )
{
updateTrackHighlightDisplay( track_highlight );
}
}
//-------------------------------------------------------------------------------------------------
override protected function partAdded(partName: String, instance: Object): void
{
super.partAdded( partName, instance );
if(partName == ""thumb"")
{
var instance_thumb: SliderThumb = SliderThumb( instance );
var slideDuration: Number = getStyle(""slideDuration"");
instance_thumb.setStyle(""slideDuration"", slideDuration);
instance_thumb.addEventListener(MouseEvent.MOUSE_DOWN, thumbMouseDownHandler);
instance_thumb.addEventListener(ThumbMouseEvent.PRESS, thumbPressHandler);
instance_thumb.addEventListener(ThumbKeyEvent.KEY_DOWN, thumbKeyDownHandler);
instance_thumb.addEventListener(FlexEvent.VALUE_COMMIT, thumbValueCommitHandler);
instance_thumb.addEventListener(ThumbEvent.ADD_THUMB_CLICKED, addThumb_clickHandler);
instance_thumb.addEventListener(ThumbEvent.REMOVE_THUMB_CLICKED, removeThumb_clickHandler);
instance_thumb.focusEnabled = true;
}
else if(partName == ""track"")
{
track.addEventListener(MouseEvent.MOUSE_DOWN, trackMouseDownHandler);
track.focusEnabled = false;
}
else if(partName == ""trackHighlight"")
{
var instance_track_highlight: SliderTrackHighlight = SliderTrackHighlight( instance );
instance_track_highlight.addEventListener(ResizeEvent.RESIZE, trackHighlight_resizeHandler);
instance_track_highlight.addEventListener( Event.CHANGE, trackHighlight_changeHandler);
// track is only clickable if in mouse interactionMode
if (getStyle(""interactionMode"") == InteractionMode.MOUSE)
instance_track_highlight.addEventListener(MouseEvent.MOUSE_DOWN, trackHighlight_mouseDownHandler);
}
}
//-------------------------------------------------------------------------------------------------
override protected function partRemoved(partName: String, instance: Object): void
{
super.partRemoved(partName, instance);
if(partName == ""thumb"")
{
var instance_thumb: SliderThumb = SliderThumb(instance);
instance_thumb.removeEventListener(MouseEvent.MOUSE_DOWN, thumbMouseDownHandler);
instance_thumb.removeEventListener(ThumbMouseEvent.PRESS, thumbPressHandler);
instance_thumb.removeEventListener(ThumbKeyEvent.KEY_DOWN, thumbKeyDownHandler);
instance_thumb.removeEventListener(FlexEvent.VALUE_COMMIT, thumbValueCommitHandler);
instance_thumb.removeEventListener(ThumbEvent.ADD_THUMB_CLICKED, addThumb_clickHandler);
instance_thumb.removeEventListener(ThumbEvent.REMOVE_THUMB_CLICKED, removeThumb_clickHandler);
}
else if(partName == ""track"")
{
var track: Button = Button(instance);
track.removeEventListener(MouseEvent.MOUSE_DOWN, trackMouseDownHandler);
}
else if(partName == ""trackHighlight"")
{
var instance_track_highlight: SliderTrackHighlight = SliderTrackHighlight( instance );
instance_track_highlight.removeEventListener(MouseEvent.MOUSE_DOWN, trackHighlight_mouseDownHandler);
instance_track_highlight.removeEventListener( Event.CHANGE, trackHighlight_changeHandler);
instance_track_highlight.removeEventListener(ResizeEvent.RESIZE, trackHighlight_resizeHandler);
}
}
//-------------------------------------------------------------------------------------------------
/**
* @private
*/
override public function styleChanged(styleProp:String):void
{
var anyStyle:Boolean = styleProp == null || styleProp == ""styleName"";
super.styleChanged(styleProp);
if (styleProp == ""showTrackHighlight"" || anyStyle)
{
showTrackHighlightChanged = true;
invalidateProperties();
}
if (styleProp == ""accentColors"" || anyStyle)
{
accentColorsChanged = true;
invalidateProperties();
}
invalidateDisplayList();
}
//-------------------------------------------------------------------------------------------------
override protected function commitProperties(): void
{
super.commitProperties();
if(dataProviderChanged || minimumChanged || maximumChanged || snapIntervalChanged || allowOverlapChanged)
{
if(valueBasedLayout)
{
if(minimumChanged)
valueBasedLayout.minimum = newMinimum;
if(maximumChanged)
valueBasedLayout.maximum = newMaximum;
}
// Compare newValues to the existing values.
// Add and remove thumbs accordingly.
var currentValues: Vector. = getValuesFromThumbs();
for each( var current_value: Number in currentValues )
{
// Check if the current value exists in the new thumbs array.
// If not found, remove the thumb at the current value.
if( -1 == newValues.indexOf( current_value ) )
removeThumbAt( current_value );
}
for each( var dp_item: Object in dataProvider )
{
var new_value: Number = Number( dp_item[ valueField ] );
// Check if the new value already exists in the existing thumbs array.
// If not found, add the thumb at the new value.
if( -1 == currentValues.indexOf( new_value ) )
{
addThumbAt( dp_item );
}
else
{
// If a thumb at the value already exists, then just update its properties.
var thumb_component: SliderThumb = getThumbAtValue( new_value );
updateThumbProperties( thumb_component, dp_item );
}
}
if( contentGroupHighlight && trackHighlight )
{
removeAllTrackHighlights();
createTrackHighlightsFromDataProvider();
}
dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT));
minimumChanged = false;
maximumChanged = false;
snapIntervalChanged = false;
dataProviderChanged = false;
allowOverlapChanged = false;
}
if(thumbValueChanged && !animating && !isDraggingThumbWithLiveDraggingDisabled)
{
dispatchEvent(new Event(Event.CHANGE));
thumbValueChanged = false;
}
if( showTrackHighlightChanged )
{
for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons )
{
track_highlight.visible = _showTrackHighlight;
}
showTrackHighlightChanged = false;
}
if( accentColorsChanged )
{
for each( var _thl: SliderTrackHighlight in trackHighlightButtons )
{
var data_provider_item: Object = _thl.dataProviderItem;
var dp_value: Number = data_provider_item[ valueField ];
var index_of_dp_value: Number = newValues.indexOf( dp_value );
updateTrackHighlightColor( _thl, index_of_dp_value );
}
accentColorsChanged = false;
}
if( markersChanged )
{
if( contentGroupMarker && marker )
{
removeAllMarkers();
createMarkersFrom( _markers );
}
markersChanged = false;
}
}
//-------------------------------------------------------------------------------------------------
private function addThumbAt( dp_item: Object ): void
{
var thumb_component: SliderThumb = SliderThumb( createDynamicPartInstance(""thumb"") );
if( ! thumb_component )
throw new ArgumentError(""Thumb part must be of type "" + getQualifiedClassName(SliderThumb));
updateThumbProperties( thumb_component, dp_item );
var value: Number = Number( dp_item[ valueField ] );
thumb_component.value = value;
addElement(thumb_component);
thumbs.push(thumb_component);
}
//-------------------------------------------------------------------------------------------------
private function updateThumbProperties( thumb_component: SliderThumb, dp_item: Object ): void
{
thumb_component.snapInterval = snapInterval;
thumb_component.dataProviderItem = dp_item;
var value: Number = Number( dp_item[ valueField ] );
var index_of_value: Number = newValues.indexOf( value );
// If the value is not a fixed_value.
if( -1 == newFixedValues.indexOf( value ) )
{
// If there is a neighboring thumb (previous) at a value lesser than this thumb, constrain this thumb to the previous thumb's value.
if( index_of_value > 0 )
{
var previous_value: Number = newValues[ index_of_value - 1 ];
var previous_thumb: SliderThumb = getThumbAtValue( previous_value );
if( previous_thumb )
thumb_component.constrainMinimumTo( previous_thumb, allowDuplicateValues );
else
thumb_component.minimum = minimum;
}
else
{
thumb_component.minimum = minimum;
}
// If there is a neighboring thumb (next) at a value greater than this thumb, constrain this thumb to the next thumb's value.
if( index_of_value < newValues.length - 1 )
{
var next_value: Number = newValues[ index_of_value + 1 ];
var next_thumb: SliderThumb = getThumbAtValue( next_value );
if( next_thumb )
thumb_component.constrainMaximumTo( next_thumb, allowDuplicateValues );
else
thumb_component.maximum = maximum;
}
else
{
thumb_component.maximum = maximum;
}
thumb_component.isValueFixed = false;
}
else
{
// If the value is a fixed value, then the max and min of the thumb should be the value itself.
thumb_component.minimum = value;
thumb_component.maximum = value;
thumb_component.isValueFixed = true;
}
}
//-------------------------------------------------------------------------------------------------
private function createTrackHighlightsFromDataProvider(): void
{
for each( var dp_item: Object in dataProvider )
{
var track_highlight: SliderTrackHighlight = SliderTrackHighlight( createDynamicPartInstance(""trackHighlight"") );
if( ! track_highlight )
throw new ArgumentError( ""Track highlight part must be of type "" + getQualifiedClassName(SliderTrackHighlight) );
track_highlight.value = dp_item[ valueField ];
track_highlight.dataProviderItem = dp_item;
trackHighlightButtons.push( track_highlight );
// Update this track HL with the properties of the current DP item.
updateTrackHighlightDisplay( track_highlight );
contentGroupHighlight.addElement( track_highlight );
}
}
//-------------------------------------------------------------------------------------------------
/**
* @protected
*/
protected function updateTrackHighlightDisplay( track_highlight: SliderTrackHighlight ):void
{
var dp_item: Object = track_highlight.dataProviderItem;
var dp_value: Number = dp_item[ valueField ];
var index_of_dp_value: Number = newValues.indexOf( dp_value );
var _thumb: SliderThumb = getThumbAtValue( dp_value );
if( !_thumb || !track || !track_highlight )
return;
var hl_x: Number;
var hl_y: Number = 0;
var hl_width: Number;
var hl_height: Number = track.getLayoutBoundsHeight();
var track_width: Number = track.getLayoutBoundsWidth();
var range: Number = maximum - minimum;
var thumb_track_x: Number;
var thumb_global_position: Point;
var parent_thumb_x: Number;
// If first thumb.
if( 0 == index_of_dp_value )
{
hl_x = 0;
// calculate thumb position.
thumb_track_x = (range > 0) ? ((_thumb.value - minimum) / range) * track_width : 0;
// convert to parent's coordinates.
thumb_global_position = track.localToGlobal( new Point(thumb_track_x, 0) );
parent_thumb_x = _thumb.parent.globalToLocal( thumb_global_position ).x;
hl_width = Math.round( parent_thumb_x );
}
else
{
// Since newValues is sorted, the previous value would be at the previous index in the newValues vector.
var previous_thumb_value: Number = newValues[ index_of_dp_value - 1];
var previous_thumb: SliderThumb = getThumbAtValue( previous_thumb_value );
// calculate previous thumb position.
var previous_thumb_track_x: Number = (range > 0) ? ((previous_thumb.value - minimum) / range) * track_width : 0;
// convert to parent's coordinates.
var previous_thumb_global_position: Point = track.localToGlobal( new Point(previous_thumb_track_x, 0) );
var parent_previous_thumb_x: Number = previous_thumb.parent.globalToLocal( previous_thumb_global_position ).x;
hl_x = parent_previous_thumb_x;
// calculate thumb position.
thumb_track_x = (range > 0) ? ((_thumb.value - minimum) / range) * track_width : 0;
// convert to parent's coordinates.
thumb_global_position = track.localToGlobal( new Point(thumb_track_x, 0) );
parent_thumb_x = _thumb.parent.globalToLocal( thumb_global_position ).x;
hl_width = Math.round( parent_thumb_x - parent_previous_thumb_x );
}
track_highlight.setLayoutBoundsPosition( hl_x, hl_y );
track_highlight.setLayoutBoundsSize( hl_width, hl_height );
updateTrackHighlightColor( track_highlight, index_of_dp_value );
track_highlight.visible = showTrackHighlight;
if( dp_item.hasOwnProperty( labelField ) && dp_item[ labelField ] is String )
track_highlight.label = String( dp_item[ labelField ] );
else
{
dp_item[ labelField ] = defaultTrackHighlightLabel;
track_highlight.label = defaultTrackHighlightLabel;
}
}
//-------------------------------------------------------------------------------------------------
protected function updateTrackHighlightColor( track_highlight: SliderTrackHighlight, index_of_dp_value: Number ): void
{
if( !track_highlight )
return;
// Color of the track highlight
var index_color_to_use: Number;
if( index_of_dp_value <= accentColors.length - 1 )
index_color_to_use = index_of_dp_value;
else
index_color_to_use = index_of_dp_value % accentColors.length;
track_highlight.setStyle( ""themeColor"", uint( accentColors[ index_color_to_use ] ) );
}
//-------------------------------------------------------------------------------------------------
private function createMarkersFrom(array_markers: Array): void
{
for(var index: int = 0; index < array_markers.length; index++)
{
var marker_component: SliderMarker = SliderMarker( createDynamicPartInstance(""marker"") );
if( ! marker_component )
throw new ArgumentError(""Slider Marker part must be of type "" + getQualifiedClassName( SliderMarker ) );
marker_component.value = array_markers[ index ];
markerComponents.push( marker_component );
contentGroupMarker.addElement( marker_component );
}
}
//-------------------------------------------------------------------------------------------------
public function removeThumbAt( value: Number ): void
{
const _thumb: SliderThumb = getThumbAtValue( value );
if( ! _thumb )
throw new Error( ""No thumb found at "" + value );
removeThumb( _thumb );
}
//-------------------------------------------------------------------------------------------------
private function removeThumb( thumb_instance: SliderThumb ): void
{
removeDynamicPartInstance( ""thumb"", thumb_instance );
removeElement( thumb_instance );
const _index: Number = thumbs.indexOf( thumb_instance );
thumbs.splice( _index, 1 );
}
//-------------------------------------------------------------------------------------------------
private function removeAllTrackHighlights(): void
{
for each( var track_hl: SliderTrackHighlight in trackHighlightButtons )
{
removeDynamicPartInstance( ""trackHighlight"", track_hl );
contentGroupHighlight.removeElement( track_hl );
}
trackHighlightButtons.splice( 0, trackHighlightButtons.length );
}
//-------------------------------------------------------------------------------------------------
private function removeAllMarkers(): void
{
for each( var _marker: SliderMarker in markerComponents )
{
removeDynamicPartInstance( ""marker"", _marker );
contentGroupMarker.removeElement( _marker );
}
markerComponents.splice(0, markerComponents.length);
}
//-------------------------------------------------------------------------------------------------
private function thumbPressHandler(event: ThumbMouseEvent): void
{
if(animating)
animatedThumb.stopAnimation();
var thumb: SliderThumb = SliderThumb(event.currentTarget);
// Store the delta between mouse pointer's position on thumb down and the current value of the thumb.
// On dragging, this value is used to offset the new value, making it appear as
// if the mouse pointer stays in the same position over the thumb. Can't trust the thumb's
// own measurements here since it doesn't know how the layout is positioning it relative to its value.
var thumbPressPoint: Point = contentGroup.globalToLocal(new Point(event.stageX, event.stageY));
var thumbPoint: Point = valueBasedLayout.valueToPoint(thumb.value);
thumbPressOffset = new Point(thumbPoint.x - thumbPressPoint.x, thumbPoint.y - thumbPressPoint.y);
thumb.addEventListener(ThumbMouseEvent.DRAGGING, thumbDraggingHandler);
thumb.addEventListener(ThumbMouseEvent.RELEASE, thumbReleaseHandler);
draggingThumb = true;
dispatchChangeStart();
}
//-------------------------------------------------------------------------------------------------
private function thumbDraggingHandler(event: ThumbMouseEvent): void
{
var thumb: SliderThumb = SliderThumb(event.currentTarget);
if(valueBasedLayout)
{
var draggedTo: Point = contentGroup.globalToLocal(new Point(event.stageX, event.stageY));
draggedTo.offset(thumbPressOffset.x, thumbPressOffset.y);
thumb.value = valueBasedLayout.pointToValue(draggedTo);
}
}
//-------------------------------------------------------------------------------------------------
private function thumbReleaseHandler(event: ThumbMouseEvent): void
{
var thumb: SliderThumb = SliderThumb(event.currentTarget);
thumb.removeEventListener(ThumbMouseEvent.DRAGGING, thumbDraggingHandler);
thumb.removeEventListener(ThumbMouseEvent.RELEASE, thumbReleaseHandler);
draggingThumb = false;
dispatchChangeEnd();
invalidateThumbValues();
}
//-------------------------------------------------------------------------------------------------
private function thumbKeyDownHandler(event: ThumbKeyEvent): void
{
var thumb: SliderThumb = SliderThumb(event.currentTarget);
if(animating)
stopAnimation();
if(!keyDownOnThumb)
{
dispatchChangeStart();
keyDownOnThumb = true;
thumb.addEventListener(ThumbKeyEvent.KEY_UP, thumbKeyUpHandler);
}
thumb.value = event.newValue;
}
//-------------------------------------------------------------------------------------------------
private function thumbKeyUpHandler(event: ThumbKeyEvent): void
{
var thumb: SliderThumb = SliderThumb(event.currentTarget);
dispatchChangeEnd();
keyDownOnThumb = false;
thumb.removeEventListener(ThumbKeyEvent.KEY_UP, thumbKeyUpHandler);
}
//-------------------------------------------------------------------------------------------------
private function thumbValueCommitHandler(event: FlexEvent): void
{
var _thumb: SliderThumb = SliderThumb( event.currentTarget );
if(!animating && !isDraggingThumbWithLiveDraggingDisabled)
{
invalidateThumbValues();
}
if( _thumb.dataProviderItem &&
_thumb.dataProviderItem.hasOwnProperty( valueField ) )
{
_thumb.dataProviderItem[ valueField ] = _thumb.value;
dataProvider.itemUpdated( _thumb.dataProviderItem, valueField );
}
// Constrain the neighboring thumbs only after the DP has been updated.
// This is because the constrainNeighboringThumbs function uses the
// newValues vector and it needs to be up-to-date.
if(!allowOverlap && thumbs.length > 1)
{
constrainNeighboringThumbs( _thumb );
}
contentGroup.invalidateDisplayList();
dispatchEvent( new MultiThumbSliderEvent( MultiThumbSliderEvent.VALUE_CHANGE ) );
}
//-------------------------------------------------------------------------------------------------
private function invalidateThumbValues(): void
{
if(!thumbValueChanged)
{
thumbValueChanged = true;
invalidateProperties();
}
}
//-------------------------------------------------------------------------------------------------
private function get isDraggingThumbWithLiveDraggingDisabled(): Boolean
{
return draggingThumb && !getStyle(""liveDragging"");
}
//-------------------------------------------------------------------------------------------------
private function constrainNeighboringThumbs( thumb_component: SliderThumb ): void
{
var index_of_value: Number = newValues.indexOf( thumb_component.value );
var _thumb: SliderThumb;
if( index_of_value > 0 )
{
_thumb = getThumbAtValue( newValues[ index_of_value - 1 ] );
// If the thumb is a fixed_value thumb, then the constraints should not be messed with.
if( _thumb && ! _thumb.isValueFixed )
_thumb.constrainMaximumTo( thumb_component, allowDuplicateValues );
}
if( index_of_value < newValues.length - 1 )
{
_thumb = getThumbAtValue( newValues[ index_of_value + 1 ] );
// If the thumb is a fixed_value thumb, then the constraints should not be messed with.
if( _thumb && ! _thumb.isValueFixed )
_thumb.constrainMinimumTo( thumb_component, allowDuplicateValues );
}
}
//-------------------------------------------------------------------------------------------------
private function trackMouseDownHandler(event: MouseEvent): void
{
if(valueBasedLayout)
{
var trackRelative: Point = track.globalToLocal(new Point(event.stageX, event.stageY));
var trackClickValue: Number = valueBasedLayout.pointToValue(trackRelative);
var nearestThumb: SliderThumb = nearestThumbTo(trackClickValue);
if( nearestThumb )
{
if(getStyle(""slideDuration"") != 0)
beginThumbAnimation(nearestThumb, trackClickValue);
else
nearestThumb.value = trackClickValue;
}
}
}
//-------------------------------------------------------------------------------------------------
private function nearestThumbTo(value: Number): SliderThumb
{
var nearestValue: Number = valueBasedLayout.maximum;
var nearestThumb: SliderThumb;
for(var index: int = 0; index < thumbs.length; index++)
{
var thumb: SliderThumb = thumbs[index];
var valueDelta: Number = Math.abs(thumb.value - value);
var valueInRange: Boolean = allowOverlap || (thumb.minimum <= value && thumb.maximum >= value);
if(valueDelta < nearestValue && valueInRange)
{
nearestValue = valueDelta;
nearestThumb = thumb;
}
}
return nearestThumb;
}
//-------------------------------------------------------------------------------------------------
private function beginThumbAnimation(thumb: SliderThumb, value: Number): void
{
if(animating)
animatedThumb.stopAnimation();
animating = true;
animatedThumb = thumb;
animatedThumb.animateMovementTo(value, endAnimation);
dispatchChangeStart();
}
//-------------------------------------------------------------------------------------------------
private function stopAnimation(): void
{
animatedThumb.stopAnimation();
endAnimation();
}
//-------------------------------------------------------------------------------------------------
private function endAnimation(): void
{
animatedThumb = null;
animating = false;
dispatchChangeEnd();
}
//-------------------------------------------------------------------------------------------------
private function addThumb_clickHandler( event: ThumbEvent ): void
{
const thumb_component: SliderThumb = SliderThumb( event.currentTarget );
var current_value: Number = thumb_component.value;
var local_values: Vector. = ObjectUtil.copy( newValues.sort( Array.NUMERIC ) ) as Vector.;
// To accommodate the new thumb, we may have to move some of the neighboring thumbs around.
// To figure out in which direction we need to do the ""spreading out"", we first go in one
// direction; if not successful, we then reset the changes of the first trial and try the other direction.
// So, during these two ""trials"", we should not edit the actual dataProvider. We use a local copy.
var local_data_provider: IList = ObjectUtil.copy( dataProvider ) as IList;
const index_current_value: Number = local_values.indexOf( current_value );
var next_value: Number = local_values[ index_current_value + 1 ];
var gap_between_values: Number = next_value - current_value;
var new_value: Number;
var dp_item: Object;
// The difference between the current and next values should be greater than
// the snapInterval. Only then, we can insert another value between them.
// NOTE: It is NOT enough if the gap is exactly the snapInterval, because we
// are inserting a new thumb in this gap.
// Contrastingly, in all other checks below, for all the other values, we are satisfied with
// a gap of snapInterval, because we are not inserting a thumb in those gaps.
if( gap_between_values <= snapInterval )
{
// 1. Increment the next_value by snapInterval.
// 2. Make sure that the new next_value and the value after it are separated
// by at least snapInterval.
// 3. If not, repeat (from step 1) for the value after the new next_value.
// Before incrementing next_value, we also need to get the (local) DP item corresponding to it.
// Even the value of the DP item should be incremented below.
dp_item = getItemOfValue( next_value, local_data_provider );
next_value += snapInterval;
if( next_value > maximum )
next_value = maximum;
dp_item[ valueField ] = next_value;
local_values[ index_current_value + 1 ] = next_value;
var successfully_spread: Boolean = false;
for( var i: Number = index_current_value + 1 ; i <= local_values.length - 1 ; i++ )
{
var i_value: Number = local_values[ i ];
var i_plus_one_value: Number = ( i == local_values.length - 1 ) ? maximum : local_values[ i + 1 ];
// We are satisfied if the gap is at least snapInterval.
if( i_plus_one_value - i_value >= snapInterval )
{
successfully_spread = true;
break;
}
else if( i == local_values.length - 1 )
{
successfully_spread = false;
break;
}
else
{
// Before incrementing i_plus_one_value, we also need to get the (local) DP item corresponding to it.
// Even the value of the DP item should be incremented below.
dp_item = getItemOfValue( i_plus_one_value, local_data_provider );
i_plus_one_value += snapInterval;
if( i_plus_one_value > maximum )
i_plus_one_value = maximum;
dp_item[ valueField ] = i_plus_one_value;
local_values[ i + 1 ] = i_plus_one_value;
}
}
if( ! successfully_spread )
{
// Try spreading in the other direction.
local_values = ObjectUtil.copy( newValues.sort( Array.NUMERIC ) ) as Vector.;
local_data_provider = ObjectUtil.copy( dataProvider ) as IList;
// Before decrementing current_value, we also need to get the (local) DP item corresponding to it.
// Even the value of the DP item should be decremented below.
dp_item = getItemOfValue( current_value, local_data_provider );
current_value -= snapInterval;
if( current_value < minimum )
current_value = minimum;
dp_item[ valueField ] = current_value;
local_values[ index_current_value ] = current_value;
for( var j: Number = index_current_value ; j >= 0 ; j-- )
{
var j_value: Number = local_values[ j ];
var j_minus_one_value: Number = ( 0 == j ) ? minimum : local_values[ j - 1 ];
// We are satisfied if the gap is at least snapInterval.
if( j_value - j_minus_one_value >= snapInterval )
{
successfully_spread = true;
break;
}
else if( 0 == j )
{
successfully_spread = false;
break;
}
else
{
// Before decrementing j_minus_one_value, we also need to get the (local) DP item corresponding to it.
// Even the value of the DP item should be decremented below.
dp_item = getItemOfValue( j_minus_one_value, local_data_provider );
j_minus_one_value -= snapInterval;
if( j_minus_one_value < minimum )
j_minus_one_value = minimum;
dp_item[ valueField ] = j_minus_one_value;
local_values[ j - 1 ] = j_minus_one_value;
}
}
if( ! successfully_spread )
{
trace(""Can't insert new thumb because of lack of space."");
Alert.show( ""Sorry, no space for a new thumb!"", ""You have run out of thumbs!"" );
return;
}
}
}
current_value = local_values[ index_current_value ];
next_value = local_values[ index_current_value + 1 ];
gap_between_values = next_value - current_value;
// The new value should be equi-distant between the two values.
new_value = current_value + Math.round( gap_between_values / 2 );
var new_dp_item: Object = new Object();
new_dp_item[ valueField ] = new_value;
new_dp_item[ labelField ] = defaultTrackHighlightLabel;
local_data_provider.addItem( new_dp_item );
dataProvider = local_data_provider;
var thumb_added_event: MultiThumbSliderEvent = new MultiThumbSliderEvent( MultiThumbSliderEvent.THUMB_ADDED, new_dp_item );
dispatchEvent( thumb_added_event );
}
//-------------------------------------------------------------------------------------------------
private function removeThumb_clickHandler( event: ThumbEvent ): void
{
const thumb_component: SliderThumb = SliderThumb( event.currentTarget );
// Make a copy of the thumb's DP item so it can be sent with the dispatched event.
var data_provider_item: Object = ObjectUtil.copy( thumb_component.dataProviderItem );
dataProvider.removeItemAt( dataProvider.getItemIndex( thumb_component.dataProviderItem ) );
var thumb_removed_event: MultiThumbSliderEvent = new MultiThumbSliderEvent( MultiThumbSliderEvent.THUMB_REMOVED, data_provider_item );
dispatchEvent( thumb_removed_event );
}
//-------------------------------------------------------------------------------------------------
private function thumbMouseDownHandler(event: MouseEvent): void
{
visuallyMoveToFront(IVisualElement(event.currentTarget));
}
//---------------------------------------Thumb Code - End----------------------------------------------------------
//-------------------------------------Track Highlight Code - Start------------------------------------------------------------
/**
* @private
*/
private function trackHighlight_resizeHandler(event:Event):void
{
var track_highlight: SliderTrackHighlight = SliderTrackHighlight( event.currentTarget );
updateTrackHighlightDisplay( track_highlight );
}
//-------------------------------------------------------------------------------------------------
protected function trackHighlight_changeHandler( event: Event ): void
{
var track_highlight: SliderTrackHighlight = SliderTrackHighlight( event.currentTarget );
var dp_item: Object = track_highlight.dataProviderItem;
dp_item[ labelField ] = track_highlight.label;
dataProvider.itemUpdated( dp_item, labelField );
dispatchEvent( new MultiThumbSliderEvent( MultiThumbSliderEvent.LABEL_CHANGE ) );
}
//-------------------------------------------------------------------------------------------------
/**
* @private
* Handle mouse-down events for the slider track hightlight. We
* calculate the value based on the new position and then
* move the thumb to the correct location as well as
* commit the value.
*/
protected function trackHighlight_mouseDownHandler(event:MouseEvent):void
{
trackMouseDownHandler(event);
}
//-------------------------------------Track Highlight Code - End------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
private function get valueBasedLayout(): IValueLayout
{
return (layout as IValueLayout);
}
//-------------------------------------------------------------------------------------------------
private function getThumbAtValue( value: Number ): SliderThumb
{
var thumb_at_value: SliderThumb = null;
for each( var _thumb: SliderThumb in thumbs )
{
if( _thumb.value == value )
{
thumb_at_value = _thumb;
break;
}
}
return thumb_at_value;
}
//-------------------------------------------------------------------------------------------------
private function getTrackHighlightAtValue( value: Number ): SliderTrackHighlight
{
var track_highlight: SliderTrackHighlight = null;
for each( var _thl: SliderTrackHighlight in trackHighlightButtons )
{
if( _thl.value == value )
{
track_highlight = _thl;
break;
}
}
return track_highlight;
}
//-------------------------------------------------------------------------------------------------
private function getValuesFromThumbs(): Vector.
{
var thumbValues: Vector. = new Vector.();
for each( var _thumb: SliderThumb in thumbs )
{
thumbValues.push( _thumb.value );
}
return thumbValues.sort( Array.NUMERIC );
}
//-------------------------------------------------------------------------------------------------
private function visuallyMoveToFront(instance: IVisualElement): void
{
var lastIndexElement: IVisualElement = getElementAt(numElements - 1);
if(instance != lastIndexElement)
swapElements(instance, lastIndexElement);
}
//-------------------------------------------------------------------------------------------------
private function dispatchChangeStart(): void
{
dispatchEvent(new FlexEvent(FlexEvent.CHANGE_START));
}
//-------------------------------------------------------------------------------------------------
private function dispatchChangeEnd(): void
{
dispatchEvent(new FlexEvent(FlexEvent.CHANGE_END));
}
//-------------------------------------------------------------------------------------------------
private function removeDataProviderDuplicateValues(): void
{
var duplicate_items: ArrayCollection = new ArrayCollection();
var vector_values: Vector. = new Vector.();
for each( var dp_item: Object in dataProvider )
{
if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number )
{
var value: Number = Number( dp_item[ valueField ] );
if( -1 == vector_values.indexOf( value ) )
{
vector_values.push( value );
}
// If already seen - this is a duplicate item.
else
{
duplicate_items.addItem( dp_item );
}
}
}
// Remove duplicate items.
for each( var duplicate_item: Object in duplicate_items )
{
dataProvider.removeItemAt( dataProvider.getItemIndex( duplicate_item ) );
}
}
//-------------------------------------------------------------------------------------------------
private function removeValuesOutOfBounds(): void
{
var items_out_of_bounds: ArrayCollection = new ArrayCollection();
for each( var dp_item: Object in dataProvider )
{
if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number )
{
const _value: Number = Number( dp_item[ valueField ] );
if( _value < minimum || _value > maximum )
items_out_of_bounds.addItem( dp_item );
}
}
// Remove items out of bounds.
for each( var item_out_of_bounds: Object in items_out_of_bounds )
{
dataProvider.removeItemAt( dataProvider.getItemIndex( item_out_of_bounds ) );
}
}
//-------------------------------------------------------------------------------------------------
private function getValuesFromDataProvider(): Vector.
{
var thumbValues: Vector. = new Vector.();
for each( var dp_item: Object in dataProvider )
{
if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number )
thumbValues.push( Number( dp_item[ valueField ] ) );
}
return thumbValues.sort( Array.NUMERIC );
}
//-------------------------------------------------------------------------------------------------
private function getFixedValuesFromDataProvider(): Vector.
{
var fixed_values: Vector. = new Vector.();
for each( var dp_item: Object in dataProvider )
{
if( ! dp_item.hasOwnProperty( fixedValueField ) ||
(
dp_item.hasOwnProperty( fixedValueField ) &&
! (dp_item[ fixedValueField ] is Boolean)
))
{
dp_item[ fixedValueField ] = false;
continue;
}
// If we reach this point, dp_item[ fixedValueField ] definitely exists.
if( dp_item.hasOwnProperty( valueField ) &&
dp_item[ valueField ] is Number )
{
var is_fixed_value: Boolean = Boolean( dp_item[ fixedValueField ] );
if( is_fixed_value )
fixed_values.push( Number( dp_item[ valueField ] ) );
}
}
return fixed_values.sort( Array.NUMERIC );
}
//-------------------------------------------------------------------------------------------------
private var newValues: Vector.;
private var newFixedValues: Vector.;
private function reactToDataProviderUpdate(): void
{
if( ! allowDuplicateValues )
removeDataProviderDuplicateValues();
removeValuesOutOfBounds();
newValues = getValuesFromDataProvider();
newFixedValues = getFixedValuesFromDataProvider();
}
//-------------------------------------------------------------------------------------------------
private function getTrackHighlightOfDataProviderItem( dp_item: Object ): SliderTrackHighlight
{
for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons )
{
if( dp_item == track_highlight.dataProviderItem )
return track_highlight;
}
return null;
}
//-------------------------------------------------------------------------------------------------
private function getItemOfValue( value: Number, collection: IList ): Object
{
for each( var dp_item: Object in collection )
{
if( dp_item.hasOwnProperty( valueField ) &&
dp_item[ valueField ] is Number )
{
var dp_item_value: Number = Number( dp_item[ valueField ] );
if( value == dp_item_value )
return dp_item;
}
}
return null;
}
//-------------------------------------------------------------------------------------------------
/**
* @private
* Called when contents within the dataProvider changes.
*
* @param event The collection change event
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
protected function dataProvider_collectionChangeHandler( event: CollectionEvent ):void
{
// We need to temporarily disable the listener because in this handler we may make some updates to the
// dataProvider (in ""reactToDataProviderUpdate"") which will further call the same events. It goes into
// an endless loop. We will add the listener again at the end of this handler function.
if (dataProvider)
dataProvider.removeEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler );
var i: uint;
switch (event.kind)
{
case CollectionEventKind.UPDATE:
for each( var event_object: * in event.items )
{
if (event_object is PropertyChangeEvent)
{
var property_change_event: PropertyChangeEvent = PropertyChangeEvent( event_object );
if( null != property_change_event )
{
// Even if one valueField has been updated, refresh the slider. Hence the ""break"".
if( valueField == property_change_event.property )
{
reactToDataProviderUpdate();
dataProviderChanged = true;
invalidateProperties();
break;
}
}
}
}
break;
default:
reactToDataProviderUpdate();
dataProviderChanged = true;
invalidateProperties();
}
if (dataProvider)
dataProvider.addEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler );
}
//-------------------------------------------------------------------------------------------------
}
}",12390,False,2302.277922284171,median
"////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the ""License""); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an ""AS IS"" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.controls.advancedDataGridClasses
{
/* import flash.display.DisplayObject;
import flash.events.Event;
*/
import mx.controls.AdvancedDataGrid;
import mx.controls.TextInput;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.core.ClassFactory;
import mx.core.IFactory;
import mx.core.mx_internal;
import mx.utils.StringUtil;
import org.apache.royale.core.UIBase;
import org.apache.royale.events.Event;
use namespace mx_internal;
//--------------------------------------
// Styles
//--------------------------------------
//include ""../../styles/metadata/TextStyles.as"";
/**
* The background color of the column.
* The default value is undefined, which means it uses the value of the
* backgroundColor style of the associated AdvancedDataGrid control.
* The default value for the AdvancedDataGrid control is 0xFFFFFF.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
[Style(name=""backgroundColor"", type=""uint"", format=""Color"", inherit=""no"")]
/**
* The name of a CSS style declaration for controlling other aspects of
* the appearance of the column headers.
* The default value is undefined, which means it uses the value of the
* headerStyleName style of the associated AdvancedDataGrid control.
* The default value for the AdvancedDataGrid control is
* "".advancedDataGridStyles"".
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
[Style(name=""headerStyleName"", type=""String"", inherit=""no"")]
/**
* The number of pixels between the container's left border and its content
* area.
* There is no default value for this style.
* An item renderer's setting of the paddingLeft property
* is used to determine the default.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//[Style(name=""paddingLeft"", type=""Number"", format=""Length"", inherit=""no"")]
/**
* The number of pixels between the container's right border and its content
* area.
* There is no default value for this style.
* An item renderer's setting of the paddingRight property
* is used to determine the default.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//[Style(name=""paddingRight"", type=""Number"", format=""Length"", inherit=""no"")]
/**
* The AdvancedDataGridColumn class describes a column in an AdvancedDataGrid control.
* There is one AdvancedDataGridColumn per displayable column, even if a column
* is hidden or off-screen.
* The data provider items of an AdvancedDataGrid control
* can contain properties that are not displayed,
* and therefore, do not need an AdvancedDataGridColumn.
* An AdvancedDataGridColumn allows specification of the color and font of the text
* in a column; specification of what kind of component displays the data for the column;
* specification of whether the column is editable, sortable, or resizeable;
* and specification of the text for the column header.
*
*
Notes:
*
An AdvancedDataGridColumn only holds information about a column;
* it is not the parent of the item renderers in the column.
*
If you specify an AdvancedDataGridColumn class without a dataField
* property, you must specify a sortCompareFunction
* property. Otherwise, sort operations may cause run-time errors.
*
*
* @mxml
*
*
You use the <mx.AdvancedDataGridcolumn> tag to configure a column
* of a AdvancedDataGrid control.
* You specify the <mx.AdvancedDataGridcolumn> tag as a child
* of the columns property in MXML.
* The <mx.AdvancedDataGridcolumn> tag inherits all of the
* tag attributes of its superclass, and adds the following tag attributes:
*
* @see mx.controls.AdvancedDataGrid
*
* @see mx.styles.CSSStyleDeclaration
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
* @royalesuppresspublicvarwarning
*/
public class AdvancedDataGridColumn extends DataGridColumn
{//extends CSSStyleDeclaration implements IIMESupport
//include ""../../core/Version.as"";
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
//----------------------------------
// embeddedFontRegistry
//----------------------------------
// private static var noEmbeddedFonts:Boolean;
/**
* @private
* Storage for the embeddedFontRegistry property.
* This gets initialized on first access,
* not at static initialization time, in order to ensure
* that the Singleton registry has already been initialized.
*/
// private static var _embeddedFontRegistry:IEmbeddedFontRegistry;
/**
* @private
* A reference to the embedded font registry.
* Single registry in the system.
* Used to look up the moduleFactory of a font.
*/
/* private static function get embeddedFontRegistry():IEmbeddedFontRegistry
{
if (!_embeddedFontRegistry && !noEmbeddedFonts)
{
try
{
_embeddedFontRegistry = IEmbeddedFontRegistry(
Singleton.getInstance(""mx.core::IEmbeddedFontRegistry""));
}
catch (e:Error)
{
noEmbeddedFonts = true;
}
}
return _embeddedFontRegistry;
}
*/
private static var _defaultItemEditorFactory:IFactory;
mx_internal static function get defaultItemEditorFactory():IFactory
{
if (!_defaultItemEditorFactory)
_defaultItemEditorFactory = new ClassFactory(TextInput);
return _defaultItemEditorFactory;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @param columnName The name of the field in the data provider
* associated with the column, and the text for the header cell of this
* column. This is equivalent to setting the dataField
* and headerText properties.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public function AdvancedDataGridColumn(columnName:String = null)
{
super(columnName);
/* if (columnName)
{
dataField = columnName;
headerText = columnName;
} */
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
// mx_internal var list:UIBase; //BaseEx;
/**
* @private
*/
// mx_internal var explicitWidth:Number;
/**
* @private
* Holds the last recorded value of the module factory used to create the font.
*/
// private var oldEmbeddedFontContext:IFlexModuleFactory = null;
/**
* @private
*
* true if font properties do not need to be set.
*/
// private var fontPropertiesSet:Boolean = false;
/**
* @private
* True if createInFontContext has been called.
*/
// private var hasFontContextBeenSaved:Boolean = false;
// preferred width is the number we should use when measuring
// regular width will be changed if we shrink columns to fit.
// mx_internal var preferredWidth:Number = 100;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
// ------------------------------------------------
// fontWeight
// ------------------------------------------------
public function get fontWeight():String
{
return ""normal"";
}
public function set fontWeight(value:String):void
{
}
// ------------------------------------------------
// fontSize
// ------------------------------------------------
public function get fontSize():Number
{
return 11;
}
public function set fontSize(value:Number):void
{
}
// ------------------------------------------------
// color
// ------------------------------------------------
public function get color():uint
{
return 0x0B333C;
}
public function set color(value:uint):void
{
}
//----------------------------------
// sortDescending
//----------------------------------
/**
* Indicates whether the column sort is
* in ascending order, false,
* or descending order, true.
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
// public var sortDescending:Boolean = false;
//----------------------------------
// dataTipField
//----------------------------------
/**
* @private
* Storage for the dataTipField property.
*/
/* private var _dataTipField:String;
[Bindable(""dataTipFieldChanged"")]
[Inspectable(category=""Advanced"", defaultValue=""label"")]
*/
/**
* The name of the field in the data provider to display as the data tip.
* By default, the AdvancedDataGrid control looks for a property named
* label on each data provider item and displays it.
* However, if the data provider does not contain a label
* property, you can set the dataTipField property to
* specify a different property.
* For example, you could set the value to ""FullName"" when a user views a
* set of people's names included from a database.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function get dataTipField():String
{
return _dataTipField;
} */
/**
* @private
*/
/* public function set dataTipField(value:String):void
{
_dataTipField = value;
if (owner)
{
owner.invalidateList();
}
dispatchEvent(new Event(""dataTipChanged""));
} */
//----------------------------------
// dataTipFunction
//----------------------------------
/**
* @private
* Storage for the dataTipFunction property.
*/
/* private var _dataTipFunction:Function;
[Bindable(""dataTipFunctionChanged"")]
[Inspectable(category=""Advanced"")] */
/**
* Specifies a callback function to run on each item of the data provider
* to determine its data tip.
* This property is used by the itemToDataTip() method.
*
*
By default, the control looks for a property named label
* on each data provider item and displays it as its dataTip.
* However, some data providers do not have a label property
* or another property that you can use for displaying data
* in the rows.
* For example, you might have a data provider that contains a lastName
* and firstName fields, but you want to display full names as the dataTip.
* You can specify a function to the dataTipFunction property
* that returns a single String containing the value of both fields. You
* can also use the dataTipFunction property for handling
* formatting and localization.
*
*
The function must take a single Object parameter, and return a String.
* For the header cell of a column, the Object parameter is of type AdvancedDataGridColumn.
* For table cells, the Object parameter contains the data provider element for the cell.
*
*
Shown below is an example implementation of the function.
* For the header cell, return ""Column Name"".
* For the table cells, return the name property of the Object:
*
* private function tipFunc(value:Object):String
* {
* if (value is AdvancedDataGridColumn)
* return ""Column Name"";
*
* // Use the 'name' property of the data provider element.
* return ""Name: "" + value[""name""];
* }
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function get dataTipFunction():Function
{
return _dataTipFunction;
} */
/**
* @private
*/
/* public function set dataTipFunction(value:Function):void
{
_dataTipFunction = value;
if (owner)
{
owner.invalidateList();
}
dispatchEvent(new Event(""labelFunctionChanged""));
} */
//----------------------------------
// draggable
//----------------------------------
// [Inspectable(category=""General"")]
/**
* A flag that indicates whether the user is allowed to drag
* the column to a new position
* If true, the user can drag the
* the column headers to a new position
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//public var draggable:Boolean = true;
//----------------------------------
// editable
//----------------------------------
//[Inspectable(category=""General"")]
/**
* A flag that indicates whether the items in the column are editable.
* If true, and the AdvancedDataGrid's editable
* property is also true, the items in a column are
* editable and can be individually edited
* by clicking an item or by navigating to the item with the
* Tab and Arrow keys.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//public var editable:Boolean = true;
//----------------------------------
// itemEditor
//----------------------------------
//[Inspectable(category=""General"")]
/**
* A class factory for the instances of the item editor to use for the
* column, when it is editable.
*
*
The default value is the mx.controls.TextInput control.
*
* @see mx.controls.TextInput
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//public var itemEditor:IFactory = defaultItemEditorFactory;
//----------------------------------
// editorDataField
//----------------------------------
// [Inspectable(category=""General"")]
/**
* The name of the property of the item editor that contains the new
* data for the list item.
* For example, the default itemEditor is
* TextInput, so the default value of the editorDataField
* property is ""text"", which specifies the
* text property of the TextInput control.
*
* @default ""text""
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
//public var editorDataField:String = ""text"";
//----------------------------------
// editorHeightOffset
//----------------------------------
[Inspectable(category=""General"", defaultValue=""0"")]
/**
* The height of the item editor, in pixels, relative to the size of the
* item renderer. This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public var editorHeightOffset:Number = 0;
//----------------------------------
// editorWidthOffset
//----------------------------------
//[Inspectable(category=""General"", defaultValue=""0"")]
/**
* The width of the item editor, in pixels, relative to the size of the
* item renderer. This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public var editorWidthOffset:Number = 0;
//----------------------------------
// editorXOffset
//----------------------------------
// [Inspectable(category=""General"", defaultValue=""0"")]
/**
* The x location of the upper-left corner of the item editor,
* in pixels, relative to the upper-left corner of the item.
* This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public var editorXOffset:Number = 0;
//----------------------------------
// editorYOffset
//----------------------------------
//[Inspectable(category=""General"", defaultValue=""0"")]
/**
* The y location of the upper-left corner of the item editor,
* in pixels, relative to the upper-left corner of the item.
* This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public var editorYOffset:Number = 0;
//----------------------------------
// editorUsesEnterKey
//----------------------------------
//[Inspectable(category=""General"", defaultValue=""false"")]
/**
* A flag that indicates whether the item editor uses Enter key.
* If true the item editor uses the Enter key and the
* AdvancedDataGrid will not look for the Enter key and move the editor in
* response.
* Note that changing this value while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public var editorUsesEnterKey:Boolean = false;
//----------------------------------
// headerRenderer
//----------------------------------
/**
* @private
* Storage for the headerRenderer property.
*/
private var _headerRenderer:IFactory;
[Bindable(""headerRendererChanged"")]
[Inspectable(category=""Other"")]
/**
* The class factory for item renderer instances that display the
* column header for the column.
* You can specify a drop-in item renderer,
* an inline item renderer, or a custom item renderer component as the
* value of this property.
*
*
The default item renderer is the AdvancedDataGridItemRenderer class,
* which displays the item data as text.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
override public function get headerRenderer():IFactory
{
return _headerRenderer;
}
/**
* @private
*/
override public function set headerRenderer(value:IFactory):void
{
_headerRenderer = value;
// rebuild the headers
/* if (owner)
{
owner.invalidateList();
owner.columnRendererChanged(this);
}
dispatchEvent(new Event(""headerRendererChanged"")); */
}
//----------------------------------
// headerWordWrap
//----------------------------------
/**
* @private
* Storage for the headerWordWrap property.
*/
private var _headerWordWrap:*;
[Inspectable(category=""Advanced"")]
/**
* Set to true to wrap the text in the column header
* if it does not fit on one line.
* If undefined, the AdvancedDataGrid control's wordWrap property
* is used.
* This property overrides the headerWordWrap property of
* the AdvancedDataGrid control.
*
* @default undefined
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public function get headerWordWrap():*
{
return _headerWordWrap;
}
/**
* @private
*/
public function set headerWordWrap(value:*):void
{
_headerWordWrap = value;
/* if (owner)
{
owner.invalidateList();
} */
}
//----------------------------------
// enableIME
//----------------------------------
/**
* A flag that indicates whether the IME should
* be enabled when the component receives focus.
*
* If an editor is up, it will set enableIME
* accordingly.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
/* public function get enableIME():Boolean
{
return false;
} */
//----------------------------------
// imeMode
//----------------------------------
/**
* @private
* Storage for the imeMode property.
*/
/* private var _imeMode:String;
[Inspectable(category=""Other"")] */
/**
* Specifies the IME (input method editor) mode.
* The IME mode enables users to enter text in Chinese, Japanese, and Korean.
* Flex sets the IME mode when the itemFocusIn event occurs,
* and sets it back
* to the previous value when the itemFocusOut event occurs.
* The flash.system.IMEConversionMode class defines constants for
* the valid values for this property.
*
*
The default value is null, in which case it uses the value of the
* AdvancedDataGrid control's imeMode property.
*
* @see flash.system.IMEConversionMode
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function get imeMode():String
{
return _imeMode;
}
*/
/**
* @private
*/
/* public function set imeMode(value:String):void
{
_imeMode = value;
} */
/* //----------------------------------
// resizable
//----------------------------------
[Inspectable(category=""General"")]
/!**
* Set to true if the user is allowed to resize
* the width of the column.
* If true, the user can drag the grid lines between
* the column headers to resize the column.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*!/
public var resizable:Boolean = true;
//----------------------------------
// showDataTips
//----------------------------------
/!**
* @private
* Storage for the showDataTips property.
*!/
private var _showDataTips:*;
[Inspectable(category=""Advanced"")]
/!**
* Set to true to show data tips in the column.
* If true, datatips are displayed for text in the rows. Datatips
* are tooltips designed to show the text that is too long for the row.
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*!/
public function get showDataTips():*
{
return _showDataTips;
}
/!**
* @private
*!/
public function set showDataTips(value:*):void
{
_showDataTips = value;
/!* if (owner)
{
owner.invalidateList();
} *!/
}
//----------------------------------
// sortable
//----------------------------------
[Inspectable(category=""General"")]
/!**
* Set to true to indicate that the user can click on the
* header of this column to sort the data provider.
* If this property and the AdvancedDataGrid sortableColumns property
* are both true, the AdvancedDataGrid control dispatches a
* headerRelease event when a user releases the mouse button
* on this column's header.
* If no other handler calls the preventDefault() method on
* the headerRelease event, the dataField
* property or sortCompareFunction in the column is used
* to reorder the items in the data provider.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*!/
public var sortable:Boolean = true;
//----------------------------------
// sortCompareFunction
//----------------------------------
/!**
* @private
* Storage for the sortCompareFunction property.
*!/
private var _sortCompareFunction:Function;
[Bindable(""sortCompareFunctionChanged"")]
[Inspectable(category=""Advanced"")]
/!**
*
* A callback function that gets called when sorting the data in
* the column. If this property is not specified, the sort tries
* to use a basic string or number sort on the data.
* If the data is not a string or number or if the dataField
* property is not a valid property of the data provider, the sort does
* not work or will generate an exception.
* If you specify a value of the labelFunction property,
* you typically also provide a function to the sortCompareFunction property,
* unless sorting is not allowed on this column.
* That means you specify a function when the value from the column's dataField
* does not sort in the same way as the computed value from the labelFunction property.
*
*
The AdvancedDataGrid control uses this function to sort the elements of the data
* provider collection. The function signature of
* the callback function takes two parameters and has the following form:
The function should return a value based on the comparison
* of the objects:
*
*
-1 if obj1 should appear before obj2 in ascending order.
*
0 if obj1 = obj2.
*
1 if obj1 should appear after obj2 in ascending order.
*
*
*
Note: The obj1 and
* obj2 parameters are entire data provider elements and not
* just the data for the item.
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*!/
public function get sortCompareFunction():Function
{
return _sortCompareFunction;
}
/!**
* @private
*!/
public function set sortCompareFunction(value:Function):void
{
_sortCompareFunction = value;
// dispatchEvent(new Event(""sortCompareFunctionChanged""));
}
*/
//----------------------------------
// sortCompareType
//----------------------------------
/**
* @private
*/
//private var _sortCompareType:String;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 11.8
* @playerversion AIR 3.8
* @productversion Flex 4.11
*/
/* [Bindable(""sortCompareTypeChanged"")]
public function get sortCompareType():String
{
return _sortCompareType;
} */
/**
* @private
*/
/* public function set sortCompareType(value:String):void
{
if (_sortCompareType != value)
{
_sortCompareType = value;
dispatchEvent(new Event(""sortCompareTypeChanged""));
}
} */
/* //----------------------------------
// visible
//----------------------------------
/!**
* @private
* Storage for the visible property.
*!/
private var _visible:Boolean = true;
[Inspectable(category=""General"", defaultValue=""true"")]
/!**
* If true, the column is visible.
* Set to false to hide the column.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*!/
public function get visible():Boolean
{
return _visible;
}
/!**
* @private
*!/
public function set visible(value:Boolean):void
{
if (_visible != value)
{
_visible = value;
if (owner)
{
(owner as AdvancedDataGrid).columnsInvalid();
// columns invisible at init don't get a dataprovider so
// force assignment by faking a dp change
(owner as AdvancedDataGrid).model.dispatchEvent(new Event(""dataProviderChanged""));
//owner.invalidateProperties();
//owner.invalidateSize();
//owner.invalidateList();
}
}
}*/
//----------------------------------
// styleFunction
//----------------------------------
/**
* @private
*/
private var _styleFunction:Function;
/**
* A callback function that is called when rendering each cell.
* The signature of the function should be:
*
*
function myStyleFunction(data:Object, column:AdvancedDataGridColumn):Object
*
*
data - data object associated with the item being rendered.
*
column - AdvancedDataGridColumn instance with
* which the item renderer is associated.
*
*
The return value should be a object with styles as properties
* having the required values.
* For example:
*
*
{ color:0xFF0000, fontWeight:""bold"" }
*
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public function get styleFunction():Function
{
return _styleFunction;
}
/**
* @private
*/
public function set styleFunction(value:Function):void
{
_styleFunction = value;
/* if (owner)
owner.invalidateDisplayList(); */
}
//----------------------------------
// formatter
//----------------------------------
/**
* @private
*/
//private var _formatter:IFormatter;
/**
* An instance of a subclasses of mx.formatters.Formatter.
* The control use this class to format the column text.
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function get formatter():IFormatter
{
return _formatter;
} */
/**
* @private
*/
/* public function set formatter(value:IFormatter):void
{
_formatter = value;
if (owner)
owner.invalidateDisplayList();
} */
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
/* override mx_internal function addStyleToProtoChain(
chain:Object, target:DisplayObject, filterMap:Object = null):Object
{
var parentGrid:AdvancedDataGridBaseEx = owner;
var item:IListItemRenderer = IListItemRenderer(target);
chain = super.addStyleToProtoChain(chain, target);
// If the target data is a AdvancedDataGridColumn and has a data
// field in its data, then it is a header so add the
// AdvancedDataGrid.headerStyleName object to the head of the proto chain.
if (item.data && (item.data is AdvancedDataGridColumn))
{
var s:Object;
var headerStyleName:Object =
parentGrid.getStyle(""headerStyleName"");
if (headerStyleName)
{
if (headerStyleName is String)
{
chain = addStylesToProtoChain(String(headerStyleName), chain, target);
}
if (headerStyleName is CSSStyleDeclaration)
chain = headerStyleName.addStyleToProtoChain(chain, target);
}
headerStyleName = getStyle(""headerStyleName"");
if (headerStyleName)
{
if (headerStyleName is String)
{
chain = addStylesToProtoChain(String(headerStyleName), chain, target);
}
if (headerStyleName is CSSStyleDeclaration)
chain = headerStyleName.addStyleToProtoChain(chain, target);
}
}
// save the current font context
if (!fontPropertiesSet)
{
fontPropertiesSet = true;
saveFontContext(owner ? owner.moduleFactory : null);
}
return chain;
} */
/**
* @private
*/
/* override public function setStyle(styleProp:String, value:*):void
{
fontPropertiesSet = false;
var oldValue:Object = getStyle(styleProp);
var regenerate:Boolean = false;
// If this AdvancedDataGridColumn didn't previously have a factory, defaultFactory, or
// overrides object, then this AdvancedDataGridColumn hasn't been added to the item
// renderers proto chains. In that case, we need to regenerate all the item
// renderers proto chains.
if (factory == null &&
defaultFactory == null &&
!overrides &&
(oldValue !== value)) // must be !==
{
regenerate = true;
}
super.setLocalStyle(styleProp, value);
// The default implementation of setStyle won't always regenerate
// the proto chain when headerStyleName is set, and we need to make sure
// that they are regenerated
if (styleProp == ""headerStyleName"")
{
if (owner)
{
owner.regenerateStyleCache(true);
owner.notifyStyleChangeInChildren(""headerStyleName"", true);
}
return;
}
if (owner)
{
if (regenerate)
{
owner.regenerateStyleCache(true);
}
if (hasFontContextChanged(owner.moduleFactory))
{
owner.columnRendererChanged(this);
}
owner.invalidateList();
}
} */
/**
* @private
*/
/* override public function get specificity():int
{
// Return 10 as there is a sorting mechanism based on specificity now
// and there could be ancestor specificity also!!
return 10;
} */
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
* Internal function to allow the AdvancedDataGrid to set the width of the
* column without locking it as an explicitWidth
mx_internal function setWidth(value:Number):void
{
_width = value;
}
*/
/**
* @private
*
* Apply column's Formatter if present.
*
*/
/* private function applyFormatting(data:String):String
{
if (formatter != null && data != null)
{
var label:String = formatter.format(data);
// Silently ignore formatter errors. For example, errors occur when
// the property corresponding to the dataField is not present in the
// row object i.e. it'll be empty and it's not anybody's fault that
// it's an error.
const mxFormatter:Formatter = formatter as Formatter;
if (mxFormatter && mxFormatter.error)
return null;
return label;
}
else
{
return data;
}
} */
/**
* Returns the String that the item renderer displays for the given data object.
* If the AdvancedDataGridColumn or its AdvancedDataGrid control
* has a non-null labelFunction
* property, it applies the function to the data object.
* Otherwise, the method extracts the contents of the field specified by the
* dataField property, or gets the string value of the data object.
* If the method cannot convert the parameter to a String, it returns a
* single space.
*
* @param data Object to be rendered.
*
* @param withFormatting It true specifies to return
* the String with any formatting applied to it.
*
* @return Displayable String based on the data.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function itemToLabel(data:Object, withFormatting:Boolean=true):String
{
var label:String = itemToLabelWithoutFormatting(data);
if (withFormatting)
return applyFormatting(label);
return label;
} */
/**
* @private
*
* This is the original AdvancedDataGrid.itemToLabel() that has been wrapped with applyFormatting()
*
*/
/* private function itemToLabelWithoutFormatting(data:Object):String
{
var headerInfo:AdvancedDataGridHeaderInfo = owner.mx_internal::getHeaderInfo(this);
// In case of Column grouping, when a column has a parent with dataField/labelFunction set, this column is
// supposed to take value from what its parent supplies it
if (headerInfo != null && headerInfo.internalLabelFunction != null)
data = headerInfo.internalLabelFunction(data, this);
if (!data)
return "" "";
if (labelFunction != null)
return labelFunction(data, this);
if (owner.labelFunction != null)
return owner.labelFunction(data, this);
if (typeof(data) == ""object"" || typeof(data) == ""xml"")
{
if (dataField != null && dataField in data)
data = data[dataField];
else
return "" ""; // stops ""[object Object]"" showing
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return "" "";
} */
/**
* Returns a String that the item renderer displays as the data tip for the given data object,
* based on the dataTipField and dataTipFunction properties.
* If the method cannot convert the parameter to a String, it returns a
* single space.
*
*
This method is for use by developers who are creating subclasses
* of the AdvancedDataGridColumn class.
* It is not for use by application developers.
*
* @param data Object to be rendered.
*
* @return Displayable String based on the data.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
/* public function itemToDataTip(data:Object):String
{
if (dataTipFunction != null)
return dataTipFunction(data);
if (owner.dataTipFunction != null)
return owner.dataTipFunction(data);
// for header items, return the header text
if (data is AdvancedDataGridColumn)
return AdvancedDataGridColumn(data).headerText;
if (typeof(data) == ""object"" || typeof(data) == ""xml"")
{
var field:String = dataTipField;
if (!field)
field = owner.dataTipField;
if (field != null)
{
if (field in data && data[field] != null)
data = data[field];
}
else if (dataField != null)
{
if (dataField in data && data[dataField] != null)
data = data[dataField];
else
data = null;
}
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return "" "";
} */
/**
* @private
*
* Save the current font context to member fields.
*/
/* private function saveFontContext(flexModuleFactory:IFlexModuleFactory):void
{
// Save for hasFontContextChanged()
hasFontContextBeenSaved = true;
var fontName:String = StringUtil.trimArrayElements(getStyle(""fontFamily""), "","");
var fontWeight:String = getStyle(""fontWeight"");
var fontStyle:String = getStyle(""fontStyle"");
var bold:Boolean = fontWeight == ""bold"";
var italic:Boolean = fontStyle == ""italic"";
oldEmbeddedFontContext = (noEmbeddedFonts || !embeddedFontRegistry) ?
null :
embeddedFontRegistry.getAssociatedModuleFactory(
fontName, bold, italic, this, flexModuleFactory,
owner.systemManager);
} */
/**
* @private
* Test if the current font context has changed
* since that last time saveFontContext() was called.
*/
/* mx_internal function hasFontContextChanged(
flexModuleFactory:IFlexModuleFactory):Boolean
{
// If the font has not been saved yet, then return false,
// the font context has not changed.
if (!hasFontContextBeenSaved)
return false;
var fontName:String =
StringUtil.trimArrayElements(getStyle(""fontFamily""), "","");
var fontWeight:String = getStyle(""fontWeight"");
var fontStyle:String = getStyle(""fontStyle"");
// Check if the module factory has changed.
var bold:Boolean = fontWeight == ""bold"";
var italic:Boolean = fontStyle == ""italic"";
var fontContext:IFlexModuleFactory = (noEmbeddedFonts || !embeddedFontRegistry) ?
null :
embeddedFontRegistry.getAssociatedModuleFactory(
fontName, bold, italic, this, flexModuleFactory,
owner.systemManager);
return fontContext != oldEmbeddedFontContext;
} */
/**
* @private
*/
/* private function addStylesToProtoChain(styles:String, chain:Object, target:DisplayObject):Object
{
var styleNames:Array = styles.split(/\\s+/);
for (var c:int=0; c < styleNames.length; c++)
{
if (styleNames[c].length)
{
var declaration:CSSStyleDeclaration =
owner.styleManager.getMergedStyleDeclaration(""."" + styleNames[c]);
if (declaration)
chain = declaration.addStyleToProtoChain(chain, target);
}
}
return chain;
} */
/**
* @private
*
* Sets the properties of this Object to the given column.
*
* It sets only the required properties.
*
* @param col AdvancedDataGridColumn in which the properties are to be set.
*
*/
/* protected function copyProperties(col:AdvancedDataGridColumn):void
{
// copy properties
col.defaultFactory = this.defaultFactory;
col.editable = this.editable;
col.editorDataField = this.editorDataField;
col.editorHeightOffset = this.editorHeightOffset;
col.editorUsesEnterKey = this.editorUsesEnterKey;
col.editorWidthOffset = this.editorWidthOffset;
col.editorXOffset = this.editorXOffset;
col.editorYOffset = this.editorYOffset;
col.factory = this.factory;
col.itemEditor = this.itemEditor;
col.rendererIsEditor = this.rendererIsEditor;
col.resizable = this.resizable;
col.sortable = this.sortable;
col.sortDescending = this.sortDescending;
col.dataField = this.dataField;
col.dataTipField = this.dataTipField;
col.dataTipFunction = this.dataTipFunction;
col.formatter = this.formatter;
col.headerRenderer = this.headerRenderer;
col.headerText = this.headerText;
col.headerWordWrap = this.headerWordWrap;
col.imeMode = this.imeMode;
col.itemRenderer = this.itemRenderer;
col.labelFunction = this.labelFunction;
col.minWidth = this.minWidth;
col.showDataTips = this.showDataTips;
col.sortCompareFunction = this.sortCompareFunction;
col.styleFunction = this.styleFunction;
col.visible = this.visible;
col.width = this.width;
col.wordWrap = this.wordWrap;
// copy styles
col.public::setStyle(""backgroundColor"",this.getStyle(""backgroundColor""));
col.public::setStyle(""headerStyleName"",this.getStyle(""headerStyleName""));
col.public::setStyle(""paddingLeft"",this.getStyle(""paddingLeft""));
col.public::setStyle(""paddingRight"",this.getStyle(""paddingRight""));
// copy text styles
col.public::setStyle(""color"",this.getStyle(""color""));
col.public::setStyle(""disabledColor"",this.getStyle(""disabledColor""));
col.public::setStyle(""fontAntiAliasType"",this.getStyle(""fontAntiAliasType""));
col.public::setStyle(""fontFamily"",this.getStyle(""fontFamily""));
col.public::setStyle(""fontGridFitType"",this.getStyle(""fontGridFitType""));
col.public::setStyle(""fontSharpness"",this.getStyle(""fontSharpness""));
col.public::setStyle(""fontSize"",this.getStyle(""fontSize""));
col.public::setStyle(""fontStyle"",this.getStyle(""fontStyle""));
col.public::setStyle(""fontThickness"",this.getStyle(""fontThickness""));
col.public::setStyle(""fontWeight"",this.getStyle(""fontWeight""));
col.public::setStyle(""kerning"",this.getStyle(""kerning""));
col.public::setStyle(""letterSpacing"",this.getStyle(""letterSpacing""));
col.public::setStyle(""textAlign"",this.getStyle(""textAlign""));
col.public::setStyle(""textDecoration"",this.getStyle(""textDecoration""));
col.public::setStyle(""textIndent"",this.getStyle(""textIndent""));
} */
/**
*
* Clone this column and return a new Column with the
* same properties and styles as this one.
*
* It does not set all the available properties
*
* @return col AdvancedDataGridColumn.
*
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.3
*/
public function clone():AdvancedDataGridColumn
{
// make a new column
var col:AdvancedDataGridColumn = new AdvancedDataGridColumn();
// copy the properties
//copyProperties(col);
return col;
}
}
}
",12450,True,2639.4201577096264,median
"// Use these for links to issue and pulls. Note issues and pulls redirect one to
// each other on Github, so don't worry too much on using the right prefix.
:issue: https://github.com/elastic/beats/issues/
:pull: https://github.com/elastic/beats/pull/
=== Beats version HEAD
https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff]
==== Breaking changes
*Affecting all Beats*
- Update to Golang 1.12.1. {pull}11330[11330]
- Update to Golang 1.12.4. {pull}11782[11782]
- Update to ECS 1.0.1. {pull}12284[12284] {pull}12317[12317]
- Default of output.kafka.metadata.full is set to false by now. This reduced the amount of metadata to be queried from a kafka cluster. {pull}12738[12738]
- Fixed a crash under Windows when fetching processes information. {pull}12833[12833]
- Update to Golang 1.12.7. {pull}12931[12931]
- Remove `in_cluster` configuration parameter for Kuberentes, now in-cluster configuration is used only if no other kubeconfig is specified {pull}13051[13051]
- Disable Alibaba Cloud and Tencent Cloud metadata providers by default. {pull}13812[12812]
- Libbeat HTTP's Server can listen to a unix socket using the `unix:///tmp/hello.sock` syntax. {pull}13655[13655]
- Libbeat HTTP's Server can listen to a Windows named pipe using the `npipe:///hello` syntax. {pull}13655[13655]
- By default, all Beats-created files and folders will have a umask of 0027 (on POSIX systems). {pull}14119[14119]
- Adding new `Enterprise` license type to the licenser. {issue}14246[14246]
- Change wording when we fail to load a CA file to the cert pool. {issue}14309[14309]
- Allow Metricbeat's beat module to read monitoring information over a named pipe or unix domain socket. {pull}14558[14558]
- Remove version information from default ILM policy for improved upgrade experience on custom policies. {pull}14745[14745]
- Running `setup` cmd respects `setup.ilm.overwrite` setting for improved support of custom policies. {pull}14741[14741]
- Libbeat: Do not overwrite agent.*, ecs.version, and host.name. {pull}14407[14407]
*Auditbeat*
- Auditd module: Normalized value of `event.category` field from `user-login` to `authentication`. {pull}11432[11432]
- Auditd module: Unset `auditd.session` and `user.audit.id` fields are removed from audit events. {issue}11431[11431] {pull}11815[11815]
- Socket dataset: Exclude localhost by default {pull}11993[11993]
- Socket dataset: New implementation using Kprobes for finer-grained monitoring and UDP support. {pull}13058[13058]
*Filebeat*
- Add Filebeat Azure Dashboards {pull}14127[14127]
- Add read_buffer configuration option. {pull}11739[11739]
- `convert_timezone` option is removed and locale is always added to the event so timezone is used when parsing the timestamp, this behaviour can be overriden with processors. {pull}12410[12410]
- Fix a race condition in the TCP input when close the client socket. {pull}13038[13038]
- cisco/asa fileset: Renamed log.original to event.original and cisco.asa.list_id to cisco.asa.rule_name. {pull}13286[13286]
- cisco/asa fileset: Fix parsing of 302021 message code. {pull}13476[13476]
- google pubsub & httpjson inputs: HTTP User agent is now `Elastic-Heartbeat/Version` instead of `Elastic Heartbeat/Version` to stay RFC compliant. {pull}14748[14748]
- CEF extensions are now mapped to the data types defined in the CEF guide. {pull}14342[14342]
- Remove --machine-learning from setup subcommand. {pull}14705[14705]
*Heartbeat*
- Removed the `add_host_metadata` and `add_cloud_metadata` processors from the default config. These don't fit well with ECS for Heartbeat and were rarely used.
- Fixed/altered redirect behavior. `max_redirects` now defaults to 0 (no redirects). Following redirects now works across hosts, but some timing fields will not be reported. {pull}14125[14125]
- Removed `host.name` field that should never have been included. Heartbeat uses `observer.*` fields instead. {pull}14140[14140]
- Changed default user-agent to be `Elastic-Heartbeat/VERSION (PLATFORM_INFO)` as the current default `Go-http-client/1.1` is often blacklisted. {pull}14291[14291]
- JSON/Regex checks against HTTP bodies will only consider the first 100MiB of the HTTP body to prevent excessive memory usage. {pull}14223[pull]
- Heartbeat now starts monitors scheduled with the '@every X' syntax instantaneously on startup, rather than waiting for the given interval to pass before running them. {pull}14890[14890]
*Journalbeat*
*Metricbeat*
- Add new dashboards for Azure vms, vm guest metrics, vm scale sets {pull}14000[14000]
- Add new Dashboard for PostgreSQL database stats {pull}13187[13187]
- Add new dashboard for CouchDB database {pull}13198[13198]
- Add new dashboard for Ceph cluster stats {pull}13216[13216]
- Add new dashboard for Aerospike database stats {pull}13217[13217]
- Add new dashboard for Couchbase cluster stats {pull}13212[13212]
- Add new dashboard for Prometheus server stats {pull}13126[13126]
- Add new dashboard for VSphere host cluster and virtual machine {pull}14135[14135]
- Add new option `OpMultiplyBuckets` to scale histogram buckets to avoid decimal points in final events {pull}10994[10994]
- system/raid metricset now uses /sys/block instead of /proc/mdstat for data. {pull}11613[11613]
- kubernetes.container.cpu.limit.cores and kubernetes.container.cpu.requests.cores are now floats. {issue}11975[11975]
- Add statistic option into cloudwatch metricset. If there is no statistic method specified, default is to collect Average, Sum, Maximum, Minimum and SampleCount. {issue}12370[12370] {pull}12840[12840]
*Packetbeat*
- Add support for mongodb opcode 2013 (OP_MSG). {issue}6191[6191] {pull}8594[8594]
- NFSv4: Always use opname `ILLEGAL` when failed to match request to a valid nfs operation. {pull}11503[11503]
*Winlogbeat*
*Functionbeat*
- Separate management and functions in Functionbeat. {pull}12939[12939]
==== Bugfixes
*Affecting all Beats*
- Make the behavior of clientWorker and netClientWorker consistent when error is returned from publisher pipeline
- Fix a bug, publisher pipeline exits if output returns an error, irrespective of pipeline is closed or not
- Fix typo in TLS renegotiation configuration and setting the option correctly {issue}10871[10871], {pull}12354[12354]
- Ensure all beat commands respect configured settings. {pull}10721[10721]
- Add missing fields and test cases for libbeat add_kubernetes_metadata processor. {issue}11133[11133], {pull}11134[11134]
- decode_json_field: process objects and arrays only {pull}11312[11312]
- decode_json_field: do not process arrays when flag not set. {pull}11318[11318]
- Report faulting file when config reload fails. {pull}11304[11304]
- Fix a typo in libbeat/outputs/transport/client.go by updating `c.conn.LocalAddr()` to `c.conn.RemoteAddr()`. {pull}11242[11242]
- Management configuration backup file will now have a timestamps in their name. {pull}11034[11034]
- [CM] Parse enrollment_token response correctly {pull}11648[11648]
- Not hiding error in case of http failure using elastic fetcher {pull}11604[11604]
- Escape BOM on JsonReader before trying to decode line {pull}11661[11661]
- Fix matching of string arrays in contains condition. {pull}11691[11691]
- Replace wmi queries with win32 api calls as they were consuming CPU resources {issue}3249[3249] and {issue}11840[11840]
- Fix a race condition with the Kafka pipeline client, it is possible that `Close()` get called before `Connect()` . {issue}11945[11945]
- Fix queue.spool.write.flush.events config type. {pull}12080[12080]
- Fixed a memory leak when using the add_process_metadata processor under Windows. {pull}12100[12100]
- Fix of docker json parser for missing ""log"" jsonkey in docker container's log {issue}11464[11464]
- Fixed Beat ID being reported by GET / API. {pull}12180[12180]
- Fixed setting bulk max size in kafka output. {pull}12254[12254]
- Add host.os.codename to fields.yml. {pull}12261[12261]
- Fix `@timestamp` being duplicated in events if `@timestamp` is set in a
processor (or by any code utilizing `PutValue()` on a `beat.Event`).
- Fix leak in script processor when using Javascript functions in a processor chain. {pull}12600[12600]
- Add additional nil pointer checks to Docker client code to deal with vSphere Integrated Containers {pull}12628[12628]
- Fixed `json.add_error_key` property setting for delivering error messages from beat events {pull}11298[11298]
- Fix Central Management enroll under Windows {issue}12797[12797] {pull}12799[12799]
- ILM: Use GET instead of HEAD when checking for alias to expose detailed error message. {pull}12886[12886]
- Fix seccomp policy preventing some features to function properly on 32bit Linux systems. {issue}12990[12990] {pull}13008[13008]
- Fix unexpected stops on docker autodiscover when a container is restarted before `cleanup_timeout`. {issue}12962[12962] {pull}13127[13127]
- Fix install-service.ps1's ability to set Windows service's delay start configuration. {pull}13173[13173]
- Fix some incorrect types and formats in field.yml files. {pull}13188[13188]
- Load DLLs only from Windows system directory. {pull}13234[13234] {pull}13384[13384]
- Fix mapping for kubernetes.labels and kubernetes.annotations in add_kubernetes_metadata. {issue}12638[12638] {pull}13226[13226]
- Fix case insensitive regular expressions not working correctly. {pull}13250[13250]
- Disable `add_kubernetes_metadata` if no matchers found. {pull}13709[13709]
- Better wording for xpack beats when the _xpack endpoint is not reachable. {pull}13771[13771]
- Recover from panics in the javascript process and log details about the failure to aid in future debugging. {pull}13690[13690]
- Make the script processor concurrency-safe. {issue}13690[13690] {pull}13857[13857]
- Kubernetes watcher at `add_kubernetes_metadata` fails with StatefulSets {pull}13905[13905]
- Fix panics that could result from invalid TLS certificates. This can affect Beats that connect over
TLS or Beats that accept connections over TLS and validate client certificates. {pull}14146[14146]
- Support usage of custom builders without hints and mappers {pull}13839[13839]
- Fix memory leak in kubernetes autodiscover provider and add_kubernetes_metadata processor happening when pods are terminated without sending a delete event. {pull}14259[14259]
- Fix kubernetes `metaGenerator.ResourceMetadata` when parent reference controller is nil {issue}14320[14320] {pull}14329[14329]
- Allow users to configure only `cluster_uuid` setting under `monitoring` namespace. {pull}14338[14338]
- Fix bug with potential concurrent reads and writes from event.Meta map by Kafka output. {issue}14542[14542] {pull}14568[14568]
*Auditbeat*
- Process dataset: Fixed a memory leak under Windows. {pull}12100[12100]
- Login dataset: Fix re-read of utmp files. {pull}12028[12028]
- Package dataset: Fixed a crash inside librpm after Auditbeat has been running for a while. {issue}12147[12147] {pull}12168[12168]
- Fix formatting of config files on macOS and Windows. {pull}12148[12148]
- Fix direction of incoming IPv6 sockets. {pull}12248[12248]
- Package dataset: Close librpm handle. {pull}12215[12215]
- Package dataset: Auto-detect package directories. {pull}12289[12289]
- Package dataset: Improve dpkg parsing. {pull}12325[12325]
- System module: Start system module without host ID. {pull}12373[12373]
- Host dataset: Fix reboot detection logic. {pull}12591[12591]
- Add syscalls used by librpm for the system/package dataset to the default Auditbeat seccomp policy. {issue}12578[12578] {pull}12617[12617]
- Process dataset: Do not show non-root warning on Windows. {pull}12740[12740]
- Host dataset: Export Host fields to gob encoder. {pull}12940[12940]
- Socket dataset: Fix start errors when IPv6 is disabled on the kernel. {issue}13953[13953] {pull}13966[13966]
*Filebeat*
- Add support for Cisco syslog format used by their switch. {pull}10760[10760]
- Cover empty request data, url and version in Apache2 module{pull}10730[10730]
- Fix registry entries not being cleaned due to race conditions. {pull}10747[10747]
- Improve detection of file deletion on Windows. {pull}10747[10747]
- Add missing Kubernetes metadata fields to Filebeat CoreDNS module, and fix a documentation error. {pull}11591[11591]
- Reduce memory usage if long lines are truncated to fit `max_bytes` limit. The line buffer is copied into a smaller buffer now. This allows the runtime to release unused memory earlier. {pull}11524[11524]
- Fix memory leak in Filebeat pipeline acker. {pull}12063[12063]
- Fix goroutine leak caused on initialization failures of log input. {pull}12125[12125]
- Fix goroutine leak on non-explicit finalization of log input. {pull}12164[12164]
- Skipping unparsable log entries from docker json reader {pull}12268[12268]
- Parse timezone in PostgreSQL logs as part of the timestamp {pull}12338[12338]
- Load correct pipelines when system module is configured in modules.d. {pull}12340[12340]
- Fix timezone offset parsing in system/syslog. {pull}12529[12529]
- When TLS is configured for the TCP input and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584]
- Apply `max_message_size` to incoming message buffer. {pull}11966[11966]
- Syslog input will now omit the `process` object from events if it is empty. {pull}12700[12700]
- Fix multiline pattern in Postgres which was too permissive {issue}12078[12078] {pull}13069[13069]
- Allow path variables to be used in files loaded from modules.d. {issue}13184[13184]
- Fix filebeat autodiscover fileset hint for container input. {pull}13296[13296]
- Fix incorrect references to index patterns in AWS and CoreDNS dashboards. {pull}13303[13303]
- Fix timezone parsing of system module ingest pipelines. {pull}13308[13308]
- Fix timezone parsing of elasticsearch module ingest pipelines. {pull}13367[13367]
- Change iis url path grok pattern from URIPATH to NOTSPACE. {issue}12710[12710] {pull}13225[13225] {issue}7951[7951] {pull}13378[13378] {pull}14754[14754]
- Fix timezone parsing of nginx module ingest pipelines. {pull}13369[13369]
- Fix incorrect field references in envoyproxy dashboard {issue}13420[13420] {pull}13421[13421]
- Fixed early expiration of templates (Netflow v9 and IPFIX). {pull}13821[13821]
- Fixed bad handling of sequence numbers when multiple observation domains were exported by a single device (Netflow V9 and IPFIX). {pull}13821[13821]
- Fix timezone parsing of rabbitmq module ingest pipelines. {pull}13879[13879]
- Fix conditions and error checking of date processors in ingest pipelines that use `event.timezone` to parse dates. {pull}13883[13883]
- Fix timezone parsing of Cisco module ingest pipelines. {pull}13893[13893]
- Fix timezone parsing of logstash module ingest pipelines. {pull}13890[13890]
- cisco asa and ftd filesets: Fix parsing of message 106001. {issue}13891[13891] {pull}13903[13903]
- Fix timezone parsing of iptables, mssql and panw module ingest pipelines. {pull}13926[13926]
- Fix merging of fields specified in global scope with fields specified under an input's scope. {issue}3628[3628] {pull}13909[13909]
- Fix delay in enforcing close_renamed and close_removed options. {issue}13488[13488] {pull}13907[13907]
- Fix missing netflow fields in index template. {issue}13768[13768] {pull}13914[13914]
- Fix cisco module's asa and ftd filesets parsing of domain names where an IP address is expected. {issue}14034[14034]
- Fixed increased memory usage with large files when multiline pattern does not match. {issue}14068[14068]
- panw module: Use geo.name instead of geo.country_iso_code for free-form location. {issue}13272[13272]
- Fix azure fields names. {pull}14098[14098]
- Fix calculation of `network.bytes` and `network.packets` for bi-directional netflow events. {pull}14111[14111]
- Accept '-' as http.response.body.bytes in apache module. {pull}14137[14137]
- Fix timezone parsing of MySQL module ingest pipelines. {pull}14130[14130]
- Improve error message in s3 input when handleSQSMessage failed. {pull}14113[14113]
- Close chan of Closer first before calling callback {pull}14231[14231]
- Fix race condition in S3 input plugin. {pull}14359[14359]
- Decode hex values in auditd module. {pull}14471[14471]
- Fix parse of remote addresses that are not IPs in nginx logs. {pull}14505[14505]
- Fix handling multiline log entries in nginx module. {issue}14349[14349] {pull}14499[14499]
- Fix parsing of Elasticsearch node name by `elasticsearch/slowlog` fileset. {pull}14547[14547]
- cisco/asa fileset: Fix parsing of 302021 message code. {pull}14519[14519]
- Fix filebeat azure dashboards, event category should be `Alert`. {pull}14668[14668]
- Update Logstash module's Grok patterns to support Logstash 7.4 logs. {pull}14743[14743]
- Fix a problem in Filebeat input httpjson where interval is not used as time.Duration. {issue}14752[14752] {pull}14753[14753]
- Fix SSL config in input.yml for Filebeat httpjson input in the MISP module. {pull}14767[14767]
*Heartbeat*
- Fix NPEs / resource leaks when executing config checks. {pull}11165[11165]
- Fix duplicated IPs on `mode: all` monitors. {pull}12458[12458]
- Fix integer comparison on JSON responses. {pull}13348[13348]
- Fix storage of HTTP bodies to work when JSON/Regex body checks are enabled. {pull}14223[14223]
- Fix recording of SSL cert metadata for Expired/Unvalidated x509 certs. {pull}13687[13687]
- The heartbeat scheduler no longer drops scheduled items when under very high load causing missed deadlines. {pull}14890[14890]
*Journalbeat*
- Use backoff when no new events are found. {pull}11861[11861]
- Iterate over journal correctly, so no duplicate entries are sent. {pull}12716[12716]
- Preserve host name when reading from remote journal. {pull}12714[12714]
*Metricbeat*
- Change diskio metrics retrieval method (only for Windows) from wmi query to DeviceIOControl function using the IOCTL_DISK_PERFORMANCE control code {pull}11635[11635]
- Call GetMetricData api per region instead of per instance. {issue}11820[11820] {pull}11882[11882]
- Update documentation with cloudwatch:ListMetrics permission. {pull}11987[11987]
- Check permissions in system socket metricset based on capabilities. {pull}12039[12039]
- Get process information from sockets owned by current user when system socket metricset is run without privileges. {pull}12039[12039]
- Avoid generating hints-based configuration with empty hosts when no exposed port is suitable for the hosts hint. {issue}8264[8264] {pull}12086[12086]
- Fixed a socket leak in the postgresql module under Windows when SSL is disabled on the server. {pull}11393[11393]
- Change some field type from scaled_float to long in aws module. {pull}11982[11982]
- Fixed RabbitMQ `queue` metricset gathering when `consumer_utilisation` is set empty at the metrics source {pull}12089[12089]
- Fix direction of incoming IPv6 sockets. {pull}12248[12248]
- Refactored Windows perfmon metricset: replaced method to retrieve counter paths with PdhExpandWildCardPathW, separated code by responsibility, removed unused functions {pull}12212[12212]
- Validate that kibana/status metricset cannot be used when xpack is enabled. {pull}12264[12264]
- Ignore prometheus metrics when their values are NaN or Inf. {pull}12084[12084] {issue}10849[10849]
- In the kibana/stats metricset, only log error (don't also index it) if xpack is enabled. {pull}12265[12265]
- Fix an issue listing all processes when run under Windows as a non-privileged user. {issue}12301[12301] {pull}12475[12475]
- The `elasticsearch/index_summary` metricset gracefully handles an empty Elasticsearch cluster when `xpack.enabled: true` is set. {pull}12489[12489] {issue}12487[12487]
- When TLS is configured for the http metricset and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584]
- Reuse connections in PostgreSQL metricsets. {issue}12504[12504] {pull}12603[12603]
- PdhExpandWildCardPathW will not expand counter paths in 32 bit windows systems, workaround will use a different function. {issue}12590[12590] {pull}12622[12622]
- In the elasticsearch/node_stats metricset, if xpack is enabled, make parsing of ES node load average optional as ES on Windows doesn't report load average. {pull}12866[12866]
- Ramdisk is not filtered out when collecting disk performance counters in diskio metricset {issue}12814[12814] {pull}12829[12829]
- Fix incoherent behaviour in redis key metricset when keyspace is specified both in host URL and key pattern {pull}12913[12913]
- Fix connections leak in redis module {pull}12914[12914] {pull}12950[12950]
- Fix wrong uptime reporting by system/uptime metricset under Windows. {pull}12915[12915]
- Print errors that were being omitted in vSphere metricsets. {pull}12816[12816]
- Fix redis key metricset dashboard references to index pattern. {pull}13303[13303]
- Check if fields in DBInstance is nil in rds metricset. {pull}13294[13294] {issue}13037[13037]
- Fix silent failures in kafka and prometheus module. {pull}13353[13353] {issue}13252[13252]
- Fix issue with aws cloudwatch module where dimensions and/or namespaces that contain space are not being parsed correctly {pull}13389[13389]
- Fix panic in Redis Key metricset when collecting information from a removed key. {pull}13426[13426]
- Fix module-level fields in Kubernetes metricsets. {pull}13433[13433] {pull}13544[13544]
- Fix reporting empty events in cloudwatch metricset. {pull}13458[13458]
- Fix `docker.cpu.system.pct` calculation by using the reported number online cpus instead of the number of metrics per cpu. {pull}13691[13691]
- Fix rds metricset dashboard. {pull}13721[13721]
- Ignore prometheus untyped metrics with NaN value. {issue}13750[13750] {pull}13790[13790]
- Change kubernetes.event.message to text. {pull}13964[13964]
- Fix performance counter values for windows/perfmon metricset. {issue}14036[14036] {pull}14039[14039]
- Add FailOnRequired when applying schema and fix metric names in mongodb metrics metricset. {pull}14143[14143]
- Change `server_status_path` default setting for nginx module {issue}13806[13806] {pull}14099[14099]
- Convert increments of 100 nanoseconds/ticks to milliseconds for WriteTime and ReadTime in diskio metricset (Windows) for consistency. {issue}14233[14233]
- Limit some of the error messages to the logs only {issue}14317[14317] {pull}14327[14327]
- Convert indexed ms-since-epoch timestamp fields in `elasticsearch/ml_job` metricset to ints from float64s. {issue}14220[14220] {pull}14222[14222]
- Fix ARN parsing function to work for ELB ARNs. {pull}14316[14316]
- Update azure configuration example. {issue}14224[14224]
- Fix cloudwatch metricset with names and dimensions in config. {issue}14376[14376] {pull}14391[14391]
- Fix marshaling of ms-since-epoch values in `elasticsearch/cluster_stats` metricset. {pull}14378[14378]
- Fix checking tagsFilter using length in cloudwatch metricset. {pull}14525[14525]
- Log bulk failures from bulk API requests to monitoring cluster. {issue}14303[14303] {pull}14356[14356]
- Fixed bug with `elasticsearch/cluster_stats` metricset not recording license expiration date correctly. {issue}14541[14541] {pull}14591[14591]
- Fix regular expression to detect instance name in perfmon metricset. {issue}14273[14273] {pull}14666[14666]
- Vshpere module splits `virtualmachine.host` into `virtualmachine.host.id` and `virtualmachine.host.hostname`. {issue}7187[7187] {pull}7213[7213]
- Fixed bug with `elasticsearch/cluster_stats` metricset not recording license ID in the correct field. {pull}14592[14592]
- Fix perfmon expanding counter path/adding counter to query when OS language is not english. {issue}14684[14684] {pull}14800[14800]
- Add extra check on `ignore_non_existent_counters` flag if the PdhExpandWildCardPathW returns no errors but does not expand the counter path successfully in windows/perfmon metricset. {pull}14797[14797]
- Fix rds metricset from reporting same values for different instances. {pull}14702[14702]
- Closing handler after verifying the registry key in diskio metricset. {issue}14683[14683] {pull}14759[14759]
- Fix docker network stats when multiple interfaces are configured. {issue}14586[14586] {pull}14825[14825]
- Fix ListMetrics pagination in aws module. {issue}14926[14926] {pull}14942[14942]
*Packetbeat*
- Prevent duplicate packet loss error messages in HTTP events. {pull}10709[10709]
- Fixed a memory leak when using process monitoring under Windows. {pull}12100[12100]
- Improved debug logging efficiency in PGQSL module. {issue}12150[12150]
- Limit memory usage of Redis replication sessions. {issue}12657[12657]
- Fix parsing the extended RCODE in the DNS parser. {pull}12805[12805]
- Fix parsing of the HTTP host header when it contains a port or an IPv6 address. {pull}14215[14215]
*Winlogbeat*
- Fix data race affecting config validation at startup. {issue}13005[13005]
- Set host.name to computername in Windows event logs & sysmon. Requires {pull}14407[14407] in libbeat to work {issue}13706[13706]
*Functionbeat*
- Fix function name reference for Kinesis streams in CloudFormation templates {pull}11646[11646]
- Fix Cloudwatch logs timestamp to use timestamp of the log record instead of when the record was processed {pull}13291[13291]
- Look for the keystore under the correct path. {pull}13332[13332]
==== Added
*Affecting all Beats*
- Decouple Debug logging from fail_on_error logic for rename, copy, truncate processors {pull}12451[12451]
- Add an option to append to existing logs rather than always rotate on start. {pull}11953[11953]
- Add `network` condition to processors for matching IP addresses against CIDRs. {pull}10743[10743]
- Add if/then/else support to processors. {pull}10744[10744]
- Add `community_id` processor for computing network flow hashes. {pull}10745[10745]
- Add output test to kafka output {pull}10834[10834]
- Gracefully shut down on SIGHUP {pull}10704[10704]
- New processor: `copy_fields`. {pull}11303[11303]
- Add `error.message` to events when `fail_on_error` is set in `rename` and `copy_fields` processors. {pull}11303[11303]
- New processor: `truncate_fields`. {pull}11297[11297]
- Allow a beat to ship monitoring data directly to an Elasticsearch monitoring cluster. {pull}9260[9260]
- Updated go-seccomp-bpf library to v1.1.0 which updates syscall lists for Linux v5.0. {pull}11394[11394]
- Add `add_observer_metadata` processor. {pull}11394[11394]
- Add `decode_csv_fields` processor. {pull}11753[11753]
- Add `convert` processor for converting data types of fields. {issue}8124[8124] {pull}11686[11686]
- New `extract_array` processor. {pull}11761[11761]
- Add number of goroutines to reported metrics. {pull}12135[12135]
- Add `proxy_disable` output flag to explicitly ignore proxy environment variables. {issue}11713[11713] {pull}12243[12243]
- Processor `add_cloud_metadata` adds fields `cloud.account.id` and `cloud.image.id` for AWS EC2. {pull}12307[12307]
- Add configurable bulk_flush_frequency in kafka output. {pull}12254[12254]
- Add `decode_base64_field` processor for decoding base64 field. {pull}11914[11914]
- Add support for reading the `network.iana_number` field by default to the community_id processor. {pull}12701[12701]
- Add aws overview dashboard. {issue}11007[11007] {pull}12175[12175]
- Add `decompress_gzip_field` processor. {pull}12733[12733]
- Add `timestamp` processor for parsing time fields. {pull}12699[12699]
- Fail with error when autodiscover providers have no defined configs. {pull}13078[13078]
- Add a check so alias creation explicitely fails if there is an index with the same name. {pull}13070[13070]
- Update kubernetes watcher to use official client-go libraries. {pull}13051[13051]
- Add support for unix epoch time values in the `timestamp` processor. {pull}13319[13319]
- add_host_metadata is now GA. {pull}13148[13148]
- Add an `ignore_missing` configuration option the `drop_fields` processor. {pull}13318[13318]
- add_host_metadata is no GA. {pull}13148[13148]
- Add `registered_domain` processor for deriving the registered domain from a given FQDN. {pull}13326[13326]
- Add support for RFC3339 time zone offsets in JSON output. {pull}13227[13227]
- Add autodetection mode for add_docker_metadata and enable it by default in included configuration files{pull}13374[13374]
- Added `monitoring.cluster_uuid` setting to associate Beat data with specified ES cluster in Stack Monitoring UI. {pull}13182[13182]
- Add autodetection mode for add_kubernetes_metadata and enable it by default in included configuration files. {pull}13473[13473]
- Add `providers` setting to `add_cloud_metadata` processor. {pull}13812[13812]
- Use less restrictive API to check if template exists. {pull}13847[13847]
- Do not check for alias when setup.ilm.check_exists is false. {pull}13848[13848]
- Add support for numeric time zone offsets in timestamp processor. {pull}13902[13902]
- Add condition to the config file template for add_kubernetes_metadata {pull}14056[14056]
- Marking Central Management deprecated. {pull}14018[14018]
- Add `keep_null` setting to allow Beats to publish null values in events. {issue}5522[5522] {pull}13928[13928]
- Add shared_credential_file option in aws related config for specifying credential file directory. {issue}14157[14157] {pull}14178[14178]
- GA the `script` processor. {pull}14325[14325]
- Add `fingerprint` processor. {issue}11173[11173] {pull}14205[14205]
- Add support for API keys in Elasticsearch outputs. {pull}14324[14324]
- Ensure that init containers are no longer tailed after they stop {pull}14394[14394]
- Add consumer_lag in Kafka consumergroup metricset {pull}14822[14822]
- Make use of consumer_lag in Kafka dashboard {pull}14863[14863]
- Refactor kubernetes autodiscover to enable different resource based discovery {pull}14738[14738]
*Auditbeat*
- Auditd module: Add `event.outcome` and `event.type` for ECS. {pull}11432[11432]
- Process: Add file hash of process executable. {pull}11722[11722]
- Socket: Add network.transport and network.community_id. {pull}12231[12231]
- Host: Fill top-level host fields. {pull}12259[12259]
- Socket: Add DNS enrichment. {pull}14004[14004]
*Filebeat*
- Add more info to message logged when a duplicated symlink file is found {pull}10845[10845]
- Add option to configure docker input with paths {pull}10687[10687]
- Add Netflow module to enrich flow events with geoip data. {pull}10877[10877]
- Set `event.category: network_traffic` for Suricata. {pull}10882[10882]
- Allow custom default settings with autodiscover (for example, use of CRI paths for logs). {pull}12193[12193]
- Allow to disable hints based autodiscover default behavior (fetching all logs). {pull}12193[12193]
- Change Suricata module pipeline to handle `destination.domain` being set if a reverse DNS processor is used. {issue}10510[10510]
- Add the `network.community_id` flow identifier to field to the IPTables, Suricata, and Zeek modules. {pull}11005[11005]
- New Filebeat coredns module to ingest coredns logs. It supports both native coredns deployment and coredns deployment in kubernetes. {pull}11200[11200]
- New module for Cisco ASA logs. {issue}9200[9200] {pull}11171[11171]
- Added support for Cisco ASA fields to the netflow input. {pull}11201[11201]
- Configurable line terminator. {pull}11015[11015]
- Add Filebeat envoyproxy module. {pull}11700[11700]
- Add apache2(httpd) log path (`/var/log/httpd`) to make apache2 module work out of the box on Redhat-family OSes. {issue}11887[11887] {pull}11888[11888]
- Add support to new MongoDB additional diagnostic information {pull}11952[11952]
- New module `panw` for Palo Alto Networks PAN-OS logs. {pull}11999[11999]
- Add RabbitMQ module. {pull}12032[12032]
- Add new `container` input. {pull}12162[12162]
- Add timeouts on communication with docker daemon. {pull}12310[12310]
- `container` and `docker` inputs now support reading of labels and env vars written by docker JSON file logging driver. {issue}8358[8358]
- Add specific date processor to convert timezones so same pipeline can be used when convert_timezone is enabled or disabled. {pull}12253[12253]
- Add MSSQL module {pull}12079[12079]
- Add ISO8601 date parsing support for system module. {pull}12568[12568] {pull}12578[12579]
- Update Kubernetes deployment manifest to use `container` input. {pull}12632[12632]
- Use correct OS path separator in `add_kubernetes_metadata` to support Windows nodes. {pull}9205[9205]
- Add support for virtual host in Apache access logs {pull}12778[12778]
- Add support for client addresses with port in Apache error logs {pull}12695[12695]
- Add `google-pubsub` input type for consuming messages from a Google Cloud Pub/Sub topic subscription. {pull}12746[12746]
- Add module for ingesting Cisco IOS logs over syslog. {pull}12748[12748]
- Add module for ingesting Google Cloud VPC flow logs. {pull}12747[12747]
- Report host metadata for Filebeat logs in Kubernetes. {pull}12790[12790]
- Add netflow dashboards based on Logstash netflow. {pull}12857[12857]
- Parse more fields from Elasticsearch slowlogs. {pull}11939[11939]
- Update module pipelines to enrich events with autonomous system fields. {pull}13036[13036]
- Add module for ingesting IBM MQ logs. {pull}8782[8782]
- Add S3 input to retrieve logs from AWS S3 buckets. {pull}12640[12640] {issue}12582[12582]
- Add aws module s3access metricset. {pull}13170[13170] {issue}12880[12880]
- Update Suricata module to populate ECS DNS fields and handle EVE DNS version 2. {issue}13320[13320] {pull}13329[13329]
- Update PAN-OS fileset to use the ECS NAT fields. {issue}13320[13320] {pull}13330[13330]
- Add fields to the Zeek DNS fileset for ECS DNS. {issue}13320[13320] {pull}13324[13324]
- Add container image in Kubernetes metadata {pull}13356[13356] {issue}12688[12688]
- Add timezone information to apache error fileset. {issue}12772[12772] {pull}13304[13304]
- Add module for ingesting Cisco FTD logs over syslog. {pull}13286[13286]
- Update CoreDNS module to populate ECS DNS fields. {issue}13320[13320] {pull}13505[13505]
- Parse query steps in PostgreSQL slowlogs. {issue}13496[13496] {pull}13701[13701]
- Add filebeat azure module with activitylogs, auditlogs, signinlogs filesets. {pull}13776[13776] {pull}14033[14033]
- Add support to set the document id in the json reader. {pull}5844[5844]
- Add input httpjson. {issue}13545[13545] {pull}13546[13546]
- Filebeat Netflow input: Remove beta label. {pull}13858[13858]
- Remove `event.timezone` from events that don't need it in some modules that support log formats with and without timezones. {pull}13918[13918]
- Add ExpandEventListFromField config option in the kafka input. {pull}13965[13965]
- Add ELB fileset to AWS module. {pull}14020[14020]
- Add module for MISP (Malware Information Sharing Platform). {pull}13805[13805]
- Add `source.bytes` and `source.packets` for uni-directional netflow events. {pull}14111[14111]
- Add support for gzipped files in S3 input. {pull}13980[13980]
- Add support for all the ObjectCreated events in S3 input. {pull}14077[14077]
- Add Kibana Dashboard for MISP module. {pull}14147[14147]
- Add JSON options to autodiscover hints {pull}14208[14208]
- Add more filesets to Zeek module. {pull}14150[14150]
- Add `index` option to all inputs to directly set a per-input index value. {pull}14010[14010]
- Remove beta flag for some filebeat modules. {pull}14374[14374]
- Add support for http hostname in nginx filebeat module. {pull}14505[14505]
- Add attack_pattern_kql field to MISP threat indicators. {pull}14470[14470]
- Add fileset to the Zeek module for the intel.log. {pull}14404[14404]
- Add vpc flow log fileset to AWS module. {issue}13880[13880] {pull}14345[14345]
- New fileset googlecloud/firewall for ingesting Google Cloud Firewall logs. {pull}14553[14553]
- Add document for Filebeat input httpjson. {pull}14602[14602]
- Add more configuration options to the Netflow module. {pull}14628{14628}
- Add dashboards to the CEF module (ported from the Logstash ArcSight module).
- Add dashboards to the CEF module (ported from the Logstash ArcSight module). {pull}14342[14342]
- Fix timezone parsing in haproxy pipeline. {pull}14755[14755]
- Add module for ActiveMQ. {pull}14840[14840]
- Add dashboards for the ActiveMQ Filebeat module. {pull}14880[14880]
*Heartbeat*
- Add non-privileged icmp on linux and darwin(mac). {pull}13795[13795] {issue}11498[11498]
- Enable `add_observer_metadata` processor in default config. {pull}11394[11394]
- Record HTTP body metadata and optionally contents in `http.response.body.*` fields. {pull}13022[13022]
- Allow `hosts` to be used to configure http monitors {pull}13703[13703]
- google-pubsub input: ACK pub/sub message when acknowledged by publisher. {issue}13346[13346] {pull}14715[14715]
- Remove Beta label from google-pubsub input. {issue}13346[13346] {pull}14715[14715]
*Journalbeat*
*Metricbeat*
- Add AWS SQS metricset. {pull}10684[10684] {issue}10053[10053]
- Add AWS s3_request metricset. {pull}10949[10949] {issue}10055[10055]
- Add s3_daily_storage metricset. {pull}10940[10940] {issue}10055[10055]
- Add `coredns` metricbeat module. {pull}10585[10585]
- Add SSL support for Metricbeat HTTP server. {pull}11482[11482] {issue}11457[11457]
- The `elasticsearch.index` metricset (with `xpack.enabled: true`) now collects `refresh.external_total_time_in_millis` fields from Elasticsearch. {pull}11616[11616]
- Allow module configurations to have variants {pull}9118[9118]
- Add `timeseries.instance` field calculation. {pull}10293[10293]
- Added new disk states and raid level to the system/raid metricset. {pull}11613[11613]
- Added `path_name` and `start_name` to service metricset on windows module {issue}8364[8364] {pull}11877[11877]
- Add check on object name in the counter path if the instance name is missing {issue}6528[6528] {pull}11878[11878]
- Add AWS cloudwatch metricset. {pull}11798[11798] {issue}11734[11734]
- Add `regions` in aws module config to specify target regions for querying cloudwatch metrics. {issue}11932[11932] {pull}11956[11956]
- Keep `etcd` followers members from reporting `leader` metricset events {pull}12004[12004]
- Add overview dashboard to Consul module {pull}10665[10665]
- New fields were added in the mysql/status metricset. {pull}12227[12227]
- Add Kubernetes metricset `proxy`. {pull}12312[12312]
- Add Kubernetes proxy dashboard to Kubernetes module {pull}12734[12734]
- Always report Pod UID in the `pod` metricset. {pull}12345[12345]
- Add Vsphere Virtual Machine operating system to `os` field in Vsphere virtualmachine module. {pull}12391[12391]
- Add validation for elasticsearch and kibana modules' metricsets when xpack.enabled is set to true. {pull}12386[12386]
- Add CockroachDB module. {pull}12467[12467]
- Add support for metricbeat modules based on existing modules (a.k.a. light modules) {issue}12270[12270] {pull}12465[12465]
- Add a system/entropy metricset {pull}12450[12450]
- Add kubernetes metricset `controllermanager` {pull}12409[12409]
- Add Kubernetes controller manager dashboard to Kubernetes module {pull}12744[12744]
- Allow redis URL format in redis hosts config. {pull}12408[12408]
- Add tags into ec2 metricset. {issue}[12263]12263 {pull}12372[12372]
- Add metrics to kubernetes apiserver metricset. {pull}12922[12922]
- Add kubernetes metricset `scheduler` {pull}12521[12521]
- Add Kubernetes scheduler dashboard to Kubernetes module {pull}12749[12749]
- Add `beat` module. {pull}12181[12181] {pull}12615[12615]
- Collect tags for cloudwatch metricset in aws module. {issue}[12263]12263 {pull}12480[12480]
- Add AWS RDS metricset. {pull}11620[11620] {issue}10054[10054]
- Add Oracle Module {pull}11890[11890]
- Add Oracle Tablespaces Dashboard {pull}12736[12736]
- Collect client provided name for rabbitmq connection. {issue}12851[12851] {pull}12852[12852]
- Add support to load default aws config file to get credentials. {pull}12727[12727] {issue}12708[12708]
- Add statistic option into cloudwatch metricset. {issue}12370[12370] {pull}12840[12840]
- Add support for kubernetes cronjobs {pull}13001[13001]
- Add cgroup memory stats to docker/memory metricset {pull}12916[12916]
- Add AWS elb metricset. {pull}12952[12952] {issue}11701[11701]
- Add AWS ebs metricset. {pull}13167[13167] {issue}11699[11699]
- Add `metricset.period` field with the configured fetching period. {pull}13242[13242] {issue}12616[12616]
- Add rate metrics for ec2 metricset. {pull}13203[13203]
- Add refresh list of perf counters at every fetch {issue}13091[13091]
- Add Performance metricset to Oracle module {pull}12547[12547]
- Add proc/vmstat data to the system/memory metricset on linux {pull}13322[13322]
- Use DefaultMetaGeneratorConfig in MetadataEnrichers to initialize configurations {pull}13414[13414]
- Add module for statsd. {pull}13109[13109]
- Add support for NATS version 2. {pull}13601[13601]
- Add `docker.cpu.*.norm.pct` metrics for `cpu` metricset of Docker Metricbeat module. {pull}13695[13695]
- Add `instance` label by default when using Prometheus collector. {pull}13737[13737]
- Add azure module. {pull}13196[13196] {pull}13859[13859] {pull}13988[13988]
- Add Apache Tomcat module {pull}13491[13491]
- Add ECS `container.id` and `container.runtime` to kubernetes `state_container` metricset. {pull}13884[13884]
- Add `job` label by default when using Prometheus collector. {pull}13878[13878]
- Add `state_resourcequota` metricset for Kubernetes module. {pull}13693[13693]
- Add tags filter in ec2 metricset. {pull}13872[13872] {issue}13145[13145]
- Add cloud.account.id and cloud.account.name into events from aws module. {issue}13551[13551] {pull}13558[13558]
- Add `metrics_path` as known hint for autodiscovery {pull}13996[13996]
- Leverage KUBECONFIG when creating k8s client. {pull}13916[13916]
- Add ability to filter by tags for cloudwatch metricset. {pull}13758[13758] {issue}13145[13145]
- Release cloudwatch, s3_daily_storage, s3_request, sqs and rds metricset as GA. {pull}14114[14114] {issue}14059[14059]
- Add Oracle overview dashboard {pull}14021[14021]
- Release CoreDNS module as GA. {pull}14308[14308]
- Release CouchDB module as GA. {pull}14300[14300]
- Add `elasticsearch/enrich` metricset. {pull}14243[14243] {issue}14221[14221]
- Add support for Application ELB and Network ELB. {pull}14123[14123] {issue}13538[13538] {issue}13539[13539]
- Release aws ebs metricset as GA. {pull}14312[14312] {issue}14060[14060]
- Add `connection.state` field for RabbitMQ module. {pull}13981[13981]
- Add more TCP states to Metricbeat system socket_summary. {pull}14347[14347]
- Add Kafka JMX metricsets. {pull}14330[14330]
- Add metrics to envoyproxy server metricset and support for envoy proxy 1.12. {pull}14416[14416] {issue}13642[13642]
- Release kubernetes modules `controllermanager`, `scheduler`, `proxy`, `state_cronjob` and `state_resourcequota` as GA. {pull}14584[14584]
- Add module for ActiveMQ. {pull}14580[14580]
- Enable script processor. {pull}14711[14711]
- Add `kube-state-metrics` `state_service` metrics for kubernetes module. {pull}14794[14794]
- Add usage metricset in aws modules. {pull}14925[14925] {issue}14935[14935]
- Add billing metricset in aws modules. {pull}14801[14801] {issue}14934[14934]
- Add AWS SNS metricset. {pull}14946[14946]
*Packetbeat*
- Update DNS protocol plugin to produce events with ECS fields for DNS. {issue}13320[13320] {pull}13354[13354]
*Functionbeat*
- New options to configure roles and VPC. {pull}11779[11779]
- Export automation templates used to create functions. {pull}11923[11923]
- Configurable Amazon endpoint. {pull}12369[12369]
- Add timeout option to reference configuration. {pull}13351[13351]
- Configurable tags for Lambda functions. {pull}13352[13352]
- Add input for Cloudwatch logs through Kinesis. {pull}13317[13317]
- Enable Logstash output. {pull}13345[13345]
- Make `bulk_max_size` configurable in outputs. {pull}13493[13493]
*Winlogbeat*
- Add support for reading from .evtx files. {issue}4450[4450]
- Add support for event ID 4634 and 4647 to the Security module. {pull}12906[12906]
- Add `network.community_id` to Sysmon network events (event ID 3). {pull}13034[13034]
- Add `event.module` to Winlogbeat modules. {pull}13047[13047]
- Add `event.category: process` and `event.type: process_start/process_end` to Sysmon process events (event ID 1 and 5). {pull}13047[13047]
- Add support for event ID 4672 to the Security module. {pull}12975[12975]
- Add support for event ID 22 (DNS query) to the Sysmon module. {pull}12960[12960]
- Add certain winlog.event_data.* fields to the index template. {issue}13700[13700] {pull}13704[13704]
- Fill `event.provider`. {pull}13937[13937]
- Add support for user management events to the Security module. {pull}13530[13530]
- GA the Winlogbeat `sysmon` module. {pull}14326[14326]
- Add support for event ID 4688 & 4689 (Process create & exit) to the Security module. {issue}14038[14038]
==== Deprecated
*Affecting all Beats*
*Filebeat*
- `docker` input is deprecated in favour `container`. {pull}12162[12162]
- `postgresql.log.timestamp` field is deprecated in favour of `@timestamp`. {pull}12338[12338]
*Heartbeat*
*Journalbeat*
*Metricbeat*
- `kubernetes.container.id` field for `state_container` is deprecated in favour of ECS `container.id` and `container.runtime`. {pull}13884[13884]
*Packetbeat*
*Winlogbeat*
*Functionbeat*
==== Known Issue
*Journalbeat*
",16298,True,3704.892501794135,median
"package view
{
import flash.display.*;
import flash.filters.*;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import mx.core.UIComponent;
import mx.core.MovieClipLoaderAsset;
import mx.controls.Button;
import mx.controls.Label;
import org.libspark.thread.*;
import org.libspark.thread.utils.*;
import org.libspark.thread.threads.between.BeTweenAS3Thread;
import model.DeckEditor;
import model.Growth;
import model.Combine;
import model.WeaponCardInventory;
import model.events.*;
import view.image.edit.*;
import view.scene.edit.*;;
import view.scene.common.*;;
import view.RealMoneyShopView;
import controller.LobbyCtrl;
import controller.GlobalChatCtrl;
// test
import model.Player;
import model.CharaCard;
import model.InventorySet;
import view.scene.common.CharaCardClip;
import view.utils.*;
/**
* 編集画面のビュークラス
*
*/
public class DeckEditView extends Thread
{
// 翻訳データ
CONFIG::LOCALE_JP
private static const _TRANS_MSG :String = ""デッキ編集"";
CONFIG::LOCALE_EN
private static const _TRANS_MSG :String = ""Deck Editor"";
CONFIG::LOCALE_TCN
private static const _TRANS_MSG :String = ""編輯牌組"";
CONFIG::LOCALE_SCN
private static const _TRANS_MSG :String = ""卡组编辑"";
CONFIG::LOCALE_KR
private static const _TRANS_MSG :String = ""덱 편집"";
CONFIG::LOCALE_FR
private static const _TRANS_MSG :String = ""Modification de votre pioche."";
CONFIG::LOCALE_ID
private static const _TRANS_MSG :String = ""デッキ編集"";
CONFIG::LOCALE_TH
private static const _TRANS_MSG :String = ""แก้ไขสำรับ"";
// コントローラ
private var _ctrl:LobbyCtrl = LobbyCtrl.instance;
// エディットインスタンス
private var _deckEdit:DeckEditor = DeckEditor.instance;
// 成長インスタンス
private var _growth:Growth = Growth.instance;
// 合成インスタンス
private var _combine:Combine = Combine.instance;
// 親ステージ
private var _stage:Sprite;
// 表示コンテナ
private var _container:UIComponent = new UIComponent();
// 合成コンテナ
private var _compoContainer:UIComponent = new UIComponent();
// アバタービューコンテナ
private var _avatarContainer:UIComponent = new UIComponent();
// 背景
private var _bg:BG = new BG();
// バインダー部分
private var _ccBinderArea:BinderArea = BinderArea.getCharaCardBinder();
private var _wpBinderArea:BinderArea = BinderArea.getWeaponCardBinder();
private var _eqBinderArea:BinderArea = BinderArea.getEquipCardBinder();
private var _evBinderArea:BinderArea = BinderArea.getEventCardBinder();
private var _mcBinderArea:BinderArea = BinderArea.getMonsterCardBinder();
private var _ocBinderArea:BinderArea = BinderArea.getOtherCardBinder();
// バインダーの配列
private var _binderArea:Array = [_ccBinderArea, _wpBinderArea, _eqBinderArea, _evBinderArea, _mcBinderArea, _ocBinderArea];
// デッキ部分
private var _ccDeckArea:DeckArea = DeckArea.getCharaCardDeck();
private var _wpDeckArea:DeckArea = DeckArea.getWeaponCardDeck();
//private var _eqDeckArea:DeckArea = DeckArea.getEquipCardDeck();
private var _evDeckArea:DeckArea = DeckArea.getEventCardDeck();
//private var _mcDeckArea:DeckArea = DeckArea.getMonsterCardDeck();
//private var _ocDeckArea:DeckArea = DeckArea.getOtherCardDeck();
// デッキの配列 # モンス・その他はキャラデッキを使う 2014/09/02
private var _deckArea:Array = [_ccDeckArea, _wpDeckArea, null, _evDeckArea, null, null];
// カードデータ部分
private var _ccDataArea:DataArea = DataArea.getCharaCardData();
private var _wpDataArea:DataArea = DataArea.getWeaponCardData();
//private var _eqDataArea:DataArea = DataArea.getEquipCardData();
private var _evDataArea:DataArea = DataArea.getEventCardData();
//private var _mcDataArea:DataArea = DataArea.getMonsterCardData();
//private var _ocDataArea:DataArea = DataArea.getOtherCardData();
// カードデータの配列 # モンス・その他はキャラデータを使う 2014/09/02
private var _dataArea:Array = [_ccDataArea, _wpDataArea, null, _evDataArea, null, null];
// ソート表示
private var _sortArea:SortArea = new SortArea();
private var _selectArea:SelectArea = new SelectArea();
// 複製確認パネル
private var _dupeSendPanel:DupeSendPanel = new DupeSendPanel();
// デッキセット
// private var _deckSetButton:DeckSetButton = new DeckSetButton();
// バインダーのタイプ
private var _editType:int;
// タイトル表示
private var _title:Label = new Label();
private var _titleJ:Label = new Label();
// 系統樹
private var _requirementsView:RequirementsView;
// 合成
private var _combinesView:CombinesView;
private var _avatarView:AvatarView = AvatarView.getPlayerAvatar(Const.PL_AVATAR_EDIT);
private var _player:Player = Player.instance;
// 定数
private const _TITLE_X:int = 15;
private const _TITLE_Y:int = 5;
private const _TITLE_WIDTH:int = 100;
private const _TITLE_HEIGHT:int = 20;
private const _J_TITLE_WIDTH:int = 100;
private const _J_TITLE_HEIGHT:int = 20;
// かけら販売フラグ
private const _SELL_TIPS:Boolean = true;
//テスト
// private var _testcccs:Array = []
/**
* コンストラクタ
* @param stage 親ステージ
*/
public function DeckEditView(stage:Sprite)
{
_stage = stage;
_dupeSendPanel.visible = false;
// Unlight.GCW.watch(_bg,""BGです"");
RaidHelpView.instance.isUpdate = true;
}
// スレッドのスタート
override protected function run():void
{
_deckEdit.initialize();
// RMItemShopの更新が必要であれば行う
RealMoneyShopView.itemReset();
// イベントの登録
_avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_bg.deckDelete.addEventListener(MouseEvent.CLICK, pushDeleteButtonHandler);
// _deckSetButton.addEventListener(MouseEvent.CLICK, pushCurrentButtonHandler);
_bg.back.addEventListener(MouseEvent.CLICK, pushLeftButtonHandler);
_bg.next.addEventListener(MouseEvent.CLICK, pushRightButtonHandler);
_bg.binderNext.addEventListener(MouseEvent.CLICK, pushNextButtonHandler);
_bg.binderPrev.addEventListener(MouseEvent.CLICK, pushPrevButtonHandler);
_dupeSendPanel.yesButton.addEventListener(MouseEvent.CLICK, pushYesDupeButtonHandler);
_dupeSendPanel.noButton.addEventListener(MouseEvent.CLICK, pushNoDupeButtonHandler);
_ctrl.addEventListener(LobbyCtrl.REQUEST_COPY_CARD, showDupeSendPanelHandler);
_ctrl.addEventListener(CharaCardEvent.COPY_CHARA_CARD, copyDoneHandler);
_deckEdit.addEventListener(DeckEditor.CHANGE_TYPE, chnageEditTypeHandler);
_dataArea[InventorySet.TYPE_CHARA].storyButton = _bg.story;
_dataArea[InventorySet.TYPE_CHARA].compoButton = _bg.compo;
_dataArea[InventorySet.TYPE_CHARA].dupeButton = _bg.dupe;
_deckArea[InventorySet.TYPE_CHARA].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler);
// 武器合成アリか
CONFIG::WEAPON_COMBINE_ON
{
_dataArea[InventorySet.TYPE_WEAPON].compoButton = _bg.compo;
}
//_dataArea[InventorySet.TYPE_MONSTER].storyButton = _bg.story;
//_dataArea[InventorySet.TYPE_MONSTER].compoButton = _bg.compo;
//_dataArea[InventorySet.TYPE_MONSTER].dupeButton = _bg.dupe;
//_deckArea[InventorySet.TYPE_MONSTER].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler);
//_dataArea[InventorySet.TYPE_OTHER].storyButton = _bg.story;
//_dataArea[InventorySet.TYPE_OTHER].compoButton = _bg.compo;
//_dataArea[InventorySet.TYPE_OTHER].dupeButton = _bg.dupe;
//_deckArea[InventorySet.TYPE_OTHER].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler);
RealMoneyShopView.shopCloseButton.addEventListener(MouseEvent.CLICK, rmShopCloseclickHandler);
Player.instance.avatar.addEventListener(AvatarSaleEvent.SALE_FINISH, saleFinishHandler);
// レイドヘルプイベント
GlobalChatCtrl.instance.addEventListener(RaidHelpEvent.ACCEPT,helpAcceptHandler);
next(initTitle);
}
// タイトルの初期化
private function initTitle():void
{
_avatarView.alpha = 0.0;
_bg.alpha = 0.0;
_sortArea.alpha = 0.0;
_selectArea.alpha = 0.0;
_binderArea[_editType].alpha = 0.0;
// デッキとデータは一部共通化
if (_editType == _deckEdit.substanceEditType(_editType))
{
_deckArea[_editType].alpha = 0.0;
_dataArea[_editType].alpha = 0.0;
}
// _deckSetButton.alpha = 0.0;
_title.x = _TITLE_X;
_title.y = _TITLE_Y;
_title.width = _TITLE_WIDTH;
_title.height = _TITLE_HEIGHT;
_title.text = ""DeckEdit"";
_title.styleName = ""EditTitleLabel"";
_title.filters = [new GlowFilter(0x000000, 1, 2, 2, 16, 1)];
_title.alpha = 0.0;
_title.mouseEnabled = false;
_title.mouseChildren = false;
_titleJ.x = _TITLE_X + 85;
_titleJ.y = _TITLE_Y + 7;
_titleJ.width = _J_TITLE_WIDTH;
_titleJ.height = _J_TITLE_HEIGHT;
// _titleJ.text = ""デッキ編集"";
_titleJ.text = _TRANS_MSG;
_titleJ.filters = [new GlowFilter(0xFFFFFF, 1, 2, 2, 16, 1)];
_titleJ.alpha = 0.0;
_titleJ.mouseEnabled = false;
_titleJ.mouseChildren = false;
_avatarView.refreshType()
next(show);
}
// 配置オブジェの表示
private function show():void
{
var pExec:ParallelExecutor = new ParallelExecutor();
pExec.addThread(_bg.getShowThread(_container, 0)); // 背景
// pExec.addThread(_deckSetButton.getShowThread(_container, 1)); // デッキセットボタン
pExec.addThread(_sortArea.getShowThread(_container, 21)); // ソート
pExec.addThread(_selectArea.getShowThread(_container, 21));
pExec.addThread(_dataArea[InventorySet.TYPE_CHARA].getShowThread(_container, 3)); // カードデータ
pExec.addThread(_dataArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 4)); // カードデータ
//pExec.addThread(_dataArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 5)); // カードデータ
pExec.addThread(_dataArea[InventorySet.TYPE_EVENT].getShowThread(_container, 6)); // カードデータ
//pExec.addThread(_dataArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 7)); // カードデータ
//pExec.addThread(_dataArea[InventorySet.TYPE_OTHER].getShowThread(_container, 8)); // カードデータ
pExec.addThread(_binderArea[InventorySet.TYPE_CHARA].getShowThread(_container, 9)); // バインダー
pExec.addThread(_binderArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 10)); // バインダー
pExec.addThread(_binderArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 11)); // バインダー
pExec.addThread(_binderArea[InventorySet.TYPE_EVENT].getShowThread(_container, 12)); // バインダー
pExec.addThread(_binderArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 13)); // バインダー
pExec.addThread(_binderArea[InventorySet.TYPE_OTHER].getShowThread(_container, 14)); // バインダー
pExec.addThread(_deckArea[InventorySet.TYPE_CHARA].getShowThread(_container, 15)); // デッキ
pExec.addThread(_deckArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 16)); // デッキ
//pExec.addThread(_deckArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 17)); // デッキ
pExec.addThread(_deckArea[InventorySet.TYPE_EVENT].getShowThread(_container, 18)); // デッキ
//pExec.addThread(_deckArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 19)); // デッキ
//pExec.addThread(_deckArea[InventorySet.TYPE_OTHER].getShowThread(_container, 20)); // デッキ
// _testcccs.forEach(function(item:*, index:int, array:Array):void{item.getShowThread(_container).start()})
pExec.start();
pExec.join();
_stage.addChildAt(_container, 1);
_stage.addChildAt(_compoContainer, 2);
_stage.addChildAt(_avatarContainer, 3);
_stage.addChildAt(_dupeSendPanel, 4);
_deckEdit.waiting();
_avatarContainer.addChild(_title);
_avatarContainer.addChild(_titleJ);
next(show2);
}
// 配置オブジェの表示
private function show2():void
{
_bg.tabChara.addEventListener(MouseEvent.CLICK, charaCardTabClickHandler);
_bg.tabEquip.addEventListener(MouseEvent.CLICK, weaponCardTabClickHandler);
_bg.tabEvent.addEventListener(MouseEvent.CLICK, eventCardTabClickHandler);
_bg.tabMonster.addEventListener(MouseEvent.CLICK, monsterCardTabClickHandler);
_bg.tabOther.addEventListener(MouseEvent.CLICK, otherCardTabClickHandler);
_deckEdit.setEditType(InventorySet.TYPE_CHARA);
var pExec:ParallelExecutor = new ParallelExecutor();
// _stage.addChildAt(_deckSetButton, 3);
pExec.addThread(new BeTweenAS3Thread(_title, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_titleJ, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_bg, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_sortArea, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_selectArea, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_dataArea[_deckEdit.substanceEditType(_editType)], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_binderArea[_editType], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(new BeTweenAS3Thread(_deckArea[_deckEdit.substanceEditType(_editType)], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
// pExec.addThread(new BeTweenAS3Thread(_avatarView, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.addThread(_avatarView.getShowThread(_avatarContainer,0)); // アバター情報
// pExec.addThread(new BeTweenAS3Thread(_deckSetButton, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true));
pExec.start();
pExec.join();
next(initPayment);
}
CONFIG::PAYMENT
private function initPayment():void
{
if(_SELL_TIPS)
{
_container.addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD));
}
next(waiting);
}
CONFIG::NOT_PAYMENT
private function initPayment():void
{
// addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD));
next(waiting);
}
// ループ
private function waiting():void
{
// ステートでループ
if (_player.state == Player.STATE_LOGOUT)
{
next(hide);
}else if(_deckEdit.state == DeckEditor.END)
{
next(hide);
}
else if(_growth.state == Growth.REQUIREMENTS)
{
next(requirements);
}
else if(_combine.state == Combine.COMBINES)
{
next(combines);
}
else
{
next(waiting);
}
}
// 系統樹を表示
private function requirements():void
{
RaidHelpView.instance.isUpdate = false;
var pExec:ParallelExecutor = new ParallelExecutor();
_requirementsView = new RequirementsView(_compoContainer, _growth.requirementsCardId)
pExec.addThread(_requirementsView);
// _deckSetButton.visible = false;
// _avatarView.exitButton.visible = false;
_avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_avatarView.exitButton.addEventListener(MouseEvent.CLICK, _requirementsView.exitHandler);
_container.removeChild(_binderArea[_editType]);
_binderArea[_editType].visible =false;
_avatarView.stopUpdateTimer();
RealMoneyShopView.offShopButton(RealMoneyShopView.TYPE_AVATAR);
pExec.start();
pExec.join();
next(requirementFinish)
}
private function requirementFinish():void
{
// _deckSetButton.visible = true;
_binderArea[_editType].visible =true;
_container.addChild(_binderArea[_editType]);
// _avatarView.exitButton.visible = true;
_avatarView.exitButton.removeEventListener(MouseEvent.CLICK, _requirementsView.exitHandler);
_avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_requirementsView = null;
_binderArea[_editType].show();
// 選択済みのカードが枚数0だったら消す
if (CharaCard.ID(_dataArea[_deckEdit.substanceEditType(_editType)].ccc.charaCard.id).num > 0)
{
_dataArea[_deckEdit.substanceEditType(_editType)].showCard();
}else{
_dataArea[_deckEdit.substanceEditType(_editType)].clearCard();
}
_avatarView.startUpdateTimer();
_deckEdit.waiting();
RaidHelpView.instance.isUpdate = true;
next(waiting);
}
// 合成画面を表示
private function combines():void
{
RaidHelpView.instance.isUpdate = false;
var pExec:ParallelExecutor = new ParallelExecutor();
var selInvId:int = 0;
var wci:WeaponCardInventory = _dataArea[_editType].selectInventory;
if (wci) {
selInvId = wci.inventoryID;
}
_combinesView = new CombinesView(_compoContainer, selInvId,_binderArea[_editType])
pExec.addThread(_combinesView);
_avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_avatarView.exitButton.addEventListener(MouseEvent.CLICK, _combinesView.exitHandler);
_container.removeChild(_binderArea[_editType]);
_binderArea[_editType].visible =false;
setTabBtnEnableCombine(false);
pExec.start();
pExec.join();
next(combineFinish)
}
private function combineFinish():void
{
var pExec:ParallelExecutor = new ParallelExecutor();
_binderArea[_editType].visible =true;
_container.addChild(_binderArea[_editType]);
_avatarView.exitButton.removeEventListener(MouseEvent.CLICK, _combinesView.exitHandler);
_avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_combinesView = null;
_binderArea[_editType].alpha = 1.0;
_binderArea[_editType].show();
setTabBtnEnableCombine(true);
_deckEdit.waiting();
pExec.start();
pExec.join();
tabDataAreaUpdate(InventorySet.TYPE_WEAPON);
RaidHelpView.instance.isUpdate = true;
next(waiting);
}
private function setTabBtnEnableCombine(f:Boolean):void
{
_bg.tabChara.mouseEnabled = f;
_bg.tabEquip.mouseEnabled = f;
_bg.tabEvent.mouseEnabled = f;
_bg.tabMonster.mouseEnabled = f;
_bg.tabOther.mouseEnabled = f;
}
private function deckUpdatedHandler(e:DeckUpdatedEvent):void
{
_deckEdit.updateCautions(e);
}
// 左にデッキ切り替え
private function pushLeftButtonHandler(e:MouseEvent):void
{
var subType:uint = _deckEdit.substanceEditType(_editType);
if(_deckArea[subType].flag)
{
SE.playClick();
_deckArea[subType].currentIndex = _deckArea[subType].currentIndex - 1;
_deckArea[InventorySet.TYPE_CHARA].changeDeck(true);
_deckArea[InventorySet.TYPE_WEAPON].changeDeck(true);
//_deckArea[InventorySet.TYPE_EQUIP].changeDeck(true);
_deckArea[InventorySet.TYPE_EVENT].changeDeck(true);
//_deckArea[InventorySet.TYPE_MONSTER].changeDeck(true);
//_deckArea[InventorySet.TYPE_OTHER].changeDeck(true);
}
}
// 右にデッキ切り替え
private function pushRightButtonHandler(e:MouseEvent):void
{
var subType:uint = _deckEdit.substanceEditType(_editType);
if(_deckArea[subType].flag)
{
SE.playClick();
_deckArea[subType].currentIndex = _deckArea[subType].currentIndex + 1;
_deckArea[InventorySet.TYPE_CHARA].changeDeck(false);
_deckArea[InventorySet.TYPE_WEAPON].changeDeck(false);
//_deckArea[InventorySet.TYPE_EQUIP].changeDeck(false);
_deckArea[InventorySet.TYPE_EVENT].changeDeck(false);
//_deckArea[InventorySet.TYPE_MONSTER].changeDeck(false);
//_deckArea[InventorySet.TYPE_OTHER].changeDeck(false);
}
}
// デッキを作成
private function pushCreateButtonHandler(e:MouseEvent):void
{
SE.playClick();
_deckEdit.createDeck();
log.writeLog(log.LV_INFO, this, ""push create deck"");
}
// デッキを削除
private function pushDeleteButtonHandler(e:MouseEvent):void
{
SE.playClick();
_deckEdit.deleteDeck(_deckEdit.selectIndex);
log.writeLog(log.LV_INFO, this, ""push create deck"");
}
// カレントデッキ変更
private function pushCurrentButtonHandler(e:MouseEvent):void
{
SE.playClick();
_deckEdit.changeCurrentDeck(_deckEdit.selectIndex);
log.writeLog(log.LV_INFO, this, ""push current change"");
}
// 終了
private function pushExitButtonHandler(e:MouseEvent):void
{
SE.playClick();
_deckEdit.finalize();
log.writeLog(log.LV_INFO, this, ""push exit"");
}
// タブのデータエリアをON/OFFする
private function tabDataAreaUpdate(t:int):void
{
// 現在タブのカードのみ出す
log.writeLog(log.LV_INFO, this, ""SHOWCARD TYPE"",t);
log.writeLog(log.LV_INFO, this, ""_dataarea size?"",_dataArea.length);
// 他タブのカードを隠す
_dataArea.forEach(function(item:DataArea, index:int, array:Array):void{
if(t != index && _deckEdit.substanceEditType(t) != index && item != null)
{
log.writeLog(log.LV_INFO, this, ""HIDE TYPE"",index);
item.hideCard();
}
});
_dataArea[_deckEdit.substanceEditType(t)].showCard();
}
// キャラカードを選択
private function charaCardTabClickHandler(e:MouseEvent):void
{
log.writeLog(log.LV_INFO, this, ""set edit type chara!!"");
_deckEdit.setEditType(InventorySet.TYPE_CHARA);
tabDataAreaUpdate(InventorySet.TYPE_CHARA);
}
// 武器カードを選択
private function weaponCardTabClickHandler(e:MouseEvent):void
{
_deckEdit.setEditType(InventorySet.TYPE_WEAPON);
tabDataAreaUpdate(InventorySet.TYPE_WEAPON);
}
// 装備カードを選択
private function equipCardTabClickHandler(e:MouseEvent):void
{
_deckEdit.setEditType(InventorySet.TYPE_EQUIP);
tabDataAreaUpdate(InventorySet.TYPE_EQUIP);
}
// イベントカードを選択
private function eventCardTabClickHandler(e:MouseEvent):void
{
_deckEdit.setEditType(InventorySet.TYPE_EVENT);
tabDataAreaUpdate(InventorySet.TYPE_EVENT);
}
// モンスターカードを選択
private function monsterCardTabClickHandler(e:MouseEvent):void
{
_deckEdit.setEditType(InventorySet.TYPE_MONSTER);
tabDataAreaUpdate(InventorySet.TYPE_MONSTER);
}
// その他カードを選択
private function otherCardTabClickHandler(e:MouseEvent):void
{
_deckEdit.setEditType(InventorySet.TYPE_OTHER);
tabDataAreaUpdate(InventorySet.TYPE_OTHER);
}
// 編集タイプを変更
private function chnageEditTypeHandler(e:Event):void
{
setEditType(_deckEdit.editType);
}
// バインダーを進める
private function pushNextButtonHandler(e:MouseEvent):void
{
log.writeLog (log.LV_DEBUG,this,""binder next"");
_binderArea[_editType].page -=1;
}
// バインダーを戻す
private function pushPrevButtonHandler(e:MouseEvent):void
{
log.writeLog (log.LV_DEBUG,this,""binder prev"");
_binderArea[_editType].page +=1;
}
// 複製確認パネルを表示
private function showDupeSendPanelHandler(e:Event):void
{
_container.mouseEnabled = false;
_container.mouseChildren = false;
_dupeSendPanel.visible = true;
}
// 複製YES
private function pushYesDupeButtonHandler(e:MouseEvent):void
{
// 表示中のカードをコピー
if (_editType == InventorySet.TYPE_CHARA || _editType == InventorySet.TYPE_MONSTER || _editType == InventorySet.TYPE_OTHER) {
_ctrl.copyCard(_dataArea[_deckEdit.substanceEditType(_editType)].ccc.charaCard.id);
}
_container.mouseEnabled = true;
_container.mouseChildren = true;
_dupeSendPanel.visible = false;
}
// 複製NO
private function pushNoDupeButtonHandler(e:MouseEvent):void
{
_container.mouseEnabled = true;
_container.mouseChildren = true;
_dupeSendPanel.visible = false;
}
// 複製完了後ハンドラ
private function copyDoneHandler(e:Event):void
{
if (_editType == InventorySet.TYPE_CHARA || _editType == InventorySet.TYPE_MONSTER || _editType == InventorySet.TYPE_OTHER) {
_dataArea[_deckEdit.substanceEditType(_editType)].reloadDupeCount();
}
}
// セールの終了判定が出たときのハンドラ
private function saleFinishHandler(e:AvatarSaleEvent):void
{
// log.writeLog (log.LV_INFO,this,""saleFinish!"");
RealMoneyShopView.hideButtonSaleMC(RealMoneyShopView.TYPE_EX_CARD);
// ショップアイテムリストの更新
RealMoneyShopView.itemReset();
}
// レイドヘルプハンドラ
private function helpAcceptHandler(e:RaidHelpEvent):void
{
_deckEdit.finalize();
log.writeLog(log.LV_INFO, this, ""raid help"");
}
// バインダーを戻す
private function setEditType(val:int):void
{
switch (val)
{
case InventorySet.TYPE_CHARA:
_binderArea[InventorySet.TYPE_CHARA].visible = true;
_binderArea[InventorySet.TYPE_WEAPON].visible = false;
_binderArea[InventorySet.TYPE_EQUIP].visible = false;
_binderArea[InventorySet.TYPE_EVENT].visible = false;
_binderArea[InventorySet.TYPE_MONSTER].visible = false;
_binderArea[InventorySet.TYPE_OTHER].visible = false;
_binderArea[InventorySet.TYPE_CHARA].addSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].removeSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].removeSortHandler();
_binderArea[InventorySet.TYPE_EVENT].removeSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].removeSortHandler();
_binderArea[InventorySet.TYPE_OTHER].removeSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = true;
_deckArea[InventorySet.TYPE_WEAPON].visible = false;
//_deckArea[InventorySet.TYPE_EQUIP].visible = false;
_deckArea[InventorySet.TYPE_EVENT].visible = false;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = false;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = true;
_dataArea[InventorySet.TYPE_WEAPON].visible = false;
//_dataArea[InventorySet.TYPE_EQUIP].visible = false;
_dataArea[InventorySet.TYPE_EVENT].visible = false;
//_dataArea[InventorySet.TYPE_MONSTER].visible = false;
//_dataArea[InventorySet.TYPE_OTHER].visible = false;
_dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false;
_bg.tabChara.visible = false;
_bg.tabEquip.visible = true;
_bg.tabEvent.visible = true;
_bg.tabMonster.visible = true;
_bg.tabOther.visible = true;
_bg.setCharaParameter();
break;
case InventorySet.TYPE_WEAPON:
_binderArea[InventorySet.TYPE_CHARA].visible = false;
_binderArea[InventorySet.TYPE_WEAPON].visible = true;
_binderArea[InventorySet.TYPE_EQUIP].visible = false;
_binderArea[InventorySet.TYPE_EVENT].visible = false;
_binderArea[InventorySet.TYPE_MONSTER].visible = false;
_binderArea[InventorySet.TYPE_OTHER].visible = false;
_binderArea[InventorySet.TYPE_CHARA].removeSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].addSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].removeSortHandler();
_binderArea[InventorySet.TYPE_EVENT].removeSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].removeSortHandler();
_binderArea[InventorySet.TYPE_OTHER].removeSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = true;
_deckArea[InventorySet.TYPE_WEAPON].visible = true;
//_deckArea[InventorySet.TYPE_EQUIP].visible = false;
_deckArea[InventorySet.TYPE_EVENT].visible = false;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = false;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_WEAPON],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = false;
_dataArea[InventorySet.TYPE_WEAPON].visible = true;
//_dataArea[InventorySet.TYPE_EQUIP].visible = false;
_dataArea[InventorySet.TYPE_EVENT].visible = false;
//_dataArea[InventorySet.TYPE_MONSTER].visible = false;
//_dataArea[InventorySet.TYPE_OTHER].visible = false;
_bg.compo.visible = false;
_bg.story.visible = false;
_bg.dupe.visible = false;
_bg.tabChara.visible = true;
_bg.tabEquip.visible = false;
_bg.tabEvent.visible = true;
_bg.tabMonster.visible = true;
_bg.tabOther.visible = true;
_bg.setEquipParameter();
break;
case InventorySet.TYPE_EQUIP:
_binderArea[InventorySet.TYPE_CHARA].visible = false;
_binderArea[InventorySet.TYPE_WEAPON].visible = false;
_binderArea[InventorySet.TYPE_EQUIP].visible = true;
_binderArea[InventorySet.TYPE_EVENT].visible = false;
_binderArea[InventorySet.TYPE_MONSTER].visible = false;
_binderArea[InventorySet.TYPE_OTHER].visible = false;
_binderArea[InventorySet.TYPE_CHARA].removeSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].removeSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].addSortHandler();
_binderArea[InventorySet.TYPE_EVENT].removeSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].removeSortHandler();
_binderArea[InventorySet.TYPE_OTHER].removeSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = false;
_deckArea[InventorySet.TYPE_WEAPON].visible = false;
//_deckArea[InventorySet.TYPE_EQUIP].visible = true;
_deckArea[InventorySet.TYPE_EVENT].visible = false;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = false;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_EQUIP],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = false;
_dataArea[InventorySet.TYPE_WEAPON].visible = false;
//_dataArea[InventorySet.TYPE_EQUIP].visible = true;
_dataArea[InventorySet.TYPE_EVENT].visible = false;
//_dataArea[InventorySet.TYPE_MONSTER].visible = false;
//_dataArea[InventorySet.TYPE_OTHER].visible = false;
_bg.compo.visible = false;
_bg.story.visible = false;
_bg.dupe.visible = false;
_bg.tabChara.visible = true;
_bg.tabEquip.visible = false;
_bg.tabEvent.visible = true;
_bg.tabMonster.visible = true;
_bg.tabOther.visible = true;
_bg.setEquipParameter();
break;
case InventorySet.TYPE_EVENT:
_binderArea[InventorySet.TYPE_CHARA].visible = false;
_binderArea[InventorySet.TYPE_WEAPON].visible = false;
_binderArea[InventorySet.TYPE_EQUIP].visible = false;
_binderArea[InventorySet.TYPE_EVENT].visible = true;
_binderArea[InventorySet.TYPE_MONSTER].visible = false;
_binderArea[InventorySet.TYPE_OTHER].visible = false;
_binderArea[InventorySet.TYPE_CHARA].removeSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].removeSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].removeSortHandler();
_binderArea[InventorySet.TYPE_EVENT].addSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].removeSortHandler();
_binderArea[InventorySet.TYPE_OTHER].removeSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = true;
_deckArea[InventorySet.TYPE_WEAPON].visible = false;
//_deckArea[InventorySet.TYPE_EQUIP].visible = false;
_deckArea[InventorySet.TYPE_EVENT].visible = true;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = false;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_EVENT],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = false;
_dataArea[InventorySet.TYPE_WEAPON].visible = false;
//_dataArea[InventorySet.TYPE_EQUIP].visible = false;
_dataArea[InventorySet.TYPE_EVENT].visible = true;
//_dataArea[InventorySet.TYPE_MONSTER].visible = false;
//_dataArea[InventorySet.TYPE_OTHER].visible = false;
_bg.compo.visible = false;
_bg.story.visible = false;
_bg.dupe.visible = false;
_bg.tabChara.visible = true;
_bg.tabEquip.visible = true;
_bg.tabEvent.visible = false;
_bg.tabMonster.visible = true;
_bg.tabOther.visible = true;
_bg.setEventParameter();
break;
case InventorySet.TYPE_MONSTER:
_binderArea[InventorySet.TYPE_CHARA].visible = false;
_binderArea[InventorySet.TYPE_WEAPON].visible = false;
_binderArea[InventorySet.TYPE_EQUIP].visible = false;
_binderArea[InventorySet.TYPE_EVENT].visible = false;
_binderArea[InventorySet.TYPE_MONSTER].visible = true;
_binderArea[InventorySet.TYPE_OTHER].visible = false;
_binderArea[InventorySet.TYPE_CHARA].removeSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].removeSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].removeSortHandler();
_binderArea[InventorySet.TYPE_EVENT].removeSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].addSortHandler();
_binderArea[InventorySet.TYPE_OTHER].removeSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = true;
_deckArea[InventorySet.TYPE_WEAPON].visible = false;
//_deckArea[InventorySet.TYPE_EQUIP].visible = false;
_deckArea[InventorySet.TYPE_EVENT].visible = false;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = false;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = true;
_dataArea[InventorySet.TYPE_WEAPON].visible = false;
//_dataArea[InventorySet.TYPE_EQUIP].visible = false;
_dataArea[InventorySet.TYPE_EVENT].visible = false;
//_dataArea[InventorySet.TYPE_MONSTER].visible = true;
//_dataArea[InventorySet.TYPE_OTHER].visible = false;
_dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false;
_bg.tabChara.visible = true;
_bg.tabEquip.visible = true;
_bg.tabEvent.visible = true;
_bg.tabMonster.visible = false;
_bg.tabOther.visible = true;
_bg.setMonsterParameter();
break;
case InventorySet.TYPE_OTHER:
_binderArea[InventorySet.TYPE_CHARA].visible = false;
_binderArea[InventorySet.TYPE_WEAPON].visible = false;
_binderArea[InventorySet.TYPE_EQUIP].visible = false;
_binderArea[InventorySet.TYPE_EVENT].visible = false;
_binderArea[InventorySet.TYPE_MONSTER].visible = false;
_binderArea[InventorySet.TYPE_OTHER].visible = true;
_binderArea[InventorySet.TYPE_CHARA].removeSortHandler();
_binderArea[InventorySet.TYPE_WEAPON].removeSortHandler();
_binderArea[InventorySet.TYPE_EQUIP].removeSortHandler();
_binderArea[InventorySet.TYPE_EVENT].removeSortHandler();
_binderArea[InventorySet.TYPE_MONSTER].removeSortHandler();
_binderArea[InventorySet.TYPE_OTHER].addSortHandler();
_deckArea[InventorySet.TYPE_CHARA].visible = true;
_deckArea[InventorySet.TYPE_WEAPON].visible = false;
//_deckArea[InventorySet.TYPE_EQUIP].visible = false;
_deckArea[InventorySet.TYPE_EVENT].visible = false;
//_deckArea[InventorySet.TYPE_MONSTER].visible = false;
//_deckArea[InventorySet.TYPE_OTHER].visible = true;
// 選ばれたデッキは最前線に送る
_container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1);
_dataArea[InventorySet.TYPE_CHARA].visible = true;
_dataArea[InventorySet.TYPE_WEAPON].visible = false;
//_dataArea[InventorySet.TYPE_EQUIP].visible = false;
_dataArea[InventorySet.TYPE_EVENT].visible = false;
//_dataArea[InventorySet.TYPE_MONSTER].visible = false;
//_dataArea[InventorySet.TYPE_OTHER].visible = true;
_dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false;
_bg.tabChara.visible = true;
_bg.tabEquip.visible = true;
_bg.tabEvent.visible = true;
_bg.tabMonster.visible = true;
_bg.tabOther.visible = false;
_bg.setOtherParameter();
break;
}
_editType = val;
// タブがキャラの時だけ、表示
if (_editType == InventorySet.TYPE_CHARA) {
_bg.search = true;
} else {
_bg.search = false;
}
}
CONFIG::PAYMENT
private function hide():void
{
if(_SELL_TIPS)
{
_container.removeChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD));
}
next(hide2);
}
CONFIG::NOT_PAYMENT
private function hide():void
{
// addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD));
next(hide2);
}
private function hide2():void
{
var pExec:ParallelExecutor = new ParallelExecutor();
pExec.addThread(new BeTweenAS3Thread(_dupeSendPanel, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_title, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_titleJ, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_bg, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_sortArea, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_selectArea, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_dataArea[_deckEdit.substanceEditType(_editType)], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_binderArea[_editType], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_deckArea[_deckEdit.substanceEditType(_editType)], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_deckArea[InventorySet.TYPE_CHARA], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
// pExec.addThread(new BeTweenAS3Thread(_deckSetButton, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.addThread(new BeTweenAS3Thread(_avatarView, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false));
pExec.start();
pExec.join();
if (_ctrl.cardInvUpdating) {
Unlight.INS.loadingReset();
Unlight.INS.loadingStart();
next(updateWait);
} else {
next(hide3);
}
// next(hide3);
}
// データ更新待ち
private function updateWait():void
{
log.writeLog(log.LV_DEBUG, this, ""updateWait"");
if (_ctrl.cardInvUpdating) {
next(updateWait);
} else {
log.writeLog(log.LV_DEBUG, this, ""updateWait end"");
Unlight.INS.loadingEnd();
next(loadWait);
}
}
// ロードオブジェ待ち
private function loadWait():void
{
log.writeLog(log.LV_DEBUG, this, ""loadWait"");
if (Unlight.INS.loadingDisable()) {
log.writeLog(log.LV_DEBUG, this, ""loadWait end"");
next(hide3);
} else {
next(loadWait);
}
}
// 配置オブジェの表示
private function hide3():void
{
var pExec:ParallelExecutor = new ParallelExecutor();
pExec.addThread(_bg.getHideThread()); // 背景
pExec.addThread(_ccDataArea.getHideThread()); // データ
pExec.addThread(_wpDataArea.getHideThread()); // データ
//pExec.addThread(_eqDataArea.getHideThread()); // データ
pExec.addThread(_evDataArea.getHideThread()); // データ
//pExec.addThread(_mcDataArea.getHideThread()); // データ
//pExec.addThread(_ocDataArea.getHideThread()); // データ
pExec.addThread(_ccBinderArea.getHideThread()); // バインダー
pExec.addThread(_wpBinderArea.getHideThread()); // バインダー
pExec.addThread(_eqBinderArea.getHideThread()); // バインダー
pExec.addThread(_evBinderArea.getHideThread()); // バインダー
pExec.addThread(_mcBinderArea.getHideThread()); // バインダー
pExec.addThread(_ocBinderArea.getHideThread()); // バインダー
pExec.addThread(_ccDeckArea.getHideThread()); // デッキ
pExec.addThread(_wpDeckArea.getHideThread()); // デッキ
//pExec.addThread(_eqDeckArea.getHideThread()); // デッキ
pExec.addThread(_evDeckArea.getHideThread()); // デッキ
//pExec.addThread(_mcDeckArea.getHideThread()); // デッキ
//pExec.addThread(_ocDeckArea.getHideThread()); // デッキ
pExec.addThread(_selectArea.getHideThread());
pExec.addThread(_sortArea.getHideThread()); // ソート
pExec.addThread(_avatarView.getHideThread()); // デッキ
// pExec.addThread(_deckSetButton.getHideThread()); // デッキ
pExec.start();
pExec.join();
next(exit);
}
private function exit():void
{
// イベントの消去
// _bg.exit.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler);
// _bg.deckCreate.removeEventListener(MouseEvent.CLICK, pushCreateButtonHandler);
RealMoneyShopView.shopCloseButton.removeEventListener(MouseEvent.CLICK, rmShopCloseclickHandler);
_avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler);
_ctrl.removeEventListener(LobbyCtrl.REQUEST_COPY_CARD, showDupeSendPanelHandler);
_ctrl.removeEventListener(CharaCardEvent.COPY_CHARA_CARD, copyDoneHandler);
_dupeSendPanel.yesButton.removeEventListener(MouseEvent.CLICK, pushYesDupeButtonHandler);
_dupeSendPanel.noButton.removeEventListener(MouseEvent.CLICK, pushNoDupeButtonHandler);
_bg.deckDelete.removeEventListener(MouseEvent.CLICK, pushDeleteButtonHandler);
_bg.back.removeEventListener(MouseEvent.CLICK, pushLeftButtonHandler);
_bg.next.removeEventListener(MouseEvent.CLICK, pushRightButtonHandler);
_bg.binderNext.removeEventListener(MouseEvent.CLICK, pushNextButtonHandler);
_bg.binderPrev.removeEventListener(MouseEvent.CLICK, pushPrevButtonHandler);
_bg.tabChara.removeEventListener(MouseEvent.CLICK, charaCardTabClickHandler);
_bg.tabEquip.removeEventListener(MouseEvent.CLICK, weaponCardTabClickHandler);
_bg.tabEvent.removeEventListener(MouseEvent.CLICK, eventCardTabClickHandler);
_bg.tabMonster.removeEventListener(MouseEvent.CLICK, monsterCardTabClickHandler);
_bg.tabOther.removeEventListener(MouseEvent.CLICK, otherCardTabClickHandler);
_deckEdit.removeEventListener(DeckEditor.CHANGE_TYPE, chnageEditTypeHandler);
Player.instance.avatar.removeEventListener(AvatarSaleEvent.SALE_FINISH, saleFinishHandler);
// レイドヘルプイベント
GlobalChatCtrl.instance.removeEventListener(RaidHelpEvent.ACCEPT,helpAcceptHandler);
// _deckSetButton.removeEventListener(MouseEvent.CLICK, pushCurrentButtonHandler);
_bg.final();
_bg = null;
log.writeLog(log.LV_INFO, this, ""edit exit"");
}
// 終了関数
override protected function finalize():void
{
RemoveChild.apply(_title);
RemoveChild.apply(_titleJ);
RemoveChild.apply(_dupeSendPanel);
RemoveChild.apply(_compoContainer);
RemoveChild.apply(_avatarContainer);
RemoveChild.apply(_container);
log.writeLog (log.LV_WARN,this,""edit end"");
}
// バインダーを更新
private function rmShopCloseclickHandler(e:Event):void
{
_binderArea[_editType].update();
}
}
}
",12052,True,2789.401210432148,median
"/*
Copyright (c) 2012 Josh Tynjala
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ""Software""), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
package feathers.themes
{
import feathers.controls.Alert;
import feathers.controls.Button;
import feathers.controls.ButtonGroup;
import feathers.controls.Callout;
import feathers.controls.Check;
import feathers.controls.GroupedList;
import feathers.controls.Header;
import feathers.controls.ImageLoader;
import feathers.controls.Label;
import feathers.controls.List;
import feathers.controls.NumericStepper;
import feathers.controls.PageIndicator;
import feathers.controls.Panel;
import feathers.controls.PanelScreen;
import feathers.controls.PickerList;
import feathers.controls.ProgressBar;
import feathers.controls.Radio;
import feathers.controls.Screen;
import feathers.controls.ScrollContainer;
import feathers.controls.ScrollText;
import feathers.controls.SimpleScrollBar;
import feathers.controls.Slider;
import feathers.controls.TabBar;
import feathers.controls.TextInput;
import feathers.controls.ToggleSwitch;
import feathers.controls.popups.CalloutPopUpContentManager;
import feathers.controls.popups.VerticalCenteredPopUpContentManager;
import feathers.controls.renderers.BaseDefaultItemRenderer;
import feathers.controls.renderers.DefaultGroupedListHeaderOrFooterRenderer;
import feathers.controls.renderers.DefaultGroupedListItemRenderer;
import feathers.controls.renderers.DefaultListItemRenderer;
import feathers.controls.text.BitmapFontTextRenderer;
import feathers.controls.text.StageTextTextEditor;
import feathers.core.DisplayListWatcher;
import feathers.core.FeathersControl;
import feathers.core.PopUpManager;
import feathers.display.Scale9Image;
import feathers.layout.HorizontalLayout;
import feathers.layout.VerticalLayout;
import feathers.skins.SmartDisplayObjectStateValueSelector;
import feathers.skins.StandardIcons;
import feathers.system.DeviceCapabilities;
import feathers.text.BitmapFontTextFormat;
import feathers.textures.Scale3Textures;
import feathers.textures.Scale9Textures;
import feathers.utils.math.roundToNearest;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Image;
import starling.display.Quad;
import starling.events.Event;
import starling.text.BitmapFont;
import starling.textures.Texture;
import starling.textures.TextureAtlas;
import starling.textures.TextureSmoothing;
public class MinimalMobileTheme extends DisplayListWatcher
{
public static const COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER:String = ""feathers-mobile-picker-list-item-renderer"";
[Embed(source=""/../assets/images/minimal.png"")]
protected static const ATLAS_IMAGE:Class;
[Embed(source=""/../assets/images/minimal.xml"",mimeType=""application/octet-stream"")]
protected static const ATLAS_XML:Class;
[Embed(source=""/../assets/fonts/pf_ronda_seven.fnt"",mimeType=""application/octet-stream"")]
protected static const ATLAS_FONT_XML:Class;
protected static const SCALE_9_GRID:Rectangle = new Rectangle(9, 9, 2, 2);
protected static const BUTTON_SCALE_9_GRID:Rectangle = new Rectangle(5, 5, 1, 1);
protected static const BUTTON_DOWN_SCALE_9_GRID:Rectangle = new Rectangle(9, 9, 1, 1);
protected static const SCROLLBAR_THUMB_SCALE_9_GRID:Rectangle = new Rectangle(1, 1, 2, 2);
protected static const TAB_SCALE_9_GRID:Rectangle = new Rectangle(25, 21, 1, 1);
protected static const HEADER_SCALE_9_GRID:Rectangle = new Rectangle(0, 5, 3, 1);
protected static const LIST_ITEM_SCALE_9_GRID:Rectangle = new Rectangle(5, 5, 1, 1);
protected static const BACK_BUTTON_SCALE_REGION1:int = 30;
protected static const BACK_BUTTON_SCALE_REGION2:int = 1;
protected static const FORWARD_BUTTON_SCALE_REGION1:int = 9;
protected static const FORWARD_BUTTON_SCALE_REGION2:int = 1;
protected static const BACKGROUND_COLOR:uint = 0xf3f3f3;
protected static const LIST_BACKGROUND_COLOR:uint = 0xf8f8f8;
protected static const LIST_HEADER_BACKGROUND_COLOR:uint = 0xeeeeee;
protected static const PRIMARY_TEXT_COLOR:uint = 0x666666;
protected static const DISABLED_TEXT_COLOR:uint = 0x999999;
protected static const MODAL_OVERLAY_COLOR:uint = 0x666666;
protected static const MODAL_OVERLAY_ALPHA:Number = 0.8;
protected static const ORIGINAL_DPI_IPHONE_RETINA:int = 326;
protected static const ORIGINAL_DPI_IPAD_RETINA:int = 264;
protected static function textRendererFactory():BitmapFontTextRenderer
{
const renderer:BitmapFontTextRenderer = new BitmapFontTextRenderer();
//since it's a pixel font, we don't want to smooth it.
renderer.smoothing = TextureSmoothing.NONE;
return renderer;
}
protected static function textEditorFactory():StageTextTextEditor
{
return new StageTextTextEditor();
}
protected static function popUpOverlayFactory():DisplayObject
{
const quad:Quad = new Quad(100, 100, MODAL_OVERLAY_COLOR);
quad.alpha = MODAL_OVERLAY_ALPHA;
return quad;
}
public function MinimalMobileTheme(container:DisplayObjectContainer = null, scaleToDPI:Boolean = true)
{
if(!container)
{
container = Starling.current.stage;
}
super(container);
Starling.current.nativeStage.color = BACKGROUND_COLOR;
if(this.root.stage)
{
this.root.stage.color = BACKGROUND_COLOR;
}
else
{
this.root.addEventListener(Event.ADDED_TO_STAGE, root_addedToStageHandler);
}
this._scaleToDPI = scaleToDPI;
this.initialize();
}
protected var _originalDPI:int;
public function get originalDPI():int
{
return this._originalDPI;
}
protected var _scaleToDPI:Boolean;
public function get scaleToDPI():Boolean
{
return this._scaleToDPI;
}
protected var scale:Number;
protected var fontSize:int;
protected var inputFontSize:int;
protected var atlas:TextureAtlas;
protected var atlasBitmapData:BitmapData;
protected var buttonUpSkinTextures:Scale9Textures;
protected var buttonDownSkinTextures:Scale9Textures;
protected var buttonDisabledSkinTextures:Scale9Textures;
protected var buttonSelectedSkinTextures:Scale9Textures;
protected var buttonSelectedDisabledSkinTextures:Scale9Textures;
protected var buttonCallToActionUpSkinTextures:Scale9Textures;
protected var buttonQuietUpSkinTextures:Scale9Textures;
protected var buttonDangerUpSkinTextures:Scale9Textures;
protected var buttonDangerDownSkinTextures:Scale9Textures;
protected var buttonBackUpSkinTextures:Scale3Textures;
protected var buttonBackDownSkinTextures:Scale3Textures;
protected var buttonBackDisabledSkinTextures:Scale3Textures;
protected var buttonForwardUpSkinTextures:Scale3Textures;
protected var buttonForwardDownSkinTextures:Scale3Textures;
protected var buttonForwardDisabledSkinTextures:Scale3Textures;
protected var tabDownSkinTextures:Scale9Textures;
protected var tabSelectedSkinTextures:Scale9Textures;
protected var tabSelectedDisabledSkinTextures:Scale9Textures;
protected var thumbSkinTextures:Scale9Textures;
protected var thumbDisabledSkinTextures:Scale9Textures;
protected var scrollBarThumbSkinTextures:Scale9Textures;
protected var insetBackgroundSkinTextures:Scale9Textures;
protected var insetBackgroundDisabledSkinTextures:Scale9Textures;
protected var dropDownArrowTexture:Texture;
protected var searchIconTexture:Texture;
protected var listItemUpTextures:Scale9Textures;
protected var listItemDownTextures:Scale9Textures;
protected var listItemSelectedTextures:Scale9Textures;
protected var pickerListItemSelectedIconTexture:Texture;
protected var headerSkinTextures:Scale9Textures;
protected var popUpBackgroundSkinTextures:Scale9Textures;
protected var calloutTopArrowSkinTexture:Texture;
protected var calloutBottomArrowSkinTexture:Texture;
protected var calloutLeftArrowSkinTexture:Texture;
protected var calloutRightArrowSkinTexture:Texture;
protected var checkIconTexture:Texture;
protected var checkDisabledIconTexture:Texture;
protected var checkSelectedIconTexture:Texture;
protected var checkSelectedDisabledIconTexture:Texture;
protected var radioIconTexture:Texture;
protected var radioDisabledIconTexture:Texture;
protected var radioSelectedIconTexture:Texture;
protected var radioSelectedDisabledIconTexture:Texture;
protected var pageIndicatorNormalSkinTexture:Texture;
protected var pageIndicatorSelectedSkinTexture:Texture;
protected var bitmapFont:BitmapFont;
protected var primaryTextFormat:BitmapFontTextFormat;
protected var disabledTextFormat:BitmapFontTextFormat;
override public function dispose():void
{
if(this.root)
{
this.root.removeEventListener(Event.ADDED_TO_STAGE, root_addedToStageHandler);
}
if(this.atlas)
{
this.atlas.dispose();
this.atlas = null;
}
if(this.atlasBitmapData)
{
this.atlasBitmapData.dispose();
this.atlasBitmapData = null;
}
super.dispose();
}
protected function initialize():void
{
const scaledDPI:int = DeviceCapabilities.dpi / Starling.contentScaleFactor;
if(this._scaleToDPI)
{
if(DeviceCapabilities.isTablet(Starling.current.nativeStage))
{
this._originalDPI = ORIGINAL_DPI_IPAD_RETINA;
}
else
{
this._originalDPI = ORIGINAL_DPI_IPHONE_RETINA;
}
}
else
{
this._originalDPI = scaledDPI;
}
//our min scale is 0.25 because lines in the graphics are four
//pixels wide and this will keep them crisp.
this.scale = Math.max(0.25, scaledDPI / this._originalDPI);
//since it's a pixel font, we want a multiple of the original size,
//which, in this case, is 8.
this.fontSize = Math.max(4, roundToNearest(24 * this.scale, 8));
this.inputFontSize = 26 * this.scale;
PopUpManager.overlayFactory = popUpOverlayFactory;
Callout.stagePaddingTop = Callout.stagePaddingRight = Callout.stagePaddingBottom =
Callout.stagePaddingLeft = 16 * this.scale;
const atlasBitmapData:BitmapData = (new ATLAS_IMAGE()).bitmapData;
this.atlas = new TextureAtlas(Texture.fromBitmapData(atlasBitmapData, false), XML(new ATLAS_XML()));
if(Starling.handleLostContext)
{
this.atlasBitmapData = atlasBitmapData;
}
else
{
atlasBitmapData.dispose();
}
this.bitmapFont = new BitmapFont(this.atlas.getTexture(""pf_ronda_seven_0""), XML(new ATLAS_FONT_XML()));
this.buttonUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-up-skin""), BUTTON_SCALE_9_GRID);
this.buttonDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-down-skin""), BUTTON_DOWN_SCALE_9_GRID);
this.buttonDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-disabled-skin""), BUTTON_SCALE_9_GRID);
this.buttonSelectedSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-selected-skin""), BUTTON_DOWN_SCALE_9_GRID);
this.buttonSelectedDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-selected-disabled-skin""), BUTTON_DOWN_SCALE_9_GRID);
this.buttonCallToActionUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-call-to-action-up-skin""), BUTTON_SCALE_9_GRID);
this.buttonQuietUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-quiet-up-skin""), BUTTON_SCALE_9_GRID);
this.buttonDangerUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-danger-up-skin""), BUTTON_SCALE_9_GRID);
this.buttonDangerDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-danger-down-skin""), BUTTON_DOWN_SCALE_9_GRID);
this.buttonBackUpSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-up-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.buttonBackDownSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-down-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.buttonBackDisabledSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-disabled-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.buttonForwardUpSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-up-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.buttonForwardDownSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-down-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.buttonForwardDisabledSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-disabled-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL);
this.tabDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-down-skin""), TAB_SCALE_9_GRID);
this.tabSelectedSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-selected-skin""), TAB_SCALE_9_GRID);
this.tabSelectedDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-selected-disabled-skin""), TAB_SCALE_9_GRID);
this.thumbSkinTextures = new Scale9Textures(this.atlas.getTexture(""thumb-skin""), SCALE_9_GRID);
this.thumbDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""thumb-disabled-skin""), SCALE_9_GRID);
this.scrollBarThumbSkinTextures = new Scale9Textures(this.atlas.getTexture(""scrollbar-thumb-skin""), SCROLLBAR_THUMB_SCALE_9_GRID);
this.insetBackgroundSkinTextures = new Scale9Textures(this.atlas.getTexture(""inset-background-skin""), SCALE_9_GRID);
this.insetBackgroundDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""inset-background-disabled-skin""), SCALE_9_GRID);
this.dropDownArrowTexture = this.atlas.getTexture(""drop-down-arrow"");
this.searchIconTexture = this.atlas.getTexture(""search-icon"");
this.listItemUpTextures = new Scale9Textures(this.atlas.getTexture(""list-item-up""), LIST_ITEM_SCALE_9_GRID);
this.listItemDownTextures = new Scale9Textures(this.atlas.getTexture(""list-item-down""), LIST_ITEM_SCALE_9_GRID);
this.listItemSelectedTextures = new Scale9Textures(this.atlas.getTexture(""list-item-selected""), LIST_ITEM_SCALE_9_GRID);
this.pickerListItemSelectedIconTexture = this.atlas.getTexture(""picker-list-item-selected-icon"");
this.headerSkinTextures = new Scale9Textures(this.atlas.getTexture(""header-skin""), HEADER_SCALE_9_GRID);
this.popUpBackgroundSkinTextures = new Scale9Textures(this.atlas.getTexture(""callout-background-skin""), BUTTON_SCALE_9_GRID);
this.calloutTopArrowSkinTexture = this.atlas.getTexture(""callout-arrow-top"");
this.calloutBottomArrowSkinTexture = this.atlas.getTexture(""callout-arrow-bottom"");
this.calloutLeftArrowSkinTexture = this.atlas.getTexture(""callout-arrow-left"");
this.calloutRightArrowSkinTexture = this.atlas.getTexture(""callout-arrow-right"");
this.checkIconTexture = this.atlas.getTexture(""check-icon"");
this.checkDisabledIconTexture = this.atlas.getTexture(""check-disabled-icon"");
this.checkSelectedIconTexture = this.atlas.getTexture(""check-selected-icon"");
this.checkSelectedDisabledIconTexture = this.atlas.getTexture(""check-selected-disabled-icon"");
this.radioIconTexture = this.atlas.getTexture(""radio-icon"");
this.radioDisabledIconTexture = this.atlas.getTexture(""radio-disabled-icon"");
this.radioSelectedIconTexture = this.atlas.getTexture(""radio-selected-icon"");
this.radioSelectedDisabledIconTexture = this.atlas.getTexture(""radio-selected-disabled-icon"");
this.pageIndicatorNormalSkinTexture = this.atlas.getTexture(""page-indicator-normal-skin"");
this.pageIndicatorSelectedSkinTexture = this.atlas.getTexture(""page-indicator-selected-skin"");
StandardIcons.listDrillDownAccessoryTexture = this.atlas.getTexture(""list-accessory-drill-down-icon"");
this.primaryTextFormat = new BitmapFontTextFormat(bitmapFont, this.fontSize, PRIMARY_TEXT_COLOR);
this.disabledTextFormat = new BitmapFontTextFormat(bitmapFont, this.fontSize, DISABLED_TEXT_COLOR);
FeathersControl.defaultTextRendererFactory = textRendererFactory;
FeathersControl.defaultTextEditorFactory = textEditorFactory;
this.setInitializerForClassAndSubclasses(Screen, screenInitializer);
this.setInitializerForClassAndSubclasses(PanelScreen, panelScreenInitializer);
this.setInitializerForClass(Label, labelInitializer);
this.setInitializerForClass(ScrollText, scrollTextInitializer);
this.setInitializerForClass(BitmapFontTextRenderer, itemRendererAccessoryLabelInitializer, BaseDefaultItemRenderer.DEFAULT_CHILD_NAME_ACCESSORY_LABEL);
this.setInitializerForClass(BitmapFontTextRenderer, alertMessageInitializer, Alert.DEFAULT_CHILD_NAME_MESSAGE);
this.setInitializerForClass(Button, buttonInitializer);
this.setInitializerForClass(Button, buttonCallToActionInitializer, Button.ALTERNATE_NAME_CALL_TO_ACTION_BUTTON);
this.setInitializerForClass(Button, buttonQuietInitializer, Button.ALTERNATE_NAME_QUIET_BUTTON);
this.setInitializerForClass(Button, buttonDangerInitializer, Button.ALTERNATE_NAME_DANGER_BUTTON);
this.setInitializerForClass(Button, buttonBackInitializer, Button.ALTERNATE_NAME_BACK_BUTTON);
this.setInitializerForClass(Button, buttonForwardInitializer, Button.ALTERNATE_NAME_FORWARD_BUTTON);
this.setInitializerForClass(Button, buttonGroupButtonInitializer, ButtonGroup.DEFAULT_CHILD_NAME_BUTTON);
this.setInitializerForClass(Button, sliderThumbInitializer, Slider.DEFAULT_CHILD_NAME_THUMB);
this.setInitializerForClass(Button, simpleScrollBarThumbInitializer, SimpleScrollBar.DEFAULT_CHILD_NAME_THUMB);
this.setInitializerForClass(Button, nothingInitializer, Slider.DEFAULT_CHILD_NAME_MINIMUM_TRACK);
this.setInitializerForClass(Button, nothingInitializer, Slider.DEFAULT_CHILD_NAME_MAXIMUM_TRACK);
this.setInitializerForClass(Button, toggleSwitchOnTrackInitializer, ToggleSwitch.DEFAULT_CHILD_NAME_ON_TRACK);
this.setInitializerForClass(Button, toggleSwitchThumbInitializer, ToggleSwitch.DEFAULT_CHILD_NAME_THUMB);
this.setInitializerForClass(Button, tabInitializer, TabBar.DEFAULT_CHILD_NAME_TAB);
this.setInitializerForClass(Button, pickerListButtonInitializer, PickerList.DEFAULT_CHILD_NAME_BUTTON);
this.setInitializerForClass(ButtonGroup, buttonGroupInitializer);
this.setInitializerForClass(ButtonGroup, alertButtonGroupInitializer, Alert.DEFAULT_CHILD_NAME_BUTTON_GROUP);
this.setInitializerForClass(Slider, sliderInitializer);
this.setInitializerForClass(ToggleSwitch, toggleSwitchInitializer);
this.setInitializerForClass(NumericStepper, numericStepperInitializer);
this.setInitializerForClass(Check, checkInitializer);
this.setInitializerForClass(Radio, radioInitializer);
this.setInitializerForClass(DefaultListItemRenderer, itemRendererInitializer);
this.setInitializerForClass(DefaultListItemRenderer, pickerListItemRendererInitializer, COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER);
this.setInitializerForClass(DefaultGroupedListItemRenderer, itemRendererInitializer);
this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, headerOrFooterRendererInitializer);
this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, insetHeaderOrFooterRendererInitializer, GroupedList.ALTERNATE_CHILD_NAME_INSET_HEADER_RENDERER);
this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, insetHeaderOrFooterRendererInitializer, GroupedList.ALTERNATE_CHILD_NAME_INSET_FOOTER_RENDERER);
this.setInitializerForClass(List, listInitializer);
this.setInitializerForClass(List, nothingInitializer, PickerList.DEFAULT_CHILD_NAME_LIST);
this.setInitializerForClass(GroupedList, groupedListInitializer);
this.setInitializerForClass(GroupedList, groupedListInsetInitializer, GroupedList.ALTERNATE_NAME_INSET_GROUPED_LIST);
this.setInitializerForClass(PickerList, pickerListInitializer);
this.setInitializerForClass(Header, headerInitializer);
this.setInitializerForClass(Header, panelHeaderInitializer, Panel.DEFAULT_CHILD_NAME_HEADER);
this.setInitializerForClass(Header, panelHeaderInitializer, Alert.DEFAULT_CHILD_NAME_HEADER);
this.setInitializerForClass(TextInput, textInputInitializer);
this.setInitializerForClass(TextInput, searchTextInputInitializer, TextInput.ALTERNATE_NAME_SEARCH_TEXT_INPUT);
this.setInitializerForClass(TextInput, numericStepperTextInputInitializer, NumericStepper.DEFAULT_CHILD_NAME_TEXT_INPUT);
this.setInitializerForClass(PageIndicator, pageIndicatorInitializer);
this.setInitializerForClass(ProgressBar, progressBarInitializer);
this.setInitializerForClass(Callout, calloutInitializer);
this.setInitializerForClass(Panel, panelInitializer);
this.setInitializerForClass(Alert, alertInitializer);
this.setInitializerForClass(ScrollContainer, scrollContainerToolbarInitializer, ScrollContainer.ALTERNATE_NAME_TOOLBAR);
}
protected function pageIndicatorNormalSymbolFactory():DisplayObject
{
const symbol:ImageLoader = new ImageLoader();
symbol.source = this.pageIndicatorNormalSkinTexture;
symbol.textureScale = this.scale;
return symbol;
}
protected function pageIndicatorSelectedSymbolFactory():DisplayObject
{
const symbol:ImageLoader = new ImageLoader();
symbol.source = this.pageIndicatorSelectedSkinTexture;
symbol.textureScale = this.scale;
return symbol;
}
protected function imageLoaderFactory():ImageLoader
{
const image:ImageLoader = new ImageLoader();
image.smoothing = TextureSmoothing.NONE;
image.textureScale = this.scale;
return image;
}
protected function nothingInitializer(target:DisplayObject):void
{
//if this is assigned as an initializer, chances are the target will
//be a subcomponent of something. the initializer for this
//component's parent is probably handing the initializing for the
//target too.
}
protected function screenInitializer(screen:Screen):void
{
screen.originalDPI = this._originalDPI;
}
protected function panelScreenInitializer(screen:PanelScreen):void
{
screen.originalDPI = this._originalDPI;
}
protected function labelInitializer(label:Label):void
{
label.textRendererProperties.textFormat = this.primaryTextFormat;
label.textRendererProperties.disabledTextFormat = this.disabledTextFormat;
}
protected function itemRendererAccessoryLabelInitializer(renderer:BitmapFontTextRenderer):void
{
renderer.textFormat = this.primaryTextFormat;
}
protected function alertMessageInitializer(renderer:BitmapFontTextRenderer):void
{
renderer.wordWrap = true;
renderer.textFormat = this.primaryTextFormat;
}
protected function scrollTextInitializer(text:ScrollText):void
{
text.textFormat = new TextFormat(""PF Ronda Seven,Roboto,Helvetica,Arial,_sans"", this.fontSize, PRIMARY_TEXT_COLOR);
text.paddingTop = text.paddingBottom = text.paddingLeft = 32 * this.scale;
text.paddingRight = 36 * this.scale;
}
protected function baseButtonInitializer(button:Button):void
{
button.defaultLabelProperties.textFormat = this.primaryTextFormat;
button.disabledLabelProperties.textFormat = this.disabledTextFormat;
button.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
button.paddingTop = button.paddingBottom = 8 * this.scale;
button.paddingLeft = button.paddingRight = 16 * this.scale;
button.gap = 12 * this.scale;
button.minWidth = 66 * this.scale;
button.minHeight = 66 * this.scale;
button.minTouchWidth = button.minTouchHeight = 88 * this.scale;
}
protected function buttonInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonUpSkinTextures;
skinSelector.defaultSelectedValue = this.buttonSelectedSkinTextures;
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, true);
skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.setValueForState(this.buttonSelectedDisabledSkinTextures, Button.STATE_DISABLED, true);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
}
protected function buttonCallToActionInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonCallToActionUpSkinTextures;
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
}
protected function buttonQuietInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonQuietUpSkinTextures;
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
}
protected function buttonDangerInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonDangerUpSkinTextures;
skinSelector.setValueForState(this.buttonDangerDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
}
protected function buttonBackInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonBackUpSkinTextures;
skinSelector.setValueForState(this.buttonBackDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonBackDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
button.paddingLeft = 38 * this.scale;
}
protected function buttonForwardInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonForwardUpSkinTextures;
skinSelector.setValueForState(this.buttonForwardDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonForwardDisabledSkinTextures, Button.STATE_DISABLED, false);
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
this.baseButtonInitializer(button);
button.paddingRight = 38 * this.scale
}
protected function buttonGroupButtonInitializer(button:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.buttonUpSkinTextures;
skinSelector.defaultSelectedValue = this.buttonSelectedSkinTextures;
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, true);
skinSelector.setValueForState(this.buttonSelectedSkinTextures, Button.STATE_DISABLED, false);
skinSelector.setValueForState(this.buttonSelectedDisabledSkinTextures, Button.STATE_DISABLED, true);
skinSelector.displayObjectProperties =
{
width: 88 * this.scale,
height: 88 * this.scale,
textureScale: this.scale
};
button.stateToSkinFunction = skinSelector.updateValue;
button.defaultLabelProperties.textFormat = this.primaryTextFormat;
button.disabledLabelProperties.textFormat = this.disabledTextFormat;
button.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
button.paddingTop = button.paddingBottom = 8 * this.scale;
button.paddingLeft = button.paddingRight = 16 * this.scale;
button.gap = 12 * this.scale;
button.minWidth = 88 * this.scale;
button.minHeight = 88 * this.scale;
button.minTouchWidth = button.minTouchHeight = 88 * this.scale;
}
protected function tabInitializer(tab:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.headerSkinTextures;
skinSelector.defaultSelectedValue = this.tabSelectedSkinTextures;
skinSelector.setValueForState(this.tabDownSkinTextures, Button.STATE_DOWN, false);
skinSelector.setValueForState(this.tabSelectedDisabledSkinTextures, Button.STATE_DISABLED, true);
skinSelector.displayObjectProperties =
{
width: 88 * this.scale,
height: 88 * this.scale,
textureScale: this.scale
};
tab.stateToSkinFunction = skinSelector.updateValue;
tab.defaultLabelProperties.textFormat = this.primaryTextFormat;
tab.disabledLabelProperties.textFormat = this.disabledTextFormat;
tab.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
tab.iconPosition = Button.ICON_POSITION_TOP;
tab.paddingTop = tab.paddingRight = tab.paddingBottom =
tab.paddingLeft = 28 * this.scale;
tab.gap = 12 * this.scale;
tab.minWidth = tab.minHeight = 88 * this.scale;
tab.minTouchWidth = tab.minTouchHeight = 88 * this.scale;
}
protected function simpleScrollBarThumbInitializer(thumb:Button):void
{
const defaultSkin:Scale9Image = new Scale9Image(scrollBarThumbSkinTextures, this.scale);
defaultSkin.width = 8 * this.scale;
defaultSkin.height = 8 * this.scale;
thumb.defaultSkin = defaultSkin;
thumb.minTouchWidth = thumb.minTouchHeight = 12 * this.scale;
}
protected function buttonGroupInitializer(group:ButtonGroup):void
{
group.minWidth = 560 * this.scale;
group.gap = 16 * this.scale;
}
protected function alertButtonGroupInitializer(group:ButtonGroup):void
{
group.direction = ButtonGroup.DIRECTION_VERTICAL;
group.horizontalAlign = ButtonGroup.HORIZONTAL_ALIGN_JUSTIFY;
group.verticalAlign = ButtonGroup.VERTICAL_ALIGN_JUSTIFY;
group.gap = 14 * this.scale;
group.paddingTop = 14 * this.scale;
group.paddingRight = 14 * this.scale;
group.paddingBottom = 14 * this.scale;
group.paddingLeft = 14 * this.scale;
}
protected function sliderInitializer(slider:Slider):void
{
slider.trackLayoutMode = Slider.TRACK_LAYOUT_MODE_SINGLE;
const sliderTrackDefaultSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale);
if(slider.direction == Slider.DIRECTION_VERTICAL)
{
sliderTrackDefaultSkin.width = 66 * this.scale;
sliderTrackDefaultSkin.height = 198 * this.scale;
}
else //horizontal
{
sliderTrackDefaultSkin.width = 198 * this.scale;
sliderTrackDefaultSkin.height = 66 * this.scale;
}
slider.minimumTrackProperties.defaultSkin = sliderTrackDefaultSkin;
}
protected function sliderThumbInitializer(thumb:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.thumbSkinTextures;
skinSelector.defaultSelectedValue = this.thumbDisabledSkinTextures;
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
thumb.stateToSkinFunction = skinSelector.updateValue;
thumb.minTouchWidth = thumb.minTouchHeight = 88 * this.scale;
}
protected function numericStepperInitializer(stepper:NumericStepper):void
{
stepper.buttonLayoutMode = NumericStepper.BUTTON_LAYOUT_MODE_SPLIT_HORIZONTAL;
stepper.incrementButtonLabel = ""+"";
stepper.decrementButtonLabel = ""-"";
}
protected function toggleSwitchInitializer(toggleSwitch:ToggleSwitch):void
{
toggleSwitch.trackLayoutMode = ToggleSwitch.TRACK_LAYOUT_MODE_SINGLE;
toggleSwitch.defaultLabelProperties.textFormat = this.primaryTextFormat;
toggleSwitch.disabledLabelProperties.textFormat = this.disabledTextFormat;
}
protected function toggleSwitchOnTrackInitializer(track:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.insetBackgroundSkinTextures;
skinSelector.defaultSelectedValue = this.insetBackgroundDisabledSkinTextures;
skinSelector.displayObjectProperties =
{
width: 148 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
track.stateToSkinFunction = skinSelector.updateValue;
track.minTouchWidth = track.minTouchHeight = 88 * this.scale;
}
protected function toggleSwitchThumbInitializer(thumb:Button):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.thumbSkinTextures;
skinSelector.defaultSelectedValue = this.thumbDisabledSkinTextures;
skinSelector.displayObjectProperties =
{
width: 66 * this.scale,
height: 66 * this.scale,
textureScale: this.scale
};
thumb.stateToSkinFunction = skinSelector.updateValue;
thumb.minTouchWidth = thumb.minTouchHeight = 88 * this.scale;
}
protected function checkInitializer(check:Check):void
{
const iconSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
iconSelector.defaultValue = this.checkIconTexture;
iconSelector.defaultSelectedValue = this.checkSelectedIconTexture;
iconSelector.setValueForState(this.checkDisabledIconTexture, Button.STATE_DISABLED, false);
iconSelector.setValueForState(this.checkSelectedDisabledIconTexture, Button.STATE_DISABLED, true);
iconSelector.displayObjectProperties =
{
scaleX: this.scale,
scaleY: this.scale
};
check.stateToIconFunction = iconSelector.updateValue;
check.defaultLabelProperties.textFormat = this.primaryTextFormat;
check.disabledLabelProperties.textFormat = this.disabledTextFormat;
check.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
check.gap = 12 * this.scale;
check.minTouchWidth = check.minTouchHeight = 88 * this.scale;
check.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT;
check.verticalAlign = Button.VERTICAL_ALIGN_MIDDLE;
}
protected function radioInitializer(radio:Radio):void
{
const iconSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
iconSelector.defaultValue = this.radioIconTexture;
iconSelector.defaultSelectedValue = this.radioSelectedIconTexture;
iconSelector.setValueForState(this.radioDisabledIconTexture, Button.STATE_DISABLED, false);
iconSelector.setValueForState(this.radioSelectedDisabledIconTexture, Button.STATE_DISABLED, true);
iconSelector.displayObjectProperties =
{
scaleX: this.scale,
scaleY: this.scale
};
radio.stateToIconFunction = iconSelector.updateValue;
radio.defaultLabelProperties.textFormat = this.primaryTextFormat;
radio.disabledLabelProperties.textFormat = this.disabledTextFormat;
radio.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
radio.gap = 12 * this.scale;
radio.minTouchWidth = radio.minTouchHeight = 88 * this.scale;
radio.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT;
radio.verticalAlign = Button.VERTICAL_ALIGN_MIDDLE;
}
protected function itemRendererInitializer(renderer:BaseDefaultItemRenderer):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.listItemUpTextures;
skinSelector.defaultSelectedValue = this.listItemSelectedTextures;
skinSelector.setValueForState(this.listItemDownTextures, Button.STATE_DOWN, false);
skinSelector.displayObjectProperties =
{
width: 88 * this.scale,
height: 88 * this.scale,
textureScale: this.scale
};
renderer.stateToSkinFunction = skinSelector.updateValue;
renderer.defaultLabelProperties.textFormat = this.primaryTextFormat;
renderer.disabledLabelProperties.textFormat = this.disabledTextFormat;
renderer.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
renderer.paddingTop = renderer.paddingBottom = 11 * this.scale;
renderer.paddingLeft = renderer.paddingRight = 16 * this.scale;
renderer.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT;
renderer.minWidth = renderer.minHeight = 88 * this.scale;
renderer.gap = 10 * this.scale;
renderer.iconPosition = Button.ICON_POSITION_LEFT;
renderer.accessoryGap = Number.POSITIVE_INFINITY;
renderer.accessoryPosition = BaseDefaultItemRenderer.ACCESSORY_POSITION_RIGHT;
renderer.accessoryLoaderFactory = this.imageLoaderFactory;
renderer.iconLoaderFactory = this.imageLoaderFactory;
}
protected function pickerListItemRendererInitializer(renderer:BaseDefaultItemRenderer):void
{
const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector();
skinSelector.defaultValue = this.listItemUpTextures;
skinSelector.setValueForState(this.listItemDownTextures, Button.STATE_DOWN, false);
skinSelector.displayObjectProperties =
{
width: 88 * this.scale,
height: 88 * this.scale,
textureScale: this.scale
};
renderer.stateToSkinFunction = skinSelector.updateValue;
const defaultSelectedIcon:ImageLoader = new ImageLoader();
defaultSelectedIcon.source = this.pickerListItemSelectedIconTexture;
defaultSelectedIcon.textureScale = this.scale;
defaultSelectedIcon.snapToPixels = true;
renderer.defaultSelectedIcon = defaultSelectedIcon;
const defaultIcon:Quad = new Quad(defaultSelectedIcon.width, defaultSelectedIcon.height, 0xff00ff);
defaultIcon.alpha = 0;
renderer.defaultIcon = defaultIcon;
renderer.defaultLabelProperties.textFormat = this.primaryTextFormat;
renderer.disabledLabelProperties.textFormat = this.disabledTextFormat;
renderer.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat;
renderer.paddingTop = renderer.paddingBottom = 11 * this.scale;
renderer.paddingLeft = renderer.paddingRight = 16 * this.scale;
renderer.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT;
renderer.minWidth = renderer.minHeight = 88 * this.scale;
renderer.iconPosition = Button.ICON_POSITION_RIGHT;
renderer.gap = Number.POSITIVE_INFINITY;
renderer.accessoryLoaderFactory = this.imageLoaderFactory;
renderer.iconLoaderFactory = this.imageLoaderFactory;
}
protected function headerOrFooterRendererInitializer(renderer:DefaultGroupedListHeaderOrFooterRenderer):void
{
const backgroundSkin:Quad = new Quad(44 * this.scale, 44 * this.scale, LIST_HEADER_BACKGROUND_COLOR);
renderer.backgroundSkin = backgroundSkin;
renderer.contentLabelProperties.textFormat = this.primaryTextFormat;
renderer.paddingTop = renderer.paddingBottom = 6 * this.scale;
renderer.paddingLeft = renderer.paddingRight = 24 * this.scale;
renderer.minWidth = renderer.minHeight = 44 * this.scale;
renderer.contentLoaderFactory = this.imageLoaderFactory;
}
protected function insetHeaderOrFooterRendererInitializer(renderer:DefaultGroupedListHeaderOrFooterRenderer):void
{
renderer.contentLabelProperties.textFormat = this.primaryTextFormat;
renderer.paddingTop = renderer.paddingBottom = 6 * this.scale;
renderer.paddingLeft = renderer.paddingRight = 24 * this.scale;
renderer.minWidth = renderer.minHeight = 66 * this.scale;
renderer.contentLoaderFactory = this.imageLoaderFactory;
}
protected function listInitializer(list:List):void
{
const backgroundSkin:Quad = new Quad(88 * this.scale, 88 * this.scale, LIST_BACKGROUND_COLOR);
list.backgroundSkin = backgroundSkin;
}
protected function groupedListInitializer(list:GroupedList):void
{
const backgroundSkin:Quad = new Quad(88 * this.scale, 88 * this.scale, LIST_BACKGROUND_COLOR);
list.backgroundSkin = backgroundSkin;
}
protected function groupedListInsetInitializer(list:GroupedList):void
{
list.headerRendererName = GroupedList.ALTERNATE_CHILD_NAME_INSET_HEADER_RENDERER;
list.footerRendererName = GroupedList.ALTERNATE_CHILD_NAME_INSET_FOOTER_RENDERER;
const layout:VerticalLayout = new VerticalLayout();
layout.useVirtualLayout = true;
layout.padding = 24 * this.scale;
layout.paddingTop = 4 * this.scale;
layout.gap = 0;
layout.horizontalAlign = VerticalLayout.HORIZONTAL_ALIGN_JUSTIFY;
layout.verticalAlign = VerticalLayout.VERTICAL_ALIGN_TOP;
list.layout = layout;
}
protected function pickerListInitializer(list:PickerList):void
{
if(DeviceCapabilities.isTablet(Starling.current.nativeStage))
{
list.popUpContentManager = new CalloutPopUpContentManager();
}
else
{
const centerStage:VerticalCenteredPopUpContentManager = new VerticalCenteredPopUpContentManager();
centerStage.marginTop = centerStage.marginRight = centerStage.marginBottom =
centerStage.marginLeft = 16 * this.scale;
list.popUpContentManager = centerStage;
}
const layout:VerticalLayout = new VerticalLayout();
layout.verticalAlign = VerticalLayout.VERTICAL_ALIGN_BOTTOM;
layout.horizontalAlign = VerticalLayout.HORIZONTAL_ALIGN_JUSTIFY;
layout.useVirtualLayout = true;
layout.gap = 0;
layout.paddingTop = layout.paddingRight = layout.paddingBottom =
layout.paddingLeft = 0;
list.listProperties.layout = layout;
list.listProperties.verticalScrollPolicy = List.SCROLL_POLICY_ON;
if(DeviceCapabilities.isTablet(Starling.current.nativeStage))
{
list.listProperties.minWidth = 560 * this.scale;
list.listProperties.maxHeight = 528 * this.scale;
}
else
{
const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale);
backgroundSkin.width = 20 * this.scale;
backgroundSkin.height = 20 * this.scale;
list.listProperties.backgroundSkin = backgroundSkin;
list.listProperties.paddingTop = list.listProperties.paddingRight =
list.listProperties.paddingBottom = list.listProperties.paddingLeft = 4 * this.scale;
}
list.listProperties.itemRendererName = COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER;
}
protected function pickerListButtonInitializer(button:Button):void
{
//we're going to expand on the standard button styles
this.buttonInitializer(button);
const defaultIcon:Image = new Image(dropDownArrowTexture);
defaultIcon.scaleX = defaultIcon.scaleY = this.scale;
button.defaultIcon = defaultIcon;
button.gap = Number.POSITIVE_INFINITY, //fill as completely as possible
button.iconPosition = Button.ICON_POSITION_RIGHT;
button.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT;
}
protected function headerInitializer(header:Header):void
{
header.minWidth = 88 * this.scale;
header.minHeight = 88 * this.scale;
header.paddingTop = header.paddingRight = header.paddingBottom =
header.paddingLeft = 14 * this.scale;
header.gap = 8 * this.scale;
header.titleGap = 12 * this.scale;
const backgroundSkin:Scale9Image = new Scale9Image(headerSkinTextures, this.scale);
backgroundSkin.width = 88 * this.scale;
backgroundSkin.height = 88 * this.scale;
header.backgroundSkin = backgroundSkin;
header.titleProperties.textFormat = this.primaryTextFormat;
header.titleProperties.disabledTextFormat = this.disabledTextFormat;
}
protected function panelHeaderInitializer(header:Header):void
{
header.minWidth = 88 * this.scale;
header.minHeight = 88 * this.scale;
header.paddingTop = header.paddingBottom = 18 * this.scale;
header.paddingLeft = header.paddingRight = 14 * this.scale;
header.gap = 8 * this.scale;
header.titleGap = 12 * this.scale;
const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale);
backgroundSkin.width = 88 * this.scale;
backgroundSkin.height = 88 * this.scale;
header.backgroundSkin = backgroundSkin;
header.titleProperties.textFormat = this.primaryTextFormat;
header.titleProperties.disabledTextFormat = this.disabledTextFormat;
}
protected function baseTextInputInitializer(input:TextInput):void
{
input.minWidth = input.minHeight = 66 * this.scale;
input.minTouchWidth = input.minTouchHeight = 66 * this.scale;
input.gap = 8 * this.scale;
input.paddingTop = 14 * this.scale;
input.paddingBottom = 8 * this.scale;
input.paddingLeft = input.paddingRight = 16 * this.scale;
input.textEditorProperties.fontFamily = ""_sans"";
input.textEditorProperties.fontSize = this.inputFontSize;
input.textEditorProperties.color = PRIMARY_TEXT_COLOR;
const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale);
backgroundSkin.width = 264 * this.scale;
backgroundSkin.height = 66 * this.scale;
input.backgroundSkin = backgroundSkin;
const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale);
backgroundDisabledSkin.width = 264 * this.scale;
backgroundDisabledSkin.height = 66 * this.scale;
input.backgroundDisabledSkin = backgroundDisabledSkin;
input.promptProperties.textFormat = this.primaryTextFormat;
input.promptProperties.disabledTextFormat = this.disabledTextFormat;
}
protected function textInputInitializer(input:TextInput):void
{
this.baseTextInputInitializer(input);
}
protected function searchTextInputInitializer(input:TextInput):void
{
this.baseTextInputInitializer(input);
var searchIcon:ImageLoader = new ImageLoader();
searchIcon.source = this.searchIconTexture;
searchIcon.snapToPixels = true;
input.defaultIcon = searchIcon;
}
protected function numericStepperTextInputInitializer(input:TextInput):void
{
input.minWidth = input.minHeight = 66 * this.scale;
input.minTouchWidth = input.minTouchHeight = 66 * this.scale;
input.gap = 12 * this.scale;
input.paddingTop = input.paddingBottom = 14 * this.scale;
input.paddingLeft = input.paddingRight = 16 * this.scale;
input.isEditable = false;
input.textEditorProperties.fontFamily = ""_sans"";
input.textEditorProperties.fontSize = this.inputFontSize;
input.textEditorProperties.color = PRIMARY_TEXT_COLOR;
input.textEditorProperties.textAlign = TextFormatAlign.CENTER;
const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale);
backgroundSkin.width = 66 * this.scale;
backgroundSkin.height = 66 * this.scale;
input.backgroundSkin = backgroundSkin;
const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale);
backgroundDisabledSkin.width = 66 * this.scale;
backgroundDisabledSkin.height = 66 * this.scale;
input.backgroundDisabledSkin = backgroundDisabledSkin;
}
protected function pageIndicatorInitializer(pageIndicator:PageIndicator):void
{
pageIndicator.normalSymbolFactory = this.pageIndicatorNormalSymbolFactory;
pageIndicator.selectedSymbolFactory = this.pageIndicatorSelectedSymbolFactory;
pageIndicator.gap = 12 * this.scale;
pageIndicator.paddingTop = pageIndicator.paddingRight = pageIndicator.paddingBottom =
pageIndicator.paddingLeft = 12 * this.scale;
pageIndicator.minTouchWidth = pageIndicator.minTouchHeight = 44 * this.scale;
}
protected function progressBarInitializer(progress:ProgressBar):void
{
const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale);
backgroundSkin.width = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 264 : 22) * this.scale;
backgroundSkin.height = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 22 : 264) * this.scale;
progress.backgroundSkin = backgroundSkin;
const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale);
backgroundDisabledSkin.width = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 264 : 22) * this.scale;
backgroundDisabledSkin.height = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 22 : 264) * this.scale;
progress.backgroundDisabledSkin = backgroundDisabledSkin;
const fillSkin:Scale9Image = new Scale9Image(buttonUpSkinTextures, this.scale);
fillSkin.width = 12 * this.scale;
fillSkin.height = 12 * this.scale;
progress.fillSkin = fillSkin;
const fillDisabledSkin:Scale9Image = new Scale9Image(buttonDisabledSkinTextures, this.scale);
fillDisabledSkin.width = 12 * this.scale;
fillDisabledSkin.height = 12 * this.scale;
progress.fillDisabledSkin = fillDisabledSkin;
}
protected function calloutInitializer(callout:Callout):void
{
callout.minWidth = 20 * this.scale;
callout.minHeight = 20 * this.scale;
callout.paddingTop = callout.paddingRight = callout.paddingBottom =
callout.paddingLeft = 12 * this.scale;
const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale);
backgroundSkin.width = 20 * this.scale;
backgroundSkin.height = 20 * this.scale;
callout.backgroundSkin = backgroundSkin;
const topArrowSkin:Image = new Image(calloutTopArrowSkinTexture);
topArrowSkin.scaleX = topArrowSkin.scaleY = this.scale;
callout.topArrowSkin = topArrowSkin;
callout.topArrowGap = -8 * this.scale;
const bottomArrowSkin:Image = new Image(calloutBottomArrowSkinTexture);
bottomArrowSkin.scaleX = bottomArrowSkin.scaleY = this.scale;
callout.bottomArrowSkin = bottomArrowSkin;
callout.bottomArrowGap = -8 * this.scale;
const leftArrowSkin:Image = new Image(calloutLeftArrowSkinTexture);
leftArrowSkin.scaleX = leftArrowSkin.scaleY = this.scale;
callout.leftArrowSkin = leftArrowSkin;
callout.leftArrowGap = -8 * this.scale;
const rightArrowSkin:Image = new Image(calloutRightArrowSkinTexture);
rightArrowSkin.scaleX = rightArrowSkin.scaleY = this.scale;
callout.rightArrowSkin = rightArrowSkin;
callout.rightArrowGap = -8 * this.scale;
}
protected function panelInitializer(panel:Panel):void
{
const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale);
backgroundSkin.width = 20 * this.scale;
backgroundSkin.height = 20 * this.scale;
panel.backgroundSkin = backgroundSkin;
panel.paddingTop = panel.paddingRight = panel.paddingBottom =
panel.paddingLeft = 14 * this.scale;
}
protected function alertInitializer(alert:Alert):void
{
const backgroundSkin:Scale9Image = new Scale9Image(this.popUpBackgroundSkinTextures, this.scale);
backgroundSkin.width = 20 * this.scale;
backgroundSkin.height = 20 * this.scale;
alert.backgroundSkin = backgroundSkin;
alert.paddingTop = alert.paddingBottom = 16 * this.scale;
alert.paddingLeft = alert.paddingRight = 32 * this.scale;
alert.maxWidth = alert.maxHeight = 560 * this.scale;
}
protected function scrollContainerToolbarInitializer(container:ScrollContainer):void
{
if(!container.layout)
{
const layout:HorizontalLayout = new HorizontalLayout();
layout.paddingTop = layout.paddingRight = layout.paddingBottom =
layout.paddingLeft = 14 * this.scale;
layout.gap = 8 * this.scale;
container.layout = layout;
}
container.minWidth = 88 * this.scale;
container.minHeight = 88 * this.scale;
const backgroundSkin:Scale9Image = new Scale9Image(headerSkinTextures, this.scale);
backgroundSkin.width = 88 * this.scale;
backgroundSkin.height = 88 * this.scale;
container.backgroundSkin = backgroundSkin;
}
protected function root_addedToStageHandler(event:Event):void
{
DisplayObject(event.currentTarget).stage.color = BACKGROUND_COLOR;
}
}
}",12267,False,2495.3184102323976,median
"////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the ""License""); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an ""AS IS"" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core
{
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.events.ContextMenuEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.external.ExternalInterface;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.Capabilities;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.utils.setInterval;
import mx.containers.utilityClasses.ApplicationLayout;
import mx.effects.EffectManager;
import mx.events.FlexEvent;
import mx.managers.FocusManager;
import mx.managers.IActiveWindowManager;
import mx.managers.ILayoutManager;
import mx.managers.ISystemManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.IStyleClient;
import mx.utils.LoaderUtil;
import mx.utils.Platform;
use namespace mx_internal;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched after the Application has been initialized,
* processed by the LayoutManager, and attached to the display list.
*
* @eventType mx.events.FlexEvent.APPLICATION_COMPLETE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name=""applicationComplete"", type=""mx.events.FlexEvent"")]
/**
* Dispatched when an HTTPService call fails.
*
* @eventType flash.events.ErrorEvent.ERROR
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name=""error"", type=""flash.events.ErrorEvent"")]
//--------------------------------------
// Styles
//--------------------------------------
include ""../styles/metadata/ModalTransparencyStyles.as"";
/**
* Specifies the alpha transparency values used for the background gradient fill of the application.
* You should set this to an Array of two numbers.
* Elements 0 and 1 specify the start and end values for an alpha gradient.
*
* @default [ 1.0, 1.0 ]
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name=""backgroundGradientAlphas"", type=""Array"", arrayType=""Number"", inherit=""no"", theme=""halo"")]
/**
* Specifies the colors used to tint the background gradient fill of the application.
* You should set this to an Array of two uint values that specify RGB colors.
* Elements 0 and 1 specify the start and end values for a color gradient.
* For a solid-color background, set the same color value for elements 0 and 1.
* A value of undefined means background gradient is generated
* based on the backgroundColor property.
*
* @default undefined
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name=""backgroundGradientColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", theme=""halo"")]
/**
* Number of pixels between the application's bottom border
* and its content area.
*
* @default 24
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name=""paddingBottom"", type=""Number"", format=""Length"", inherit=""no"")]
/**
* Number of pixels between the application's top border
* and its content area.
*
* @default 24
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name=""paddingTop"", type=""Number"", format=""Length"", inherit=""no"")]
//--------------------------------------
// Excluded APIs
//--------------------------------------
[Exclude(name=""direction"", kind=""property"")]
[Exclude(name=""icon"", kind=""property"")]
[Exclude(name=""label"", kind=""property"")]
[Exclude(name=""tabIndex"", kind=""property"")]
[Exclude(name=""toolTip"", kind=""property"")]
[Exclude(name=""x"", kind=""property"")]
[Exclude(name=""y"", kind=""property"")]
//--------------------------------------
// Other metadata
//--------------------------------------
/**
* The frameworks must be initialized by SystemManager.
* This factoryClass will be automatically subclassed by any
* MXML applications that don't explicitly specify a different
* factoryClass.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Frame(factoryClass=""mx.managers.SystemManager"")]
[ResourceBundle(""core"")]
[Alternative(replacement=""spark.components.Application"", since=""4.0"")]
/**
* Flex defines a default, or Application, container that lets you start
* adding content to your application without explicitly defining
* another container.
* Flex creates this container from the <mx:Application>
* tag, the first tag in an MXML application file.
* While you might find it convenient to use the Application container
* as the only container in your application, in most cases you explicitly
* define at least one more container before you add any controls
* to your application.
*
*
Applications support a predefined plain style that sets
* a white background, left alignment, and removes all margins.
* To use this style, do the following:
*
*
* <mx:Application styleName=""plain"" />
*
*
*
This is equivalent to setting the following style attributes:
*
* @includeExample examples/SimpleApplicationExample.mxml
*
* @see mx.managers.CursorManager
* @see mx.managers.LayoutManager
* @see mx.managers.SystemManager
* @see flash.events.EventDispatcher
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class Application extends LayoutContainer
{
include ""../core/Version.as"";
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
mx_internal static var useProgressiveLayout:Boolean = false;
//--------------------------------------------------------------------------
//
// Class properties
//
//--------------------------------------------------------------------------
/**
* A reference to the top-level application.
*
*
In general, there can be a hierarchy of Application objects,
* because an Application can use a SWFLoader control to dynamically
* load another Application.
* The parentApplication property of a UIComponent can be
* used to access the sub-Application in which that UIComponent lives,
* and to walk up the hierarchy to the top-level Application.
*
*
This property has been deprecated starting in Flex4. Note that this
* property will still return applications of type mx.core.Application and
* mx.core.WindowedApplication as in previous versions. Starting in Flex 4
* it will also return applications of type spark.components.Application or
* spark.components.WindowedApplication.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
/*
* Note: here are two reasons that 'application' is typed as Object
* rather than as Application. The first is for consistency with
* the 'parentApplication' property of UIComponent. That property is not
* typed as Application because it would make UIComponent dependent
* on Application, slowing down compile times not only for SWCs
* for also for MXML and AS components. Second, if it were typed
* as Application, authors would not be able to access properties
* and methods in the ' +
' ' +
' RRX9856' +
' 42.50' +
' ' +
' Red' +
' Navy' +
' Burgundy' +
' ' +
' ' +
' Red' +
' Navy' +
' Burgundy' +
' Black' +
' ' +
' ' +
' Navy' +
' Black' +
' ' +
' ' +
' Burgundy' +
' Black' +
' ' +
' ' +
' ' +
'';
quotedXML = ;
xml = new XML(xmlStr);
text = ""hi"";
xml2 = new XML('hiyeah!');
}
[AfterClass]
public static function tearDownAfterClass():void
{
xmlStr = null;
quotedXML = null;
xml = null;
text = null;
xml2 = null;
}
[Test]
public function testSimpleAttributes():void
{
var xml1:XML = ;
assertTrue( xml1.hasOwnProperty(""@baz""), ' should have attribute @baz');
assertFalse( xml1.hasOwnProperty(""@foo""), ' should not have attribute @foo');
assertFalse( xml1.hasOwnProperty(""baz""), ' should not have attribute baz');
assertTrue( xml1.toXMLString() == '', ' toXMLString should be ');
assertTrue( xml1.@baz.toString() == 'true', 'xml1.@baz.toString() should be ""true""');
var baz:XMLList = xml1.@baz;
assertTrue( baz.toString() == 'true', 'baz.toString() should be ""true""');
assertEquals( baz.length(),1, 'baz.length() should be 1');
var xml3:XML = ;
xml3.bar.baz = ""baz"";
xml3.foo.@boo = ""boo"";
assertEquals( xml3.bar.baz,'baz', 'xml3.bar.baz should be ""baz""');
assertEquals( xml3.foo.@boo,'boo', 'xml3.foo.@boo should be ""boo""');
}
[Test]
public function testSimpleXMLList():void
{
var xml1:XML = ;
assertTrue( xml1.@baz.toString() == ""true"", 'toString value should be ""true"" ');
var xml3:XML = ;
xml3.bar.baz = ""baz"";
xml3.foo.@boo = ""boo"";
assertEquals( xml3.bar.baz.toString(), ""baz"", 'toString value should be ""baz"" ');
assertEquals( xml3.foo.@boo.toString(), ""boo"", 'toString value should be ""boo"" ');
var newContent:XML = ;
newContent.Properties.Leading.@type = ""string"";
newContent.Properties.Leading = 36;
assertEquals( newContent.Properties.Leading.@type, ""string"", ""Leading should be @type=string"");
assertStrictlyEquals(newContent.Properties.Leading.toString(), ""36"", ""Leading should be 36"");
assertStrictlyEquals(
newContent.toXMLString(),
""\\n"" +
"" \\n"" +
"" 36\\n"" +
"" \\n"" +
"""",
""unexpected toXMLString() value""
);
newContent.Properties.Leading = 72;
assertStrictlyEquals(newContent.Properties.Leading.toString(), ""72"", ""Leading should be 72"");
}
[Test]
public function testMinimum():void{
var xml:XML = new XML();
assertEquals(xml.nodeKind(), 'text', 'unexpected default nodeKind');
assertEquals(xml.toString(), '', 'unexpected default stringification');
}
[Test]
public function testXMLMethods1():void
{
var xml1:XML = ;
var child:XML = ;
xml1.appendChild(child);
child = ;
xml1.appendChild(child);
assertTrue( xml1.pop[0].child.@name.toString() == 'Sam', 'unexpected child result');
assertTrue( xml1.pop[1].child.@name.toString() == 'George', 'unexpected child result');
}
[TestVariance(variance=""JS"", description=""toLocaleString has a substantially different output in javascript"")]
[TestVariance(variance=""SWF"", description=""(observed) some of the XML methods for SWF had incorrect results before swf version 21"")]
[Test]
public function testXMLMethods2():void
{
var xml1:XML = ;
var child:XML = ;
xml1.appendChild(child);
child = ;
xml1.appendChild(child);
assertEquals(
xml1.pop[0].toString(),
'\\n' +
' \\n' +
'', 'unexpected output with xml1.pop[0].toString()');
assertEquals(
xml1.pop[1].toString(),
'\\n' +
' \\n' +
'', 'unexpected output with xml1.pop[1].toString()');
var pop:XMLList = xml1.pop;
pop[pop.length()] = ;
assertEquals(
pop.toString(),
'\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'', 'unexpected output with pop.toString()');
assertEquals(
xml1.toString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected output with xml1.toString()');
pop[0] = ;
assertEquals(
pop.toString(),
'\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'', 'unexpected output with pop.toString()');
assertEquals(
xml1.toString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected output with xml1.toString()');
//toLocaleString
//VARIANCE
var expected:String = isJS
? '\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'' //js
: '[object XML]';// swf
assertEquals(
xml1.toLocaleString(),
expected, 'unexpected output with xml1.toLocaleString()');
expected = isJS
? '\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'\\n' +
'\\n' +
' \\n' +
'' //js
: '[object XMLList]';//swf
assertEquals(
xml1.pop.toLocaleString(),
expected, 'unexpected output with xml1.pop.toLocaleString()');
var parentXML:XML = ;
var childXML:XML = ;
parentXML.appendChild(childXML);
assertTrue( (childXML.parent() == parentXML), 'child/parent relationship was unexpected');
assertEquals(
parentXML.toXMLString(),
'\\n' +
' \\n' +
'', 'unexpected output following re-parenting');
var newParent:XML = ;
newParent.appendChild(childXML);
if (getSwfVersion() < 21) {
//I think, a bug in old swf version, some 'remnant' of the old 'child' is still present in the'old' parent
expected = '\\n' +
' \\n' +
''
} else {
expected = '';
}
assertEquals(
parentXML.toXMLString(),
expected, 'unexpected output following re-parenting');
assertEquals(
newParent.toXMLString(),
'\\n' +
' \\n' +
'', 'unexpected output following re-parenting');
assertFalse( (childXML.parent() == parentXML), 'child/parent relationship was unexpected');
var expectedLength:uint = getSwfVersion() < 21 ? 1 : 0;
//another bug in old swf version, some 'remnant' of the old 'child' is still present in the'old' parent
assertTrue( (parentXML.children().length() == expectedLength), 'child/parent relationship was unexpected');
assertTrue( (childXML.parent() == newParent), 'child/parent relationship was unexpected');
childXML = • Some amazing content;
var childXMLStr:String = childXML.text();
assertEquals( childXMLStr, '•Some amazing content', "" (should be) •Some amazing content"");
}
[Test]
public function testInvalidAppendChild():void{
var root:XML = new XML('test');
root.appendChild('test');
assertEquals(root.toString(), 'test', 'testInvalidAppendChild 1 result is bad');
assertEquals(root.toXMLString(), 'test', 'testInvalidAppendChild 2 result is bad');
}
[Test]
public function testAppendNonXMLChild():void{
var root:XML = ;
root.appendChild('test');
assertEquals(root.toString(), 'test', 'testAppendNonXMLChild 1 result is bad');
assertEquals(root.toXMLString(), 'test', 'testAppendNonXMLChild 2 result is bad');
root = ;
root.appendChild('test');
assertEquals(
root.toString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' test\\n' +
'', 'testAppendNonXMLChild 3 result is bad');
assertEquals(
root.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' test\\n' +
'', 'testAppendNonXMLChild 4 result is bad');
}
[Test]
public function testXMLNormalize():void{
var xml:XML = ;
xml.appendChild(""test1"");
xml.appendChild(""test2"");
xml.appendChild();
xml.appendChild(""test3"");
xml.appendChild(""test4"");
assertEquals(
xml.toString(),
'\\n' +
' test1\\n' +
' test2\\n' +
' \\n' +
' test3\\n' +
' test4\\n' +
'', 'testXMLNormalize 1 result is bad');
assertEquals(
xml.toXMLString(),
'\\n' +
' test1\\n' +
' test2\\n' +
' \\n' +
' test3\\n' +
' test4\\n' +
'', 'testXMLNormalize 2 result is bad');
xml.normalize();
assertEquals(
xml.toString(),
'\\n' +
' test1test2\\n' +
' \\n' +
' test3\\n' +
' test4\\n' +
'', 'testXMLNormalize 3 result is bad');
assertEquals(
xml.toXMLString(),
'\\n' +
' test1test2\\n' +
' \\n' +
' test3\\n' +
' test4\\n' +
'', 'testXMLNormalize 4 result is bad');
}
[Test]
public function testSVG():void
{
var svg:XML = ;
var rects:XMLList = svg..rect;
rects[1].@width = ""100px"";
rects.(@id == 3).@height = ""100px"";
var expected:String =
'' + '\\n'
+ '' + '\\n'
+ '' + '\\n'
+ '';
assertTrue( rects.toXMLString() == expected, 'string output was unexpected');
}
[Test]
public function testChildList():void{
var xml:XML = asdasdas asdasqdasd;
var list:XMLList = xml.*;
assertEquals( 4, list.length(), 'Error in list length');
assertEquals( list.toXMLString(), 'asdasdas\\n' + '\\n' +'asdasqdasd\\n' +'', 'Error in list length');
list = xml.element;
assertEquals( 1, list.length(), 'Error in list length');
assertEquals( list.toXMLString(),'', 'Error in list length');
list = xml.otherElement;
assertEquals( 1, list.length(), 'Error in list length');
assertEquals( list.toXMLString(),'', 'Error in list length');
list = xml.otherElement;
assertEquals( 1, list.length(), 'Error in list length');
}
[Test]
[TestVariance(variance=""JS"",description=""Some browsers (IE11/Edge legacy) can parse to a different order of attributes and namespace declarations (which affects stringified content comparisons)"")]
public function testChildVariants():void{
var xml:XML = asdasdas asdasqdasd;
var list:XMLList = xml.*::*;
assertEquals( 4, list.length(), 'Error in list length');
//IE11/Edge issues
/*assertEquals( list.toXMLString(), '\\n' +
'\\n' +
'\\n' +
'', 'Error in list content');*/
assertEquals( list.toXMLString().length, 212, 'Error in list content');
list = xml.otherElement;
assertEquals( 1, list.length(), 'Error in list length');
//IE11/Edge issues
/* assertEquals( list.toXMLString(),'', 'Error in list content');*/
assertEquals( list.toXMLString().length,51, 'Error in list content');
list = xml.*;
assertEquals( 6, list.length(), 'Error in list length');
/* assertEquals( list.toXMLString(),'asdasdas\\n' +
'\\n' +
'asdasqdasd\\n' +
'\\n' +
'\\n' +
'', 'Error in list content');*/
assertEquals( list.toXMLString().length,232, 'Error in list content');
}
[Test]
public function testNamespaceRetrieval():void{
var content:XML = ;
var namespace:Namespace = content.children()[0].namespace();
assertEquals( namespace.prefix, 'x', 'Error in namespace prefix');
assertEquals( namespace.uri, 'adobe:ns:meta/', 'Error in namespace uri');
}
[Test]
[TestVariance(variance=""JS"",description=""Javascript does not support duplicate namespace declarations (Error thrown)"")]
public function testNamespaceRetrieval2():void{
var caughtError:Boolean;
try {
var content:XML = ;
} catch(e:Error) {
caughtError = true;
}
if (isJS) {
caughtError = !caughtError;
}
assertFalse( caughtError, 'Unexpected Error state with duplicate namespace declarations');
}
[Test]
public function testDuplicateAttributesError():void{
var caughtError:Boolean;
try {
var content:XML = ;
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'Unexpected Error state with duplicate attribute declarations');
}
[Test]
public function testParsingWhitespaceSetting1():void{
var originalSetting:Boolean = XML.ignoreWhitespace;
XML.ignoreWhitespace = true;
var script:XML = ;
assertEquals(1, script.children().length(), 'unexpected children number after parsing');
assertEquals(
'',
script.toXMLString(), 'unexpected toString value after parsing');
XML.ignoreWhitespace = false;
script = ;
assertEquals(3, script.children().length(), 'unexpected children number after parsing');
assertEquals(
'',
script.toXMLString(), 'unexpected toString value after parsing');
XML.ignoreWhitespace = originalSetting;
}
[Test]
public function testSingleProcessingInstructions():void{
var original:Boolean = XML.ignoreProcessingInstructions;
XML.ignoreProcessingInstructions = true;
var xml:XML = new XML('');
assertEquals( 'text', xml.nodeKind(), 'unexpected nodeKind with XML.ignoreProcessingInstructions = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreProcessingInstructions = true');
XML.ignoreProcessingInstructions = false;
xml = new XML('');
assertEquals( 'processing-instruction', xml.nodeKind(), 'unexpected nodeKind with XML.ignoreProcessingInstructions = false');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreProcessingInstructions = false');
XML.ignoreProcessingInstructions = original;
}
[Test]
public function testSingleCDATA():void{
var original:Boolean = XML.ignoreWhitespace;
XML.ignoreWhitespace = true;
var xml:XML = new XML(' ');
assertEquals( 'text', xml.nodeKind(), 'unexpected cdata result with XML.ignoreWhitespace = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true');
assertNull( xml.name(), 'unexpected name value with CDATA');
XML.ignoreWhitespace = false;
var caughtError:Boolean = false;
try {
xml = new XML(' ');
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status for single cdata string parsing with XML.ignoreWhitespace = false');
XML.ignoreWhitespace = original;
}
[Test]
public function testSingleText():void{
var original:Boolean = XML.ignoreWhitespace;
XML.ignoreWhitespace = true;
var xml:XML = new XML(' my text ');
assertEquals( 'text', xml.nodeKind(), 'unexpected text result with XML.ignoreWhitespace = true');
assertEquals( 'my text', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true');
assertNull( xml.name(), 'unexpected name value with text');
XML.ignoreWhitespace = false;
var caughtError:Boolean = false;
try {
xml = new XML(' my text ');
} catch(e:Error) {
caughtError = true;
}
assertFalse( caughtError, 'unexpected error status for text string parsing with XML.ignoreWhitespace = false');
assertEquals( 'text', xml.nodeKind(), 'unexpected text result with XML.ignoreWhitespace = true');
assertEquals( ' my text ', xml.valueOf(), 'unexpected toXMLString with XML.ignoreWhitespace = true');
XML.ignoreWhitespace = original;
}
[Test]
public function testSingleComment():void{
var original:Boolean = XML.ignoreWhitespace;
var originalComments:Boolean = XML.ignoreComments;
XML.ignoreWhitespace = true;
XML.ignoreComments = false;
var xml:XML = new XML(' ');
assertEquals( 'comment', xml.nodeKind(), 'unexpected comment result with XML.ignoreWhitespace = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true');
assertNull( xml.name(), 'unexpected name value with text');
XML.ignoreWhitespace = false;
var caughtError:Boolean = false;
try {
xml = new XML(' ');
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status for comment parsing with XML.ignoreWhitespace = false');
xml = new XML('');
assertNull( xml.name(), 'unexpected name value with comment');
assertEquals( 'comment', xml.nodeKind(), 'unexpected comment result with XML.ignoreWhitespace = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true');
XML.ignoreComments = true;
xml = new XML('');
assertNull( xml.name(), 'unexpected name value with text');
assertEquals( 'text', xml.nodeKind(), 'unexpected comment result with XML.ignoreComments = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = true');
XML.ignoreWhitespace = original;
XML.ignoreComments = originalComments;
}
[Test]
public function testIgnoreComments():void{
var original:Boolean = XML.ignoreWhitespace;
var originalComments:Boolean = XML.ignoreComments;
XML.ignoreWhitespace = true;
XML.ignoreComments = false;
var xml:XML = new XML('');
assertEquals( 1, xml.children().length(), 'unexpected comment result with XML.ignoreComments = false');
assertEquals(
'\\n' +
' \\n' +
'',
xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = false');
assertNull( xml.children()[0].name(), 'unexpected name value with comment');
XML.ignoreComments = true;
xml = new XML('');
assertEquals( 0, xml.children().length(), 'unexpected comment result with XML.ignoreComments = true');
assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = true');
XML.ignoreWhitespace = original;
XML.ignoreComments = originalComments;
}
[Test]
[TestVariance(variance=""JS"",description=""Some browsers (IE11/Edge legacy) can parse to a different order of attributes and namespace declarations (which affects stringified content comparisons)"")]
public function testLargeComplex():void{
var xmlString:String = xml.toXMLString();
//IE and MS Edge: inlcude alternate output check
//account for variation in output order of attributes and namespace declarations (from native DOMParser)
assertTrue( xmlString.length == 2060, 'unexpected complex stringify results');
}
[Test]
public function testTopLevelProcessingInstructions():void{
var xmlSource:String = '\\n' +
'\\n' +
'';
XML.ignoreProcessingInstructions = true;
var xml:XML = new XML(xmlSource);
assertTrue( xml.toString() == '', 'unexpected toSting result');
assertTrue( xml.nodeKind() == 'text', 'unexpected nodeKind result');
XML.ignoreProcessingInstructions = false;
var caughtError:Boolean;
try {
xml = new XML(xmlSource);
} catch (e:Error)
{
//RoyaleUnitTestRunner.consoleOut(e.message);
caughtError = true;
}
//RoyaleUnitTestRunner.consoleOut('testTopLevelProcessingInstructions '+xml.nodeKind());
assertTrue( caughtError, 'error was expected');
}
[Test]
public function testTopLevelWhitespace():void{
var original:Boolean = XML.ignoreWhitespace;
var xmlSource:String = '\\n'
+' test ';
XML.ignoreWhitespace = true;
var xml:XML = new XML(xmlSource);
assertTrue( xml.toString() == 'test', 'unexpected toSting result');
assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result');
XML.ignoreWhitespace = false;
xml = new XML(xmlSource);
assertTrue( xml.toString() == 'test', 'unexpected toSting result');
assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result');
XML.ignoreWhitespace = original;
}
[Test]
public function testTopLevelMultipleTypes():void{
var original:Object = XML.settings();
var xmlSource:String = '\\n'
+' test ';
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
XML.ignoreWhitespace = false;
var xml:XML = new XML(xmlSource);
assertTrue( xml.toString() == 'test', 'unexpected toSting result');
assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result');
xmlSource = '\\n'
+' ';
var caughtError:Boolean = false;
try {
xml =new XML(xmlSource);
} catch (e:Error)
{
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
assertTrue( xml.toString() == 'test', 'unexpected toSting result');
assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result');
XML.setSettings(original)
}
[Test]
public function testTopLevelVariants():void{
var original:Object = XML.settings();
//error 2 root tags
var xmlSource:String = ' testtest ';
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
XML.ignoreWhitespace = false;
var xml:XML;
var caughtError:Boolean = false;
try {
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error statust');
//repeat with all settings toggled (must remain an error)
XML.ignoreComments = true;
XML.ignoreProcessingInstructions = true;
XML.ignoreWhitespace = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error statust');
//restore settings
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
XML.ignoreWhitespace = false;
//error multiple non-element nodes with whitespace
xmlSource = ' ';
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
//repeat with whiteSpace toggled (must remain an error)
XML.ignoreWhitespace = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
XML.ignoreWhitespace = false;
//repeat with ignoreProcessingInstructions toggled
XML.ignoreProcessingInstructions = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
XML.ignoreProcessingInstructions = false;
//repeat with ignoreComments toggled
XML.ignoreComments = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
XML.ignoreComments = false;
//repeat with all settings toggled
XML.ignoreComments = true;
XML.ignoreProcessingInstructions = true;
XML.ignoreWhitespace = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertFalse( caughtError, 'unexpected error status');
assertTrue( xml.toString() == '', 'unexpected toSting result');
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
XML.ignoreWhitespace = false;
//another one with top level cdata just to cover more:
xmlSource = ' - ]]> ';
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertTrue( caughtError, 'unexpected error status');
//repeat with all settings toggled
XML.ignoreComments = true;
XML.ignoreProcessingInstructions = true;
XML.ignoreWhitespace = true;
try {
caughtError = false;
xml = new XML(xmlSource);
} catch(e:Error) {
caughtError = true;
}
assertFalse( caughtError, 'unexpected error status');
assertTrue( xml.toString() == ' -- ', 'unexpected toSting result');
assertTrue( xml.toXMLString() == '- ]]>', 'unexpected toXMLString result');
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
XML.ignoreWhitespace = false;
XML.setSettings(original)
}
[Test]
public function testTopLevelCoercionFunction():void{
var localXml:XML;
localXml = XML(true);
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == 'true', 'XML content was unexpected');
localXml = XML(false);
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == 'false', 'XML content was unexpected');
localXml = XML('string');
assertTrue( localXml.nodeKind() == 'text', 'XMLList content was unexpected');
assertTrue( localXml.toString() == 'string', 'XMLList content was unexpected');
localXml = XML(99.9);
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == '99.9', 'XML content was unexpected');
//as3 docs say this is an error, but it is not (in AVM)
localXml = XML(null);
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == '', 'XML content was unexpected');
//as3 docs say this is an error, but it is not (in AVM)
localXml = XML(undefined);
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == '', 'XML content was unexpected');
//as3 docs say this is an error, but it is not (in AVM)
localXml = XML({});
assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected');
assertTrue( localXml.toString() == '[object Object]', 'XML content was unexpected');
var xmlContent:XML = xml;
localXml = XML(xmlContent);
assertTrue( localXml == xml, 'XML content was unexpected');
var sizes:XMLList = localXml..size.(@description == 'Small');
assertTrue( sizes.length() == 1, 'XML content was unexpected');
localXml = XML(sizes);
assertTrue( localXml == sizes[0], 'XML content was unexpected');
}
[Test]
public function testChildren():void{
XML.setSettings(XML.defaultSettings());
var xml:XML = Something surrounded With Whitespace ;
assertEquals(xml.children().length(),3 , 'unexpected default parsing children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' Something\\n' +
' surrounded With Whitespace\\n' +
'' , 'unexpected default parsing string output');
XML.ignoreComments = false;
xml = Something surrounded With Whitespace ;
assertEquals(xml.children().length(),4 , 'unexpected parsing with ignoreComments = false children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' Something\\n' +
' \\n' +
' surrounded With Whitespace\\n' +
'' , 'unexpected parsing with ignoreComments = false string output');
XML.ignoreProcessingInstructions= false;
xml = Something surrounded With Whitespace ;
assertEquals(xml.children().length(),5 , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' Something\\n' +
' \\n' +
' surrounded With Whitespace\\n' +
'' , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false string output');
XML.ignoreWhitespace= false;
xml = Something surrounded With Whitespace ;
assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false and ignoreWhitespace= false children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' Something\\n' +
' \\n' +
' surrounded With Whitespace\\n' +
'' , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false and ignoreWhitespace= false string output');
//try something different
XML.ignoreComments = true;
xml = Something surrounded With Whitespace ;
//because ignoreComments is true, the following is parsed as an empty test node:
xml.appendChild();
assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' Something\\n' +
' surrounded With Whitespace\\n' +
' \\n' +
'' , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... string output');
XML.ignoreComments = false;
var comment:XML = ;
comment = comment.comments()[0];
assertEquals(comment.toXMLString(),'', 'unexpected toXMLString for comment');
XML.ignoreComments = true;
xml = Something surrounded With Whitespace ;
//because ignoreComments is true, the following is parsed as an empty test node:
xml.appendChild(comment);
assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... children length');
assertEquals(xml.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' Something\\n' +
' surrounded With Whitespace\\n' +
' \\n' +
'' , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... string output');
XML.setSettings(XML.defaultSettings());
}
[Test]
public function testElements():void{
XML.setSettings(XML.defaultSettings());
var xml:XML = Something surrounded With Whitespace ;
var elements:XMLList = xml.elements();
assertEquals(
elements.toString(),
'\\n' +
'\\n' +
'', 'elements only should be 3 elements');
elements = xml.elements('el1')
assertEquals(
elements.toXMLString(),
'', 'elements query should return 1 element');
var el:XML = ;
xml.appendChild(el)
elements = xml.elements('el1')
assertEquals(
elements.toXMLString(),
'\\n', 'elements query should return 2 elements');
}
[Test]
public function testDelete():void{
XML.setSettings(XML.defaultSettings());
XML.prettyPrinting = false;
var xml:XML = ;
delete xml.@name;
assertEquals(xml.toString(),'',""name attribute should have been removed."");
delete xml.baz[0];
assertEquals(xml.toString(),'',""the first baz element should have been removed."");
xml = ;
delete xml.baz;
// delete xml.baz[0];
assertEquals(xml.toXMLString(),'',""the first baz element should have been removed."");
XML.setSettings(XML.defaultSettings());
}
[Test]
public function testDynamicAttributes():void{
var xml:XML = ;
assertEquals(xml.attributes().length(),2, 'unexpected attributes count');
const MYAtt:String = 'myAtt1';
const MYAttTestVal:String = 'myAttTestVal';
delete xml.@[MYAtt];
assertEquals(xml.attributes().length(),1, 'unexpected attributes count');
xml.@[MYAtt] = MYAttTestVal;
assertEquals(xml.attributes().length(),2, 'unexpected attributes count');
assertEquals(xml.@myAtt1,'myAttTestVal', 'unexpected attributes value');
}
[Test]
public function testAppendChildContentTransfer():void{
var source:XML = ;
var sourceChildren:XMLList = source.children();
var attList:XMLList = source.@att;
var att:XML = attList[0];
var orig1:XML = sourceChildren[0];
var dest:XML = ;
assertTrue(orig1.parent() === source, 'unexpected parent');
assertTrue(att.parent() === source, 'unexpected parent');
dest.appendChild(sourceChildren);
//element was re-parented:
assertFalse(orig1.parent() === source, 'unexpected parent');
//attribute was not moved:
assertTrue(att.parent() === source, 'unexpected parent');
assertTrue(orig1.parent() === dest, 'unexpected parent');
//at this point the actual nodes are present in both xml trees when iterating downwards,
//but the 'parent()' evaluation only resolves to the latest parent
//this is the swf behavior, but may not conform to standard
assertEquals(source.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected source toXMLString')
assertEquals(dest.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected dest toXMLString')
dest.appendChild(attList);
//swf has a strange variation here:
var appendedAtt1:String = isJS ? ' attribute\\n' : ' attribute\\n'
assertEquals(dest.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
appendedAtt1 +
'', 'unexpected dest toXMLString');
dest.appendChild(att);
assertEquals(dest.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
appendedAtt1 +
' attribute\\n' +
'', 'unexpected dest toXMLString');
dest.appendChild(orig1);
//the source remains unchanged
assertEquals(source.toXMLString(),
'\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected source toXMLString');
//this is effectively a re-ordering inside dest
var expected1:String = '\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
appendedAtt1 +
' attribute\\n' +
' \\n' +
''
var expected2:String = '\\n' +
' \\n' + //this seems to be the case in standalone debug player
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
appendedAtt1 +
' attribute\\n' +
' \\n' +
''
var actual:String = dest.toXMLString();
assertTrue(actual==expected1 || actual==expected2
, 'unexpected dest toXMLString');
}
[Test]
public function testAssignXMLListVariants():void{
var xmlList:XMLList = new XMLList();
var xml:XML = ;
xml.foobaz = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
'', 'unexpected empty XMLList assignment');
xmlList = new XMLList('');
xml.foobaz = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected XMLList assignment');
xml = ;
xml.foobaz = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected XMLList assignment');
xml = ;
xml.foobaz = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected XMLList assignment');
xml =;
xml.foobaz = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected XMLList assignment');
xmlList = new XMLList();
xml.foobazzer = xmlList;
assertEquals(xml.toXMLString(), '\\n' +
' \\n' +
' \\n' +
' \\n' +
'', 'unexpected XMLList assignment')
}
//@todo - Passes in Swf, fails in browser:
/*[Test]
public function checkNumericAttributeSupported():void{
var xml:XML = XML('');
assertEquals(xml.toXMLString(), '', 'roundtripping with numeric attributes did not work');
}*/
}
}
",12447,False,2394.0679500143065,median
"[role=""xpack""]
[testenv=""basic""]
[[ml-find-file-structure]]
=== Find file structure API
++++
Find file structure
++++
experimental[]
Finds the structure of a text file. The text file must contain data that is
suitable to be ingested into {es}.
[[ml-find-file-structure-request]]
==== {api-request-title}
`POST _ml/find_file_structure`
[[ml-find-file-structure-prereqs]]
==== {api-prereq-title}
* If the {es} {security-features} are enabled, you must have `monitor_ml` or
`monitor` cluster privileges to use this API. See
{stack-ov}/security-privileges.html[Security privileges].
[[ml-find-file-structure-desc]]
==== {api-description-title}
This API provides a starting point for ingesting data into {es} in a format that
is suitable for subsequent use with other {ml} functionality.
Unlike other {es} endpoints, the data that is posted to this endpoint does not
need to be UTF-8 encoded and in JSON format. It must, however, be text; binary
file formats are not currently supported.
The response from the API contains:
* A couple of messages from the beginning of the file.
* Statistics that reveal the most common values for all fields detected within
the file and basic numeric statistics for numeric fields.
* Information about the structure of the file, which is useful when you write
ingest configurations to index the file contents.
* Appropriate mappings for an {es} index, which you could use to ingest the file
contents.
All this information can be calculated by the structure finder with no guidance.
However, you can optionally override some of the decisions about the file
structure by specifying one or more query parameters.
Details of the output can be seen in the
<>.
If the structure finder produces unexpected results for a particular file,
specify the `explain` query parameter. It causes an `explanation` to appear in
the response, which should help in determining why the returned structure was
chosen.
[[ml-find-file-structure-query-parms]]
==== {api-query-parms-title}
`charset` (Optional)::
(string) The file's character set. It must be a character set that is supported
by the JVM that {es} uses. For example, `UTF-8`, `UTF-16LE`, `windows-1252`, or
`EUC-JP`. If this parameter is not specified, the structure finder chooses an
appropriate character set.
`column_names` (Optional)::
(string) If you have set `format` to `delimited`, you can specify the column names
in a comma-separated list. If this parameter is not specified, the structure
finder uses the column names from the header row of the file. If the file does
not have a header role, columns are named ""column1"", ""column2"", ""column3"", etc.
`delimiter` (Optional)::
(string) If you have set `format` to `delimited`, you can specify the character used
to delimit the values in each row. Only a single character is supported; the
delimiter cannot have multiple characters. If this parameter is not specified,
the structure finder considers the following possibilities: comma, tab,
semi-colon, and pipe (`|`).
`explain` (Optional)::
(boolean) If this parameter is set to `true`, the response includes a field
named `explanation`, which is an array of strings that indicate how the
structure finder produced its result. The default value is `false`.
`format` (Optional)::
(string) The high level structure of the file. Valid values are `ndjson`, `xml`,
`delimited`, and `semi_structured_text`. If this parameter is not specified,
the structure finder chooses one.
`grok_pattern` (Optional)::
(string) If you have set `format` to `semi_structured_text`, you can specify a Grok
pattern that is used to extract fields from every message in the file. The
name of the timestamp field in the Grok pattern must match what is specified
in the `timestamp_field` parameter. If that parameter is not specified, the
name of the timestamp field in the Grok pattern must match ""timestamp"". If
`grok_pattern` is not specified, the structure finder creates a Grok pattern.
`has_header_row` (Optional)::
(boolean) If you have set `format` to `delimited`, you can use this parameter to
indicate whether the column names are in the first row of the file. If this
parameter is not specified, the structure finder guesses based on the similarity of
the first row of the file to other rows.
`line_merge_size_limit` (Optional)::
(unsigned integer) The maximum number of characters in a message when lines are
merged to form messages while analyzing semi-structured files. The default
is 10000. If you have extremely long messages you may need to increase this, but
be aware that this may lead to very long processing times if the way to group
lines into messages is misdetected.
`lines_to_sample` (Optional)::
(unsigned integer) The number of lines to include in the structural analysis,
starting from the beginning of the file. The minimum is 2; the default
is 1000. If the value of this parameter is greater than the number of lines in
the file, the analysis proceeds (as long as there are at least two lines in the
file) for all of the lines. +
+
--
NOTE: The number of lines and the variation of the lines affects the speed of
the analysis. For example, if you upload a log file where the first 1000 lines
are all variations on the same message, the analysis will find more commonality
than would be seen with a bigger sample. If possible, however, it is more
efficient to upload a sample file with more variety in the first 1000 lines than
to request analysis of 100000 lines to achieve some variety.
--
`quote` (Optional)::
(string) If you have set `format` to `delimited`, you can specify the character used
to quote the values in each row if they contain newlines or the delimiter
character. Only a single character is supported. If this parameter is not
specified, the default value is a double quote (`""`). If your delimited file
format does not use quoting, a workaround is to set this argument to a
character that does not appear anywhere in the sample.
`should_trim_fields` (Optional)::
(boolean) If you have set `format` to `delimited`, you can specify whether values
between delimiters should have whitespace trimmed from them. If this parameter
is not specified and the delimiter is pipe (`|`), the default value is `true`.
Otherwise, the default value is `false`.
`timeout` (Optional)::
(time) Sets the maximum amount of time that the structure analysis make take.
If the analysis is still running when the timeout expires then it will be
aborted. The default value is 25 seconds.
`timestamp_field` (Optional)::
(string) The name of the field that contains the primary timestamp of each
record in the file. In particular, if the file were ingested into an index,
this is the field that would be used to populate the `@timestamp` field. +
+
--
If the `format` is `semi_structured_text`, this field must match the name of the
appropriate extraction in the `grok_pattern`. Therefore, for semi-structured
file formats, it is best not to specify this parameter unless `grok_pattern` is
also specified.
For structured file formats, if you specify this parameter, the field must exist
within the file.
If this parameter is not specified, the structure finder makes a decision about which
field (if any) is the primary timestamp field. For structured file formats, it
is not compulsory to have a timestamp in the file.
--
`timestamp_format` (Optional)::
(string) The Java time format of the timestamp field in the file. +
+
--
NOTE: Only a subset of Java time format letter groups are supported:
* `a`
* `d`
* `dd`
* `EEE`
* `EEEE`
* `H`
* `HH`
* `h`
* `M`
* `MM`
* `MMM`
* `MMMM`
* `mm`
* `ss`
* `XX`
* `XXX`
* `yy`
* `yyyy`
* `zzz`
Additionally `S` letter groups (fractional seconds) of length one to nine are
supported providing they occur after `ss` and separated from the `ss` by a `.`,
`,` or `:`. Spacing and punctuation is also permitted with the exception of `?`,
newline and carriage return, together with literal text enclosed in single
quotes. For example, `MM/dd HH.mm.ss,SSSSSS 'in' yyyy` is a valid override
format.
One valuable use case for this parameter is when the format is semi-structured
text, there are multiple timestamp formats in the file, and you know which
format corresponds to the primary timestamp, but you do not want to specify the
full `grok_pattern`. Another is when the timestamp format is one that the
structure finder does not consider by default.
If this parameter is not specified, the structure finder chooses the best
format from a built-in set.
--
[[ml-find-file-structure-request-body]]
==== {api-request-body-title}
The text file that you want to analyze. It must contain data that is suitable to
be ingested into {es}. It does not need to be in JSON format and it does not
need to be UTF-8 encoded. The size is limited to the {es} HTTP receive buffer
size, which defaults to 100 Mb.
[[ml-find-file-structure-examples]]
==== {api-examples-title}
Suppose you have a newline-delimited JSON file that contains information about
some books. You can send the contents to the `find_file_structure` endpoint:
[source,js]
----
POST _ml/find_file_structure
{""name"": ""Leviathan Wakes"", ""author"": ""James S.A. Corey"", ""release_date"": ""2011-06-02"", ""page_count"": 561}
{""name"": ""Hyperion"", ""author"": ""Dan Simmons"", ""release_date"": ""1989-05-26"", ""page_count"": 482}
{""name"": ""Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1965-06-01"", ""page_count"": 604}
{""name"": ""Dune Messiah"", ""author"": ""Frank Herbert"", ""release_date"": ""1969-10-15"", ""page_count"": 331}
{""name"": ""Children of Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1976-04-21"", ""page_count"": 408}
{""name"": ""God Emperor of Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1981-05-28"", ""page_count"": 454}
{""name"": ""Consider Phlebas"", ""author"": ""Iain M. Banks"", ""release_date"": ""1987-04-23"", ""page_count"": 471}
{""name"": ""Pandora's Star"", ""author"": ""Peter F. Hamilton"", ""release_date"": ""2004-03-02"", ""page_count"": 768}
{""name"": ""Revelation Space"", ""author"": ""Alastair Reynolds"", ""release_date"": ""2000-03-15"", ""page_count"": 585}
{""name"": ""A Fire Upon the Deep"", ""author"": ""Vernor Vinge"", ""release_date"": ""1992-06-01"", ""page_count"": 613}
{""name"": ""Ender's Game"", ""author"": ""Orson Scott Card"", ""release_date"": ""1985-06-01"", ""page_count"": 324}
{""name"": ""1984"", ""author"": ""George Orwell"", ""release_date"": ""1985-06-01"", ""page_count"": 328}
{""name"": ""Fahrenheit 451"", ""author"": ""Ray Bradbury"", ""release_date"": ""1953-10-15"", ""page_count"": 227}
{""name"": ""Brave New World"", ""author"": ""Aldous Huxley"", ""release_date"": ""1932-06-01"", ""page_count"": 268}
{""name"": ""Foundation"", ""author"": ""Isaac Asimov"", ""release_date"": ""1951-06-01"", ""page_count"": 224}
{""name"": ""The Giver"", ""author"": ""Lois Lowry"", ""release_date"": ""1993-04-26"", ""page_count"": 208}
{""name"": ""Slaughterhouse-Five"", ""author"": ""Kurt Vonnegut"", ""release_date"": ""1969-06-01"", ""page_count"": 275}
{""name"": ""The Hitchhiker's Guide to the Galaxy"", ""author"": ""Douglas Adams"", ""release_date"": ""1979-10-12"", ""page_count"": 180}
{""name"": ""Snow Crash"", ""author"": ""Neal Stephenson"", ""release_date"": ""1992-06-01"", ""page_count"": 470}
{""name"": ""Neuromancer"", ""author"": ""William Gibson"", ""release_date"": ""1984-07-01"", ""page_count"": 271}
{""name"": ""The Handmaid's Tale"", ""author"": ""Margaret Atwood"", ""release_date"": ""1985-06-01"", ""page_count"": 311}
{""name"": ""Starship Troopers"", ""author"": ""Robert A. Heinlein"", ""release_date"": ""1959-12-01"", ""page_count"": 335}
{""name"": ""The Left Hand of Darkness"", ""author"": ""Ursula K. Le Guin"", ""release_date"": ""1969-06-01"", ""page_count"": 304}
{""name"": ""The Moon is a Harsh Mistress"", ""author"": ""Robert A. Heinlein"", ""release_date"": ""1966-04-01"", ""page_count"": 288}
----
// CONSOLE
// TEST
If the request does not encounter errors, you receive the following result:
[source,js]
----
{
""num_lines_analyzed"" : 24, <1>
""num_messages_analyzed"" : 24, <2>
""sample_start"" : ""{\\""name\\"": \\""Leviathan Wakes\\"", \\""author\\"": \\""James S.A. Corey\\"", \\""release_date\\"": \\""2011-06-02\\"", \\""page_count\\"": 561}\\n{\\""name\\"": \\""Hyperion\\"", \\""author\\"": \\""Dan Simmons\\"", \\""release_date\\"": \\""1989-05-26\\"", \\""page_count\\"": 482}\\n"", <3>
""charset"" : ""UTF-8"", <4>
""has_byte_order_marker"" : false, <5>
""format"" : ""ndjson"", <6>
""timestamp_field"" : ""release_date"", <7>
""joda_timestamp_formats"" : [ <8>
""ISO8601""
],
""java_timestamp_formats"" : [ <9>
""ISO8601""
],
""need_client_timezone"" : true, <10>
""mappings"" : { <11>
""@timestamp"" : {
""type"" : ""date""
},
""author"" : {
""type"" : ""keyword""
},
""name"" : {
""type"" : ""keyword""
},
""page_count"" : {
""type"" : ""long""
},
""release_date"" : {
""type"" : ""date"",
""format"" : ""iso8601""
}
},
""ingest_pipeline"" : {
""description"" : ""Ingest pipeline created by file structure finder"",
""processors"" : [
{
""date"" : {
""field"" : ""release_date"",
""timezone"" : ""{{ beat.timezone }}"",
""formats"" : [
""ISO8601""
]
}
}
]
},
""field_stats"" : { <12>
""author"" : {
""count"" : 24,
""cardinality"" : 20,
""top_hits"" : [
{
""value"" : ""Frank Herbert"",
""count"" : 4
},
{
""value"" : ""Robert A. Heinlein"",
""count"" : 2
},
{
""value"" : ""Alastair Reynolds"",
""count"" : 1
},
{
""value"" : ""Aldous Huxley"",
""count"" : 1
},
{
""value"" : ""Dan Simmons"",
""count"" : 1
},
{
""value"" : ""Douglas Adams"",
""count"" : 1
},
{
""value"" : ""George Orwell"",
""count"" : 1
},
{
""value"" : ""Iain M. Banks"",
""count"" : 1
},
{
""value"" : ""Isaac Asimov"",
""count"" : 1
},
{
""value"" : ""James S.A. Corey"",
""count"" : 1
}
]
},
""name"" : {
""count"" : 24,
""cardinality"" : 24,
""top_hits"" : [
{
""value"" : ""1984"",
""count"" : 1
},
{
""value"" : ""A Fire Upon the Deep"",
""count"" : 1
},
{
""value"" : ""Brave New World"",
""count"" : 1
},
{
""value"" : ""Children of Dune"",
""count"" : 1
},
{
""value"" : ""Consider Phlebas"",
""count"" : 1
},
{
""value"" : ""Dune"",
""count"" : 1
},
{
""value"" : ""Dune Messiah"",
""count"" : 1
},
{
""value"" : ""Ender's Game"",
""count"" : 1
},
{
""value"" : ""Fahrenheit 451"",
""count"" : 1
},
{
""value"" : ""Foundation"",
""count"" : 1
}
]
},
""page_count"" : {
""count"" : 24,
""cardinality"" : 24,
""min_value"" : 180,
""max_value"" : 768,
""mean_value"" : 387.0833333333333,
""median_value"" : 329.5,
""top_hits"" : [
{
""value"" : 180,
""count"" : 1
},
{
""value"" : 208,
""count"" : 1
},
{
""value"" : 224,
""count"" : 1
},
{
""value"" : 227,
""count"" : 1
},
{
""value"" : 268,
""count"" : 1
},
{
""value"" : 271,
""count"" : 1
},
{
""value"" : 275,
""count"" : 1
},
{
""value"" : 288,
""count"" : 1
},
{
""value"" : 304,
""count"" : 1
},
{
""value"" : 311,
""count"" : 1
}
]
},
""release_date"" : {
""count"" : 24,
""cardinality"" : 20,
""earliest"" : ""1932-06-01"",
""latest"" : ""2011-06-02"",
""top_hits"" : [
{
""value"" : ""1985-06-01"",
""count"" : 3
},
{
""value"" : ""1969-06-01"",
""count"" : 2
},
{
""value"" : ""1992-06-01"",
""count"" : 2
},
{
""value"" : ""1932-06-01"",
""count"" : 1
},
{
""value"" : ""1951-06-01"",
""count"" : 1
},
{
""value"" : ""1953-10-15"",
""count"" : 1
},
{
""value"" : ""1959-12-01"",
""count"" : 1
},
{
""value"" : ""1965-06-01"",
""count"" : 1
},
{
""value"" : ""1966-04-01"",
""count"" : 1
},
{
""value"" : ""1969-10-15"",
""count"" : 1
}
]
}
}
}
----
// TESTRESPONSE[s/""sample_start"" : "".*"",/""sample_start"" : ""$body.sample_start"",/]
// The substitution is because the ""file"" is pre-processed by the test harness,
// so the fields may get reordered in the JSON the endpoint sees
<1> `num_lines_analyzed` indicates how many lines of the file were analyzed.
<2> `num_messages_analyzed` indicates how many distinct messages the lines contained.
For NDJSON, this value is the same as `num_lines_analyzed`. For other file
formats, messages can span several lines.
<3> `sample_start` reproduces the first two messages in the file verbatim. This
may help to diagnose parse errors or accidental uploads of the wrong file.
<4> `charset` indicates the character encoding used to parse the file.
<5> For UTF character encodings, `has_byte_order_marker` indicates whether the
file begins with a byte order marker.
<6> `format` is one of `ndjson`, `xml`, `delimited` or `semi_structured_text`.
<7> The `timestamp_field` names the field considered most likely to be the
primary timestamp of each document.
<8> `joda_timestamp_formats` are used to tell Logstash how to parse timestamps.
<9> `java_timestamp_formats` are the Java time formats recognized in the time
fields. Elasticsearch mappings and Ingest pipeline use this format.
<10> If a timestamp format is detected that does not include a timezone,
`need_client_timezone` will be `true`. The server that parses the file must
therefore be told the correct timezone by the client.
<11> `mappings` contains some suitable mappings for an index into which the data
could be ingested. In this case, the `release_date` field has been given a
`keyword` type as it is not considered specific enough to convert to the
`date` type.
<12> `field_stats` contains the most common values of each field, plus basic
numeric statistics for the numeric `page_count` field. This information
may provide clues that the data needs to be cleaned or transformed prior
to use by other {ml} functionality.
The next example shows how it's possible to find the structure of some New York
City yellow cab trip data. The first `curl` command downloads the data, the
first 20000 lines of which are then piped into the `find_file_structure`
endpoint. The `lines_to_sample` query parameter of the endpoint is set to 20000
to match what is specified in the `head` command.
[source,js]
----
curl -s ""s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2018-06.csv"" | head -20000 | curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&lines_to_sample=20000"" -T -
----
// NOTCONSOLE
// Not converting to console because this shows how curl can be used
--
NOTE: The `Content-Type: application/json` header must be set even though in
this case the data is not JSON. (Alternatively the `Content-Type` can be set
to any other supported by Elasticsearch, but it must be set.)
--
If the request does not encounter errors, you receive the following result:
[source,js]
----
{
""num_lines_analyzed"" : 20000,
""num_messages_analyzed"" : 19998, <1>
""sample_start"" : ""VendorID,tpep_pickup_datetime,tpep_dropoff_datetime,passenger_count,trip_distance,RatecodeID,store_and_fwd_flag,PULocationID,DOLocationID,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount\\n\\n1,2018-06-01 00:15:40,2018-06-01 00:16:46,1,.00,1,N,145,145,2,3,0.5,0.5,0,0,0.3,4.3\\n"",
""charset"" : ""UTF-8"",
""has_byte_order_marker"" : false,
""format"" : ""delimited"", <2>
""multiline_start_pattern"" : ""^.*?,\\""?\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"",
""exclude_lines_pattern"" : ""^\\""?VendorID\\""?,\\""?tpep_pickup_datetime\\""?,\\""?tpep_dropoff_datetime\\""?,\\""?passenger_count\\""?,\\""?trip_distance\\""?,\\""?RatecodeID\\""?,\\""?store_and_fwd_flag\\""?,\\""?PULocationID\\""?,\\""?DOLocationID\\""?,\\""?payment_type\\""?,\\""?fare_amount\\""?,\\""?extra\\""?,\\""?mta_tax\\""?,\\""?tip_amount\\""?,\\""?tolls_amount\\""?,\\""?improvement_surcharge\\""?,\\""?total_amount\\""?"",
""column_names"" : [ <3>
""VendorID"",
""tpep_pickup_datetime"",
""tpep_dropoff_datetime"",
""passenger_count"",
""trip_distance"",
""RatecodeID"",
""store_and_fwd_flag"",
""PULocationID"",
""DOLocationID"",
""payment_type"",
""fare_amount"",
""extra"",
""mta_tax"",
""tip_amount"",
""tolls_amount"",
""improvement_surcharge"",
""total_amount""
],
""has_header_row"" : true, <4>
""delimiter"" : "","", <5>
""quote"" : ""\\"""", <6>
""timestamp_field"" : ""tpep_pickup_datetime"", <7>
""joda_timestamp_formats"" : [ <8>
""YYYY-MM-dd HH:mm:ss""
],
""java_timestamp_formats"" : [ <9>
""yyyy-MM-dd HH:mm:ss""
],
""need_client_timezone"" : true, <10>
""mappings"" : {
""@timestamp"" : {
""type"" : ""date""
},
""DOLocationID"" : {
""type"" : ""long""
},
""PULocationID"" : {
""type"" : ""long""
},
""RatecodeID"" : {
""type"" : ""long""
},
""VendorID"" : {
""type"" : ""long""
},
""extra"" : {
""type"" : ""double""
},
""fare_amount"" : {
""type"" : ""double""
},
""improvement_surcharge"" : {
""type"" : ""double""
},
""mta_tax"" : {
""type"" : ""double""
},
""passenger_count"" : {
""type"" : ""long""
},
""payment_type"" : {
""type"" : ""long""
},
""store_and_fwd_flag"" : {
""type"" : ""keyword""
},
""tip_amount"" : {
""type"" : ""double""
},
""tolls_amount"" : {
""type"" : ""double""
},
""total_amount"" : {
""type"" : ""double""
},
""tpep_dropoff_datetime"" : {
""type"" : ""date"",
""format"" : ""yyyy-MM-dd HH:mm:ss""
},
""tpep_pickup_datetime"" : {
""type"" : ""date"",
""format"" : ""yyyy-MM-dd HH:mm:ss""
},
""trip_distance"" : {
""type"" : ""double""
}
},
""ingest_pipeline"" : {
""description"" : ""Ingest pipeline created by file structure finder"",
""processors"" : [
{
""date"" : {
""field"" : ""tpep_pickup_datetime"",
""timezone"" : ""{{ beat.timezone }}"",
""formats"" : [
""yyyy-MM-dd HH:mm:ss""
]
}
}
]
},
""field_stats"" : {
""DOLocationID"" : {
""count"" : 19998,
""cardinality"" : 240,
""min_value"" : 1,
""max_value"" : 265,
""mean_value"" : 150.26532653265312,
""median_value"" : 148,
""top_hits"" : [
{
""value"" : 79,
""count"" : 760
},
{
""value"" : 48,
""count"" : 683
},
{
""value"" : 68,
""count"" : 529
},
{
""value"" : 170,
""count"" : 506
},
{
""value"" : 107,
""count"" : 468
},
{
""value"" : 249,
""count"" : 457
},
{
""value"" : 230,
""count"" : 441
},
{
""value"" : 186,
""count"" : 432
},
{
""value"" : 141,
""count"" : 409
},
{
""value"" : 263,
""count"" : 386
}
]
},
""PULocationID"" : {
""count"" : 19998,
""cardinality"" : 154,
""min_value"" : 1,
""max_value"" : 265,
""mean_value"" : 153.4042404240424,
""median_value"" : 148,
""top_hits"" : [
{
""value"" : 79,
""count"" : 1067
},
{
""value"" : 230,
""count"" : 949
},
{
""value"" : 148,
""count"" : 940
},
{
""value"" : 132,
""count"" : 897
},
{
""value"" : 48,
""count"" : 853
},
{
""value"" : 161,
""count"" : 820
},
{
""value"" : 234,
""count"" : 750
},
{
""value"" : 249,
""count"" : 722
},
{
""value"" : 164,
""count"" : 663
},
{
""value"" : 114,
""count"" : 646
}
]
},
""RatecodeID"" : {
""count"" : 19998,
""cardinality"" : 5,
""min_value"" : 1,
""max_value"" : 5,
""mean_value"" : 1.0656565656565653,
""median_value"" : 1,
""top_hits"" : [
{
""value"" : 1,
""count"" : 19311
},
{
""value"" : 2,
""count"" : 468
},
{
""value"" : 5,
""count"" : 195
},
{
""value"" : 4,
""count"" : 17
},
{
""value"" : 3,
""count"" : 7
}
]
},
""VendorID"" : {
""count"" : 19998,
""cardinality"" : 2,
""min_value"" : 1,
""max_value"" : 2,
""mean_value"" : 1.59005900590059,
""median_value"" : 2,
""top_hits"" : [
{
""value"" : 2,
""count"" : 11800
},
{
""value"" : 1,
""count"" : 8198
}
]
},
""extra"" : {
""count"" : 19998,
""cardinality"" : 3,
""min_value"" : -0.5,
""max_value"" : 0.5,
""mean_value"" : 0.4815981598159816,
""median_value"" : 0.5,
""top_hits"" : [
{
""value"" : 0.5,
""count"" : 19281
},
{
""value"" : 0,
""count"" : 698
},
{
""value"" : -0.5,
""count"" : 19
}
]
},
""fare_amount"" : {
""count"" : 19998,
""cardinality"" : 208,
""min_value"" : -100,
""max_value"" : 300,
""mean_value"" : 13.937719771977209,
""median_value"" : 9.5,
""top_hits"" : [
{
""value"" : 6,
""count"" : 1004
},
{
""value"" : 6.5,
""count"" : 935
},
{
""value"" : 5.5,
""count"" : 909
},
{
""value"" : 7,
""count"" : 903
},
{
""value"" : 5,
""count"" : 889
},
{
""value"" : 7.5,
""count"" : 854
},
{
""value"" : 4.5,
""count"" : 802
},
{
""value"" : 8.5,
""count"" : 790
},
{
""value"" : 8,
""count"" : 789
},
{
""value"" : 9,
""count"" : 711
}
]
},
""improvement_surcharge"" : {
""count"" : 19998,
""cardinality"" : 3,
""min_value"" : -0.3,
""max_value"" : 0.3,
""mean_value"" : 0.29915991599159913,
""median_value"" : 0.3,
""top_hits"" : [
{
""value"" : 0.3,
""count"" : 19964
},
{
""value"" : -0.3,
""count"" : 22
},
{
""value"" : 0,
""count"" : 12
}
]
},
""mta_tax"" : {
""count"" : 19998,
""cardinality"" : 3,
""min_value"" : -0.5,
""max_value"" : 0.5,
""mean_value"" : 0.4962246224622462,
""median_value"" : 0.5,
""top_hits"" : [
{
""value"" : 0.5,
""count"" : 19868
},
{
""value"" : 0,
""count"" : 109
},
{
""value"" : -0.5,
""count"" : 21
}
]
},
""passenger_count"" : {
""count"" : 19998,
""cardinality"" : 7,
""min_value"" : 0,
""max_value"" : 6,
""mean_value"" : 1.6201620162016201,
""median_value"" : 1,
""top_hits"" : [
{
""value"" : 1,
""count"" : 14219
},
{
""value"" : 2,
""count"" : 2886
},
{
""value"" : 5,
""count"" : 1047
},
{
""value"" : 3,
""count"" : 804
},
{
""value"" : 6,
""count"" : 523
},
{
""value"" : 4,
""count"" : 406
},
{
""value"" : 0,
""count"" : 113
}
]
},
""payment_type"" : {
""count"" : 19998,
""cardinality"" : 4,
""min_value"" : 1,
""max_value"" : 4,
""mean_value"" : 1.315631563156316,
""median_value"" : 1,
""top_hits"" : [
{
""value"" : 1,
""count"" : 13936
},
{
""value"" : 2,
""count"" : 5857
},
{
""value"" : 3,
""count"" : 160
},
{
""value"" : 4,
""count"" : 45
}
]
},
""store_and_fwd_flag"" : {
""count"" : 19998,
""cardinality"" : 2,
""top_hits"" : [
{
""value"" : ""N"",
""count"" : 19910
},
{
""value"" : ""Y"",
""count"" : 88
}
]
},
""tip_amount"" : {
""count"" : 19998,
""cardinality"" : 717,
""min_value"" : 0,
""max_value"" : 128,
""mean_value"" : 2.010959095909593,
""median_value"" : 1.45,
""top_hits"" : [
{
""value"" : 0,
""count"" : 6917
},
{
""value"" : 1,
""count"" : 1178
},
{
""value"" : 2,
""count"" : 624
},
{
""value"" : 3,
""count"" : 248
},
{
""value"" : 1.56,
""count"" : 206
},
{
""value"" : 1.46,
""count"" : 205
},
{
""value"" : 1.76,
""count"" : 196
},
{
""value"" : 1.45,
""count"" : 195
},
{
""value"" : 1.36,
""count"" : 191
},
{
""value"" : 1.5,
""count"" : 187
}
]
},
""tolls_amount"" : {
""count"" : 19998,
""cardinality"" : 26,
""min_value"" : 0,
""max_value"" : 35,
""mean_value"" : 0.2729697969796978,
""median_value"" : 0,
""top_hits"" : [
{
""value"" : 0,
""count"" : 19107
},
{
""value"" : 5.76,
""count"" : 791
},
{
""value"" : 10.5,
""count"" : 36
},
{
""value"" : 2.64,
""count"" : 21
},
{
""value"" : 11.52,
""count"" : 8
},
{
""value"" : 5.54,
""count"" : 4
},
{
""value"" : 8.5,
""count"" : 4
},
{
""value"" : 17.28,
""count"" : 4
},
{
""value"" : 2,
""count"" : 2
},
{
""value"" : 2.16,
""count"" : 2
}
]
},
""total_amount"" : {
""count"" : 19998,
""cardinality"" : 1267,
""min_value"" : -100.3,
""max_value"" : 389.12,
""mean_value"" : 17.499898989898995,
""median_value"" : 12.35,
""top_hits"" : [
{
""value"" : 7.3,
""count"" : 478
},
{
""value"" : 8.3,
""count"" : 443
},
{
""value"" : 8.8,
""count"" : 420
},
{
""value"" : 6.8,
""count"" : 406
},
{
""value"" : 7.8,
""count"" : 405
},
{
""value"" : 6.3,
""count"" : 371
},
{
""value"" : 9.8,
""count"" : 368
},
{
""value"" : 5.8,
""count"" : 362
},
{
""value"" : 9.3,
""count"" : 332
},
{
""value"" : 10.3,
""count"" : 332
}
]
},
""tpep_dropoff_datetime"" : {
""count"" : 19998,
""cardinality"" : 9066,
""earliest"" : ""2018-05-31 06:18:15"",
""latest"" : ""2018-06-02 02:25:44"",
""top_hits"" : [
{
""value"" : ""2018-06-01 01:12:12"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:32:15"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:44:27"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:46:42"",
""count"" : 9
},
{
""value"" : ""2018-06-01 01:03:22"",
""count"" : 9
},
{
""value"" : ""2018-06-01 01:05:13"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:11:20"",
""count"" : 8
},
{
""value"" : ""2018-06-01 00:16:03"",
""count"" : 8
},
{
""value"" : ""2018-06-01 00:19:47"",
""count"" : 8
},
{
""value"" : ""2018-06-01 00:25:17"",
""count"" : 8
}
]
},
""tpep_pickup_datetime"" : {
""count"" : 19998,
""cardinality"" : 8760,
""earliest"" : ""2018-05-31 06:08:31"",
""latest"" : ""2018-06-02 01:21:21"",
""top_hits"" : [
{
""value"" : ""2018-06-01 00:01:23"",
""count"" : 12
},
{
""value"" : ""2018-06-01 00:04:31"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:05:38"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:09:50"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:12:01"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:14:17"",
""count"" : 10
},
{
""value"" : ""2018-06-01 00:00:34"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:00:40"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:02:53"",
""count"" : 9
},
{
""value"" : ""2018-06-01 00:05:40"",
""count"" : 9
}
]
},
""trip_distance"" : {
""count"" : 19998,
""cardinality"" : 1687,
""min_value"" : 0,
""max_value"" : 64.63,
""mean_value"" : 3.6521062106210715,
""median_value"" : 2.16,
""top_hits"" : [
{
""value"" : 0.9,
""count"" : 335
},
{
""value"" : 0.8,
""count"" : 320
},
{
""value"" : 1.1,
""count"" : 316
},
{
""value"" : 0.7,
""count"" : 304
},
{
""value"" : 1.2,
""count"" : 303
},
{
""value"" : 1,
""count"" : 296
},
{
""value"" : 1.3,
""count"" : 280
},
{
""value"" : 1.5,
""count"" : 268
},
{
""value"" : 1.6,
""count"" : 268
},
{
""value"" : 0.6,
""count"" : 256
}
]
}
}
}
----
// NOTCONSOLE
<1> `num_messages_analyzed` is 2 lower than `num_lines_analyzed` because only
data records count as messages. The first line contains the column names
and in this sample the second line is blank.
<2> Unlike the first example, in this case the `format` has been identified as
`delimited`.
<3> Because the `format` is `delimited`, the `column_names` field in the output
lists the column names in the order they appear in the sample.
<4> `has_header_row` indicates that for this sample the column names were in
the first row of the sample. (If they hadn't been then it would have been
a good idea to specify them in the `column_names` query parameter.)
<5> The `delimiter` for this sample is a comma, as it's a CSV file.
<6> The `quote` character is the default double quote. (The structure finder
does not attempt to deduce any other quote character, so if you have a
delimited file that's quoted with some other character you must specify it
using the `quote` query parameter.)
<7> The `timestamp_field` has been chosen to be `tpep_pickup_datetime`.
`tpep_dropoff_datetime` would work just as well, but `tpep_pickup_datetime`
was chosen because it comes first in the column order. If you prefer
`tpep_dropoff_datetime` then force it to be chosen using the
`timestamp_field` query parameter.
<8> `joda_timestamp_formats` are used to tell Logstash how to parse timestamps.
<9> `java_timestamp_formats` are the Java time formats recognized in the time
fields. Elasticsearch mappings and Ingest pipeline use this format.
<10> The timestamp format in this sample doesn't specify a timezone, so to
accurately convert them to UTC timestamps to store in Elasticsearch it's
necessary to supply the timezone they relate to. `need_client_timezone`
will be `false` for timestamp formats that include the timezone.
If you try to analyze a lot of data then the analysis will take a long time.
If you want to limit the amount of processing your {es} cluster performs for
a request, use the `timeout` query parameter. The analysis will be aborted and
an error returned when the timeout expires. For example, you can replace 20000
lines in the previous example with 200000 and set a 1 second timeout on the
analysis:
[source,js]
----
curl -s ""s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2018-06.csv"" | head -200000 | curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&lines_to_sample=200000&timeout=1s"" -T -
----
// NOTCONSOLE
// Not converting to console because this shows how curl can be used
Unless you are using an incredibly fast computer you'll receive a timeout error:
[source,js]
----
{
""error"" : {
""root_cause"" : [
{
""type"" : ""timeout_exception"",
""reason"" : ""Aborting structure analysis during [delimited record parsing] as it has taken longer than the timeout of [1s]""
}
],
""type"" : ""timeout_exception"",
""reason"" : ""Aborting structure analysis during [delimited record parsing] as it has taken longer than the timeout of [1s]""
},
""status"" : 500
}
----
// NOTCONSOLE
--
NOTE: If you try the example above yourself you will note that the overall
running time of the `curl` commands is considerably longer than 1 second. This
is because it takes a while to download 200000 lines of CSV from the internet,
and the timeout is measured from the time this endpoint starts to process the
data.
--
This is an example of analyzing {es}'s own log file:
[source,js]
----
curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty"" -T ""$ES_HOME/logs/elasticsearch.log""
----
// NOTCONSOLE
// Not converting to console because this shows how curl can be used
If the request does not encounter errors, the result will look something like
this:
[source,js]
----
{
""num_lines_analyzed"" : 53,
""num_messages_analyzed"" : 53,
""sample_start"" : ""[2018-09-27T14:39:28,518][INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net usable_space [165.4gb], net total_space [464.7gb], types [hfs]\\n[2018-09-27T14:39:28,521][INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [494.9mb], compressed ordinary object pointers [true]\\n"",
""charset"" : ""UTF-8"",
""has_byte_order_marker"" : false,
""format"" : ""semi_structured_text"", <1>
""multiline_start_pattern"" : ""^\\\\[\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"", <2>
""grok_pattern"" : ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel}.*"", <3>
""timestamp_field"" : ""timestamp"",
""joda_timestamp_formats"" : [
""ISO8601""
],
""java_timestamp_formats"" : [
""ISO8601""
],
""need_client_timezone"" : true,
""mappings"" : {
""@timestamp"" : {
""type"" : ""date""
},
""loglevel"" : {
""type"" : ""keyword""
},
""message"" : {
""type"" : ""text""
}
},
""ingest_pipeline"" : {
""description"" : ""Ingest pipeline created by file structure finder"",
""processors"" : [
{
""grok"" : {
""field"" : ""message"",
""patterns"" : [
""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel}.*""
]
}
},
{
""date"" : {
""field"" : ""timestamp"",
""timezone"" : ""{{ beat.timezone }}"",
""formats"" : [
""ISO8601""
]
}
},
{
""remove"" : {
""field"" : ""timestamp""
}
}
]
},
""field_stats"" : {
""loglevel"" : {
""count"" : 53,
""cardinality"" : 3,
""top_hits"" : [
{
""value"" : ""INFO"",
""count"" : 51
},
{
""value"" : ""DEBUG"",
""count"" : 1
},
{
""value"" : ""WARN"",
""count"" : 1
}
]
},
""timestamp"" : {
""count"" : 53,
""cardinality"" : 28,
""earliest"" : ""2018-09-27T14:39:28,518"",
""latest"" : ""2018-09-27T14:39:37,012"",
""top_hits"" : [
{
""value"" : ""2018-09-27T14:39:29,859"",
""count"" : 10
},
{
""value"" : ""2018-09-27T14:39:29,860"",
""count"" : 9
},
{
""value"" : ""2018-09-27T14:39:29,858"",
""count"" : 6
},
{
""value"" : ""2018-09-27T14:39:28,523"",
""count"" : 3
},
{
""value"" : ""2018-09-27T14:39:34,234"",
""count"" : 2
},
{
""value"" : ""2018-09-27T14:39:28,518"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:28,521"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:28,522"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:29,861"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:32,786"",
""count"" : 1
}
]
}
}
}
----
// NOTCONSOLE
<1> This time the `format` has been identified as `semi_structured_text`.
<2> The `multiline_start_pattern` is set on the basis that the timestamp appears
in the first line of each multi-line log message.
<3> A very simple `grok_pattern` has been created, which extracts the timestamp
and recognizable fields that appear in every analyzed message. In this case
the only field that was recognized beyond the timestamp was the log level.
If you recognize more fields than the simple `grok_pattern` produced by the
structure finder unaided then you can resubmit the request specifying a more
advanced `grok_pattern` as a query parameter and the structure finder will
calculate `field_stats` for your additional fields.
In the case of the {es} log a more complete Grok pattern is
`\\[%{TIMESTAMP_ISO8601:timestamp}\\]\\[%{LOGLEVEL:loglevel} *\\]\\[%{JAVACLASS:class} *\\] \\[%{HOSTNAME:node}\\] %{JAVALOGMESSAGE:message}`.
You can analyze the same log file again, submitting this `grok_pattern` as a
query parameter (appropriately URL escaped):
[source,js]
----
curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&format=semi_structured_text&grok_pattern=%5C%5B%25%7BTIMESTAMP_ISO8601:timestamp%7D%5C%5D%5C%5B%25%7BLOGLEVEL:loglevel%7D%20*%5C%5D%5C%5B%25%7BJAVACLASS:class%7D%20*%5C%5D%20%5C%5B%25%7BHOSTNAME:node%7D%5C%5D%20%25%7BJAVALOGMESSAGE:message%7D"" -T ""$ES_HOME/logs/elasticsearch.log""
----
// NOTCONSOLE
// Not converting to console because this shows how curl can be used
If the request does not encounter errors, the result will look something like
this:
[source,js]
----
{
""num_lines_analyzed"" : 53,
""num_messages_analyzed"" : 53,
""sample_start"" : ""[2018-09-27T14:39:28,518][INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net usable_space [165.4gb], net total_space [464.7gb], types [hfs]\\n[2018-09-27T14:39:28,521][INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [494.9mb], compressed ordinary object pointers [true]\\n"",
""charset"" : ""UTF-8"",
""has_byte_order_marker"" : false,
""format"" : ""semi_structured_text"",
""multiline_start_pattern"" : ""^\\\\[\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"",
""grok_pattern"" : ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel} *\\\\]\\\\[%{JAVACLASS:class} *\\\\] \\\\[%{HOSTNAME:node}\\\\] %{JAVALOGMESSAGE:message}"", <1>
""timestamp_field"" : ""timestamp"",
""joda_timestamp_formats"" : [
""ISO8601""
],
""java_timestamp_formats"" : [
""ISO8601""
],
""need_client_timezone"" : true,
""mappings"" : {
""@timestamp"" : {
""type"" : ""date""
},
""class"" : {
""type"" : ""keyword""
},
""loglevel"" : {
""type"" : ""keyword""
},
""message"" : {
""type"" : ""text""
},
""node"" : {
""type"" : ""keyword""
}
},
""ingest_pipeline"" : {
""description"" : ""Ingest pipeline created by file structure finder"",
""processors"" : [
{
""grok"" : {
""field"" : ""message"",
""patterns"" : [
""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel} *\\\\]\\\\[%{JAVACLASS:class} *\\\\] \\\\[%{HOSTNAME:node}\\\\] %{JAVALOGMESSAGE:message}""
]
}
},
{
""date"" : {
""field"" : ""timestamp"",
""timezone"" : ""{{ beat.timezone }}"",
""formats"" : [
""ISO8601""
]
}
},
{
""remove"" : {
""field"" : ""timestamp""
}
}
]
},
""field_stats"" : { <2>
""class"" : {
""count"" : 53,
""cardinality"" : 14,
""top_hits"" : [
{
""value"" : ""o.e.p.PluginsService"",
""count"" : 26
},
{
""value"" : ""o.e.c.m.MetaDataIndexTemplateService"",
""count"" : 8
},
{
""value"" : ""o.e.n.Node"",
""count"" : 7
},
{
""value"" : ""o.e.e.NodeEnvironment"",
""count"" : 2
},
{
""value"" : ""o.e.a.ActionModule"",
""count"" : 1
},
{
""value"" : ""o.e.c.s.ClusterApplierService"",
""count"" : 1
},
{
""value"" : ""o.e.c.s.MasterService"",
""count"" : 1
},
{
""value"" : ""o.e.d.DiscoveryModule"",
""count"" : 1
},
{
""value"" : ""o.e.g.GatewayService"",
""count"" : 1
},
{
""value"" : ""o.e.l.LicenseService"",
""count"" : 1
}
]
},
""loglevel"" : {
""count"" : 53,
""cardinality"" : 3,
""top_hits"" : [
{
""value"" : ""INFO"",
""count"" : 51
},
{
""value"" : ""DEBUG"",
""count"" : 1
},
{
""value"" : ""WARN"",
""count"" : 1
}
]
},
""message"" : {
""count"" : 53,
""cardinality"" : 53,
""top_hits"" : [
{
""value"" : ""Using REST wrapper from plugin org.elasticsearch.xpack.security.Security"",
""count"" : 1
},
{
""value"" : ""adding template [.monitoring-alerts] for index patterns [.monitoring-alerts-6]"",
""count"" : 1
},
{
""value"" : ""adding template [.monitoring-beats] for index patterns [.monitoring-beats-6-*]"",
""count"" : 1
},
{
""value"" : ""adding template [.monitoring-es] for index patterns [.monitoring-es-6-*]"",
""count"" : 1
},
{
""value"" : ""adding template [.monitoring-kibana] for index patterns [.monitoring-kibana-6-*]"",
""count"" : 1
},
{
""value"" : ""adding template [.monitoring-logstash] for index patterns [.monitoring-logstash-6-*]"",
""count"" : 1
},
{
""value"" : ""adding template [.triggered_watches] for index patterns [.triggered_watches*]"",
""count"" : 1
},
{
""value"" : ""adding template [.watch-history-9] for index patterns [.watcher-history-9*]"",
""count"" : 1
},
{
""value"" : ""adding template [.watches] for index patterns [.watches*]"",
""count"" : 1
},
{
""value"" : ""starting ..."",
""count"" : 1
}
]
},
""node"" : {
""count"" : 53,
""cardinality"" : 1,
""top_hits"" : [
{
""value"" : ""node-0"",
""count"" : 53
}
]
},
""timestamp"" : {
""count"" : 53,
""cardinality"" : 28,
""earliest"" : ""2018-09-27T14:39:28,518"",
""latest"" : ""2018-09-27T14:39:37,012"",
""top_hits"" : [
{
""value"" : ""2018-09-27T14:39:29,859"",
""count"" : 10
},
{
""value"" : ""2018-09-27T14:39:29,860"",
""count"" : 9
},
{
""value"" : ""2018-09-27T14:39:29,858"",
""count"" : 6
},
{
""value"" : ""2018-09-27T14:39:28,523"",
""count"" : 3
},
{
""value"" : ""2018-09-27T14:39:34,234"",
""count"" : 2
},
{
""value"" : ""2018-09-27T14:39:28,518"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:28,521"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:28,522"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:29,861"",
""count"" : 1
},
{
""value"" : ""2018-09-27T14:39:32,786"",
""count"" : 1
}
]
}
}
}
----
// NOTCONSOLE
<1> The `grok_pattern` in the output is now the overridden one supplied in the
query parameter.
<2> The returned `field_stats` include entries for the fields from the
overridden `grok_pattern`.
The URL escaping is hard, so if you are working interactively it is best to use
the {ml} UI!
",16157,True,3221.7079248442224,median
"/*
VERSION: 10.11
DATE: 2/25/2009
ACTIONSCRIPT VERSION: 3.0 (AS2 version is also available)
UPDATES & MORE DETAILED DOCUMENTATION AT: http://www.TweenMax.com
DESCRIPTION:
TweenMax extends the extremely lightweight, FAST TweenLite engine, adding many useful features
like pause/resume, timeScale, event listeners, reverse(), restart(), setDestination(), yoyo, loop,
rounding, and the ability to jump to any point in the tween using the ""progress"" property. It also
activates many extra plugins by default, making it extremely full-featured. Since TweenMax extends
TweenLite, it can do ANYTHING TweenLite can do plus much more. Same syntax. There are plenty of other
tweening engines out there to choose from, so here's why you might want to consider TweenMax:
- SPEED - I'm not aware of any popular tweening engine with a similar feature set that's as fast
as TweenMax. See some speed comparisons yourself at http://blog.greensock.com/tweening-speed-test/
- Feature set - In addition to tweening ANY numeric property of ANY object, TweenMax can tween filters,
hex colors, volume, tint, frames, saturation, contrast, hue, colorization, brightness, and even do
bezier tweening, orientToBezier, pause/resume, reverse(), restart(), round values, jump to any point
in the tween with the ""progress"" property, automatically rotate in the shortest direction, plus LOTS more.
Overwrite management is an important consideration for a tweening engine as well which is another area
where the GreenSock tweening platform shines. You have options for AUTO overwriting or you can manually
define how each tween will handle overlapping tweens of the same object.
- Expandability - With its new plugin architecture, you can activate as many (or as few) features as your
project requires. Or write your own plugin if you need a feature that's unavailable. Minimize bloat and
maximize performance.
- Management features - TweenGroup makes it surprisingly simple to create complex sequences and groups
of TweenLite/Max tweens that you can pause(), resume(), restart(), or reverse(). You can even tween
a TweenGroup's progress property to fastforward or rewind the entire group/sequence.
- Ease of use - Designers and Developers alike rave about how intuitive the GreenSock tweening platform is.
- Updates - Frequent updates and feature additions make the GreenSock tweening platform reliable and robust.
- AS2 and AS3 - Most other engines are only developed for AS2 or AS3 but not both.
PARAMETERS:
1) $target : Object - Target object whose properties we're tweening
2) $duration : Number - Duration (in seconds) of the tween
3) $vars : Object - An object containing the end values of all the properties you'd like tweened (or if you're using
TweenMax.from(), these variables would define the BEGINNING values). For example, to tween
myClip's alpha to 0.5 over the course of 1 second, you'd do: TweenMax.to(myClip, 1, {alpha:0.5}).
SPECIAL PROPERTIES (no plugins required):
Any of the following special properties can optionally be passed in through the $vars object (the third parameter):
delay : Number - Amount of delay before the tween should begin (in seconds).
ease : Function - Use any standard easing equation to control the rate of change. For example,
gs.easing.Elastic.easeOut. The Default is Regular.easeOut.
easeParams : Array - An Array of extra parameters to feed the easing equation. This can be useful when
using an ease like Elastic and want to control extra parameters like the amplitude and period.
Most easing equations, however, don't require extra parameters so you won't need to pass in any easeParams.
onStart : Function - If you'd like to call a function as soon as the tween begins, reference it here.
onStartParams : Array - An Array of parameters to pass the onStart function.
onUpdate : Function - If you'd like to call a function every time the property values are updated (on every frame during
the course of the tween), reference it here.
onUpdateParams : Array - An Array of parameters to pass the onUpdate function
onComplete : Function - If you'd like to call a function when the tween has finished, reference it here.
onCompleteParams : Array - An Array of parameters to pass the onComplete function
persist : Boolean - if true, the TweenMax instance will NOT automatically be removed by the garbage collector when it is complete.
However, it is still eligible to be overwritten by new tweens even if persist is true. By default, it is false.
renderOnStart : Boolean - If you're using TweenMax.from() with a delay and want to prevent the tween from rendering until it
actually begins, set this to true. By default, it's false which causes TweenMax.from() to render
its values immediately, even before the delay has expired.
overwrite : int - Controls how other tweens of the same object are handled when this tween is created. Here are the options:
- 0 (NONE): No tweens are overwritten. This is the fastest mode, but you need to be careful not to create any
tweens with overlapping properties, otherwise they'll conflict with each other.
- 1 (ALL): (this is the default unless OverwriteManager.init() has been called) All tweens of the same object
are completely overwritten immediately when the tween is created.
TweenMax.to(mc, 1, {x:100, y:200});
TweenMax.to(mc, 1, {x:300, delay:2, overwrite:1}); //immediately overwrites the previous tween
- 2 (AUTO): (used by default if OverwriteManager.init() has been called) Searches for and overwrites only
individual overlapping properties in tweens that are active when the tween begins.
TweenMax.to(mc, 1, {x:100, y:200});
TweenMax.to(mc, 1, {x:300, overwrite:2}); //only overwrites the ""x"" property in the previous tween
- 3 (CONCURRENT): Overwrites all tweens of the same object that are active when the tween begins.
TweenMax.to(mc, 1, {x:100, y:200});
TweenMax.to(mc, 1, {x:300, delay:2, overwrite:3}); //does NOT overwrite the previous tween because the first tween will have finished by the time this one begins.
onStartListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent when it begins.
This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.START, myFunction);
onUpdateListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent every time it updates values.
This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.UPDATE, myFunction);
onCompleteListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent when it completes.
This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.COMPLETE, myFunction);
yoyo : Number - To make the tween reverse when it completes (like a yoyo) any number of times, set this to the number of cycles
you'd like the tween to yoyo. A value of zero causes the tween to yoyo endlessly.
loop : Number - To make the tween repeat when it completes any number of times, set this to the number of cycles
you'd like the tween to loop. A value of zero causes the tween to loop endlessly.
timeScale : Number - Multiplier that controls the speed of the tween (perceived duration) where 1 = normal speed, 0.5 = half speed, 2 = double speed, etc.
NOTE: There is also a static TweenMax.globalTimeScale property that affects ALL TweenMax and TweenFilterLite tweens (not TweenLite though)
startAt : Object - Allows you to define the starting values for each property. Typically, TweenMax uses the current
value (whatever it happens to be at the time the tween begins) as the start value, but startAt
allows you to override that behavior. Simply pass an object in with whatever properties you'd like
to set just before the tween begins. For example, if mc.x is currently 100, and you'd like to
tween it from 0 to 500, do TweenMax.to(mc, 2, {x:500, startAt:{x:0}});
PLUGINS:
There are many plugins that add capabilities through other special properties. Adding the capabilities
is as simple as activating the plugin with a single line of code, like SetSizePlugin.activate();
Get information about all the plugins at http://blog.greensock.com/plugins/
The following plugins are activated by default in TweenMax (you can easily prevent them from activating,
thus saving file size, by commenting out the associated activation lines of code in the constructor):
autoAlpha : Number - Use it instead of the alpha property to gain the additional feature of toggling
the visible property to false when alpha reaches 0. It will also toggle visible
to true before the tween starts if the value of autoAlpha is greater than zero.
visible : Boolean - To set a DisplayObject's ""visible"" property at the end of the tween, use this special property.
volume : Number - Tweens the volume of an object with a soundTransform property (MovieClip/SoundChannel/NetStream, etc.)
tint : Number - To change a DisplayObject's tint/color, set this to the hex value of the tint you'd like
to end up at(or begin at if you're using TweenMax.from()). An example hex value would be 0xFF0000.
removeTint : Boolean - If you'd like to remove the tint that's applied to a DisplayObject, pass true for this special property.
frame : Number - Use this to tween a MovieClip to a particular frame.
bezier : Array - Bezier tweening allows you to tween in a non-linear way. For example, you may want to tween
a MovieClip's position from the origin (0,0) 500 pixels to the right (500,0) but curve downwards
through the middle of the tween. Simply pass as many objects in the bezier array as you'd like,
one for each ""control point"" (see documentation on Flash's curveTo() drawing method for more
about how control points work). In this example, let's say the control point would be at x/y coordinates
250,50. Just make sure your my_mc is at coordinates 0,0 and then do:
TweenMax.to(my_mc, 3, {_x:500, _y:0, bezier:[{_x:250, _y:50}]});
bezierThrough : Array - Identical to bezier except that instead of passing bezier control point values, you
pass points through which the bezier values should move. This can be more intuitive
than using control points.
orientToBezier : Array (or Boolean) - A common effect that designers/developers want is for a MovieClip/Sprite to
orient itself in the direction of a Bezier path (alter its rotation). orientToBezier
makes it easy. In order to alter a rotation property accurately, TweenMax needs 4 pieces
of information:
1) Position property 1 (typically ""x"")
2) Position property 2 (typically ""y"")
3) Rotational property (typically ""rotation"")
4) Number of degrees to add (optional - makes it easy to orient your MovieClip properly)
The orientToBezier property should be an Array containing one Array for each set of these values.
For maximum flexibility, you can pass in any number of arrays inside the container array, one
for each rotational property. This can be convenient when working in 3D because you can rotate
on multiple axis. If you're doing a standard 2D x/y tween on a bezier, you can simply pass
in a boolean value of true and TweenMax will use a typical setup, [[""x"", ""y"", ""rotation"", 0]].
Hint: Don't forget the container Array (notice the double outer brackets)
hexColors : Object - Although hex colors are technically numbers, if you try to tween them conventionally,
you'll notice that they don't tween smoothly. To tween them properly, the red, green, and
blue components must be extracted and tweened independently. TweenMax makes it easy. To tween
a property of your object that's a hex color to another hex color, use this special hexColors
property of TweenMax. It must be an OBJECT with properties named the same as your object's
hex color properties. For example, if your my_obj object has a ""myHexColor"" property that you'd like
to tween to red (0xFF0000) over the course of 2 seconds, do:
TweenMax.to(my_obj, 2, {hexColors:{myHexColor:0xFF0000}});
You can pass in any number of hexColor properties.
shortRotation : Number - To tween the rotation property of the target object in the shortest direction, use ""shortRotation""
instead of ""rotation"" as the property. For example, if myObject.rotation is currently 170 degrees
and you want to tween it to -170 degrees, a normal rotation tween would travel a total of 340 degrees
in the counter-clockwise direction, but if you use shortRotation, it would travel 20 degrees in the
clockwise direction instead.
roundProps : Array - If you'd like the inbetween values in a tween to always get rounded to the nearest integer, use the roundProps
special property. Just pass in an Array containing the property names that you'd like rounded. For example,
if you're tweening the x, y, and alpha properties of mc and you want to round the x and y values (not alpha)
every time the tween is rendered, you'd do: TweenMax.to(mc, 2, {x:300, y:200, alpha:0.5, roundProps:[""x"",""y""]});
blurFilter : Object - To apply a BlurFilter, pass an object with one or more of the following properties:
blurX, blurY, quality
glowFilter : Object - To apply a GlowFilter, pass an object with one or more of the following properties:
alpha, blurX, blurY, color, strength, quality, inner, knockout
colorMatrixFilter : Object - To apply a ColorMatrixFilter, pass an object with one or more of the following properties:
colorize, amount, contrast, brightness, saturation, hue, threshold, relative, matrix
dropShadowFilter : Object - To apply a DropShadowFilter, pass an object with one or more of the following properties:
alpha, angle, blurX, blurY, color, distance, strength, quality
bevelFilter : Object - To apply a BevelFilter, pass an object with one or more of the following properties:
angle, blurX, blurY, distance, highlightAlpha, highlightColor, shadowAlpha, shadowColor, strength, quality
KEY PROPERTIES:
- progress : Number (0 - 1 where 0 = tween hasn't progressed, 0.5 = tween is halfway done, and 1 = tween is finished)
- timeScale : Number (Multiplier that controls the speed of the tween where 1 = normal speed, 0.5 = half speed, 2 = double speed, etc. )
- paused : Boolean
- reversed : Boolean
KEY METHODS:
- TweenMax.to(target:Object, duration:Number, vars:Object):TweenMax
- TweenMax.from(target:Object, duration:Number, vars:Object):TweenMax
- TweenMax.getTweensOf(target:Object):Array
- TweenMax.isTweening(target:Object):Boolean
- TweenMax.getAllTweens():Array
- TweenMax.killAllTweens(complete:Boolean):void
- TweenMax.killAllDelayedCalls(complete:Boolean):void
- TweenMax.pauseAll(tweens:Boolean, delayedCalls:Boolean):void
- TweenMax.resumeAll(tweens:Boolean, delayedCalls:Boolean):void
- TweenMax.delayedCall(delay:Number, function:Function, params:Array, persist:Boolean):TweenMax
- TweenMax.setGlobalTimeScale(scale:Number):void
- addEventListener(type:String, listener:Function, useCapture:Boolean, priority:int, useWeakReference:Boolean):void
- removeEventListener(type:String, listener:Function):void
- pause():void
- resume():void
- restart(includeDelay:Boolean):void
- reverse(adjustStart:Boolean, forcePlay:Boolean):void
- setDestination(property:String, value:*, adjustStartValues:Boolean):void
- invalidate(adjustStartValues:Boolean):void
- killProperties(names:Array):void
EXAMPLES:
To tween the clip_mc MovieClip over 5 seconds, changing the alpha to 0.5, the x to 120 using the Back.easeOut
easing function, delay starting the whole tween by 2 seconds, and then call a function named ""onFinishTween"" when
it has completed and pass in a few parameters to that function (a value of 5 and a reference to the clip_mc),
you'd do so like:
import gs.*;
import gs.easing.*;
TweenMax.to(clip_mc, 5, {alpha:0.5, x:120, ease:Back.easeOut, delay:2, onComplete:onFinishTween, onCompleteParams:[5, clip_mc]});
function onFinishTween(argument1:Number, argument2:MovieClip):void {
trace(""The tween has finished! argument1 = "" + argument1 + "", and argument2 = "" + argument2);
}
If you have a MovieClip on the stage that is already in it's end position and you just want to animate it into
place over 5 seconds (drop it into place by changing its y property to 100 pixels higher on the screen and
dropping it from there), you could:
import gs.*;
import gs.easing.*;
TweenMax.from(clip_mc, 5, {y:""-100"", ease:Elastic.easeOut});
To set up an onUpdate listener (not callback) that traces the ""progress"" property of a tween, and another listener
that gets called when the tween completes, you could do:
import gs.*;
import gs.events.TweenEvent;
TweenMax.to(clip_mc, 2, {x:200, onUpdateListener:reportProgress, onCompleteListener:tweenFinished});
function reportProgress($e:TweenEvent):void {
trace(""tween progress: "" + $e.target.progress);
}
function tweenFinished($e:TweenEvent):void {
trace(""tween finished!"");
}
NOTES / HINTS:
- Passing values as Strings will make the tween relative to the current value. For example, if you do
TweenMax.to(mc, 2, {x:""-20""}); it'll move the mc.x to the left 20 pixels which is the same as doing
TweenMax.to(mc, 2, {x:mc.x - 20}); You could also cast it like: TweenMax.to(mc, 2, {x:String(myVariable)});
- If you prefer, instead of using the onCompleteListener, onStartListener, and onUpdateListener special properties,
you can set up listeners the typical way, like:
var myTween:TweenMax = new TweenMax(my_mc, 2, {x:200});
myTween.addEventListener(TweenEvent.COMPLETE, myFunction);
- To tween an Array, just pass in an Array as a property named endArray like:
var myArray:Array = [1,2,3,4];
TweenMax.to(myArray, 1.5, {endArray:[10,20,30,40]});
- You can kill all tweens of a particular object anytime with the TweenMax.killTweensOf(myObject);
function. If you want to have the tweens forced to completion, pass true as the second parameter,
like TweenMax.killTweensOf(myObject, true);
- You can kill all delayedCalls to a particular function using TweenMax.killDelayedCallsTo(myFunction);
This can be helpful if you want to preempt a call.
- Use the TweenMax.from() method to animate things into place. For example, if you have things set up on
the stage in the spot where they should end up, and you just want to animate them into place, you can
pass in the beginning x and/or y and/or alpha (or whatever properties you want).
- If you find this class useful, please consider joining Club GreenSock which not only contributes
to ongoing development, but also gets you bonus classes (and other benefits) that are ONLY available
to members. Learn more at http://blog.greensock.com/club/
CHANGE LOG:
10.11:
- Fixed bug in setDestination() when adjustStartValues was false
- Fixed bug in startAt that caused it to wait one frame when the delay was zero.
10.1:
- Fixed bug that caused error when ""omit trace actions"" was selected in publish settings.
10.09:
- Fixed bug with timeScale
10.08:
- Fixed bug in setDestination()
- Fixed bug in SetSizePlugin
- Fixed bug in isTweening() which didn't report true immediately after a tween was created.
10.07:
- Fixed reporting of ""paused"" property being reversed
10.06:
- Added ""startAt"" special property for defining starting values.
- Speed improvements
- Integrated a new gs.utils.tween.TweenInfo class
- Minor internal changes
10.0:
- Major update, shifting to a ""plugin"" architecture for handling special properties.
- Eliminated TweenFilterLite and extended TweenLite instead
- Added ""remove"" property to all filter tweens to accommodate removing the filter at the end of the tween
- Added ""setSize"" and ""frameLabel"" plugins
- Speed enhancements
- Fixed minor overwrite bugs
- Updated the version to sync better with TweenLite (jumped from 3.6 to 10.0)
3.6:
- Added compatibility with TweenProxy and TweenProxy3D
- Fixed bug with adding event listeners via TweenMaxVars
3.52:
- Adjusted how the timeScale special property is handled internally. It should be more flexible and slightly faster now.
- Changed the way parseBeziers() stores values to make bezier tweening faster (Arrays instead of Objects with named properties)
3.51:
- Fixed problem that caused killAllTweens() to not fully kill paused tweens
3.5:
- Changed yoyo and loop behavior so that instead of being Boolean values that loop or yoyo endlessly, they're numbers so that you can define a specific number of cycles you'd like the tween to loop or yoyo. Zero causes the loop or yoyo to repeat endlessly.
3.41:
- Fixed conflict between TweenMaxVars and the new shortRotation property in Flash Player 10
3.4:
- Added ""shortRotation"" special property
- Minor speed enhancement
3.391:
- Minor change to make the timing of looping and yoyo-ing tweens more accurate (a few milliseconds could have been lost previously when the loop or yoyo was triggered)
3.39:
- Speed improvement and slight file size decrease
3.37:
- Fixed resumeAll()
3.36:
- Fixed bug with autoAlpha tweens working with TweenGroups when they're reversed.
3.35:
- Deprecated allTo() and allFrom() in favor of the much more powerful and flexible TweenGroup class (see http://blog.greensock.com/tweengroup/ for details)
3.2:
- Added ""roundProps"" special property for rounding values
- Fixed but with TweenLiteVars, TweenFilterVars, and TweenMaxVars that caused ""visible"" to always get set at the end of a tween
3.1:
- In AUTO or CONCURRENT mode, OverwriteManager doesn't handle overwriting until the tween actually begins which allows for immediate pause()-ing or re-ordering in TweenGroup, etc.
- Re-architected some inner-workings to further optimize for speed and reduce file size
3.04:
- Fixed bug with killTweensOf()
- Fixed bug with reverse()
- Fixed bug with from()
3.0:
- Deprecated sequence() and multiSequence() in favor of the much more powerful and flexible TweenGroup class (see http://blog.greensock.com/tweengroup/ for details)
- Added clear() method
- Added a ""clear"" parameter to the removeTween() method
- Exposed TweenLite.currentTime as well as several other TweenLite variables for compatibility with TweenGroup
2.35:
- Fixed potential problem if multiple tweens used the same vars object and reverse() was called on more than one.
2.34:
- Fixed problem with COMPLETE event listeners not firing when killTweensOf() was called with the forceComplete parameter set to true
2.32:
- Fixed bug with invalidating() a tween with event listeners and adding an UPDATE listener after a tween is instantiated.
2.31:
- invalidate() reparses onCompleteListener, onUpdateListener, and onStartListener special properties now.
- If a tween completed without persist:true and the globalTimeScale was updated between that time and the time restart(), reverse(), or resume() was called, it could have an incorrect timeScale. That's fixed now.
2.3:
- Added setGlobalTimeScale() function to control the speed of all TweenFilterLite and TweenMax instances
- Added static ""globalTimeScale"" property to TweenMax and TweenFilterLite classes. You can even tween it like TweenLite.to(TweenMax, 1, {globalTimeScale:0.5});
- Changed timeScale so that it also affects the delay (if any)
AUTHOR: Jack Doyle, jack@greensock.com
Copyright 2009, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
*/
package gs {
import flash.events.*;
import flash.utils.*;
import gs.events.TweenEvent;
import gs.plugins.*;
import gs.utils.tween.*;
public class TweenMax extends TweenLite implements IEventDispatcher {
public static const version:Number = 10.1;
private static var _activatedPlugins:Boolean = TweenPlugin.activate([
//ACTIVATE (OR DEACTIVATE) PLUGINS HERE...
TintPlugin, //tweens tints
RemoveTintPlugin, //allows you to remove a tint
FramePlugin, //tweens MovieClip frames
AutoAlphaPlugin, //tweens alpha and then toggles ""visible"" to false if/when alpha is zero
VisiblePlugin, //tweens a target's ""visible"" property
VolumePlugin, //tweens the volume of a MovieClip or SoundChannel or anything with a ""soundTransform"" property
EndArrayPlugin, //tweens numbers in an Array
HexColorsPlugin, //tweens hex colors
BlurFilterPlugin, //tweens BlurFilters
ColorMatrixFilterPlugin, //tweens ColorMatrixFilters (including hue, saturation, colorize, contrast, brightness, and threshold)
BevelFilterPlugin, //tweens BevelFilters
DropShadowFilterPlugin, //tweens DropShadowFilters
GlowFilterPlugin, //tweens GlowFilters
RoundPropsPlugin, //enables the roundProps special property for rounding values.
BezierPlugin, //enables bezier tweening
BezierThroughPlugin, //enables bezierThrough tweening
ShortRotationPlugin //tweens rotation values in the shortest direction
]); //activated in static var instead of constructor because otherwise if there's a from() tween, TweenLite's constructor would get called first and initTweenVals() would run before the plugins were activated.
private static var _overwriteMode:int = (OverwriteManager.enabled) ? OverwriteManager.mode : OverwriteManager.init(); //OverwriteManager is optional for TweenLite and TweenFilterLite, but it is used by default in TweenMax.
public static var killTweensOf:Function = TweenLite.killTweensOf;
public static var killDelayedCallsTo:Function = TweenLite.killTweensOf;
public static var removeTween:Function = TweenLite.removeTween;
protected static var _pausedTweens:Dictionary = new Dictionary(false); //protects from garbage collection issues
protected static var _globalTimeScale:Number = 1;
protected var _dispatcher:EventDispatcher;
protected var _callbacks:Object; //stores the original onComplete, onStart, and onUpdate Functions from the this.vars Object (we replace them if/when dispatching events)
protected var _repeatCount:Number; //number of times the tween has yoyo'd or loop'd.
protected var _timeScale:Number; //Allows you to speed up or slow down a tween. Default is 1 (normal speed) 0.5 would be half-speed
public var pauseTime:Number;
public function TweenMax($target:Object, $duration:Number, $vars:Object) {
super($target, $duration, $vars);
if (TweenLite.version < 10.09) {
trace(""TweenMax error! Please update your TweenLite class or try deleting your ASO files. TweenMax requires a more recent version. Download updates at http://www.TweenMax.com."");
}
if (this.combinedTimeScale != 1 && this.target is TweenMax) { //in case the user is trying to tween the timeScale of another TweenFilterLite/TweenMax instance
_timeScale = 1;
this.combinedTimeScale = _globalTimeScale;
} else {
_timeScale = this.combinedTimeScale;
this.combinedTimeScale *= _globalTimeScale; //combining them speeds processing in important functions like render().
}
if (this.combinedTimeScale != 1 && this.delay != 0) {
this.startTime = this.initTime + (this.delay * (1000 / this.combinedTimeScale));
}
if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null) {
initDispatcher();
if ($duration == 0 && this.delay == 0) {
onUpdateDispatcher();
onCompleteDispatcher();
}
}
_repeatCount = 0;
if (!isNaN(this.vars.yoyo) || !isNaN(this.vars.loop)) {
this.vars.persist = true;
}
if (this.delay == 0 && this.exposedVars.startAt != null) {
this.exposedVars.startAt.overwrite = 0;
new TweenMax(this.target, 0, this.exposedVars.startAt);
}
}
override public function initTweenVals():void {
if (this.exposedVars.startAt != null && this.delay != 0) {
this.exposedVars.startAt.overwrite = 0;
new TweenMax(this.target, 0, this.exposedVars.startAt);
}
super.initTweenVals();
//accommodate rounding if necessary...
if (this.exposedVars.roundProps is Array && TweenLite.plugins.roundProps != null) {
var i:int, j:int, prop:String, multiProps:String, rp:Array = this.exposedVars.roundProps, plugin:Object, ti:TweenInfo;
for (i = rp.length - 1; i > -1; i--) {
prop = rp[i];
for (j = this.tweens.length - 1; j > -1; j--) {
ti = this.tweens[j];
if (ti.name == prop) {
if (ti.isPlugin) {
ti.target.round = true;
} else {
if (plugin == null) {
plugin = new TweenLite.plugins.roundProps();
plugin.add(ti.target, prop, ti.start, ti.change);
_hasPlugins = true;
this.tweens[j] = new TweenInfo(plugin, ""changeFactor"", 0, 1, prop, true);
} else {
plugin.add(ti.target, prop, ti.start, ti.change); //using a single plugin for rounding speeds processing
this.tweens.splice(j, 1);
}
}
} else if (ti.isPlugin && ti.name == ""_MULTIPLE_"" && !ti.target.round) {
multiProps = "" "" + ti.target.overwriteProps.join("" "") + "" "";
if (multiProps.indexOf("" "" + prop + "" "") != -1) {
ti.target.round = true;
}
}
}
}
}
}
public function pause():void {
if (isNaN(this.pauseTime)) {
this.pauseTime = currentTime;
this.startTime = 999999999999999; //required for OverwriteManager
this.enabled = false;
_pausedTweens[this] = this;
}
}
public function resume():void {
this.enabled = true;
if (!isNaN(this.pauseTime)) {
this.initTime += currentTime - this.pauseTime;
this.startTime = this.initTime + (this.delay * (1000 / this.combinedTimeScale));
this.pauseTime = NaN;
if (!this.started && currentTime >= this.startTime) {
activate(); //triggers onStart if necessary and initTweenVals()
} else {
this.active = this.started;
}
_pausedTweens[this] = null;
delete _pausedTweens[this];
}
}
public function restart($includeDelay:Boolean=false):void {
if ($includeDelay) {
this.initTime = currentTime;
this.startTime = currentTime + (this.delay * (1000 / this.combinedTimeScale));
} else {
this.startTime = currentTime;
this.initTime = currentTime - (this.delay * (1000 / this.combinedTimeScale));
}
_repeatCount = 0;
if (this.target != this.vars.onComplete) { //protects delayedCall()s from being rendered.
render(this.startTime);
}
this.pauseTime = NaN;
_pausedTweens[this] = null;
delete _pausedTweens[this];
this.enabled = true;
}
public function reverse($adjustDuration:Boolean=true, $forcePlay:Boolean=true):void {
this.ease = (this.vars.ease == this.ease) ? reverseEase : this.vars.ease;
var p:Number = this.progress;
if ($adjustDuration && p > 0) {
this.startTime = currentTime - ((1 - p) * this.duration * 1000 / this.combinedTimeScale);
this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale));
}
if ($forcePlay != false) {
if (p < 1) {
resume();
} else {
restart();
}
}
}
public function reverseEase($t:Number, $b:Number, $c:Number, $d:Number):Number {
return this.vars.ease($d - $t, $b, $c, $d);
}
public function invalidate($adjustStartValues:Boolean=true):void { //forces the vars to be re-parsed and immediately re-rendered
if (this.initted) {
var p:Number = this.progress;
if (!$adjustStartValues && p != 0) {
this.progress = 0;
}
this.tweens = [];
_hasPlugins = false;
this.exposedVars = (this.vars.isTV == true) ? this.vars.exposedProps : this.vars; //for TweenLiteVars and TweenMaxVars
initTweenVals();
_timeScale = this.vars.timeScale || 1;
this.combinedTimeScale = _timeScale * _globalTimeScale;
this.delay = this.vars.delay || 0;
if (isNaN(this.pauseTime)) {
this.startTime = this.initTime + (this.delay * 1000 / this.combinedTimeScale);
}
if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null) {
if (_dispatcher != null) {
this.vars.onStart = _callbacks.onStart;
this.vars.onUpdate = _callbacks.onUpdate;
this.vars.onComplete = _callbacks.onComplete;
_dispatcher = null;
}
initDispatcher();
}
if (p != 0) {
if ($adjustStartValues) {
adjustStartValues();
} else {
this.progress = p;
}
}
}
}
public function setDestination($property:String, $value:*, $adjustStartValues:Boolean=true):void {
var p:Number = this.progress, i:int, ti:TweenInfo;
if (this.initted) {
if (!$adjustStartValues) {
for (i = this.tweens.length - 1; i > -1; i--) {
ti = this.tweens[i];
if (ti.name == $property) {
ti.target[ti.property] = ti.start; //return it to its start value (tween index values: [object, property, start, change, name])
}
}
}
var varsOld:Object = this.vars;
var exposedVarsOld:Object = this.exposedVars;
var tweensOld:Array = this.tweens;
var hadPlugins:Boolean = _hasPlugins;
this.tweens = [];
this.vars = this.exposedVars = {};
this.vars[$property] = $value;
initTweenVals();
if (this.ease != reverseEase && varsOld.ease is Function) {
this.ease = varsOld.ease;
}
if ($adjustStartValues && p != 0) {
adjustStartValues();
}
var addedTweens:Array = this.tweens;
this.vars = varsOld;
this.exposedVars = exposedVarsOld;
this.tweens = tweensOld;
var killVars:Object = {};
killVars[$property] = true;
for (i = this.tweens.length - 1; i > -1; i--) {
ti = this.tweens[i];
if (ti.name == $property) {
this.tweens.splice(i, 1);
} else if (ti.isPlugin && ti.name == ""_MULTIPLE_"") { //is a plugin with multiple overwritable properties
ti.target.killProps(killVars);
if (ti.target.overwriteProps.length == 0) {
this.tweens.splice(i, 1);
}
}
}
this.tweens = this.tweens.concat(addedTweens);
_hasPlugins = Boolean(hadPlugins || _hasPlugins);
}
this.vars[$property] = this.exposedVars[$property] = $value;
}
protected function adjustStartValues():void { //adjusts the start values in the tweens so that the current progress and end values are maintained which prevents ""skipping"" when changing destination values mid-way through the tween.
var p:Number = this.progress;
if (p != 0) {
var factor:Number = this.ease(p, 0, 1, 1);
var inv:Number = 1 / (1 - factor);
var endValue:Number, ti:TweenInfo, i:int;
for (i = this.tweens.length - 1; i > -1; i--) {
ti = this.tweens[i];
endValue = ti.start + ti.change; //[object, property, start, change, name, isPlugin]
if (ti.isPlugin) { //can't read the ""progress"" value of a plugin, but we know what it is based on the factor (above)
ti.change = (endValue - factor) * inv;
} else {
ti.change = (endValue - ti.target[ti.property]) * inv;
}
ti.start = endValue - ti.change;
}
}
}
public function killProperties($names:Array):void {
var v:Object = {}, i:int;
for (i = $names.length - 1; i > -1; i--) {
v[$names[i]] = true;
}
killVars(v);
}
override public function render($t:uint):void {
var time:Number = ($t - this.startTime) * 0.001 * this.combinedTimeScale, factor:Number, ti:TweenInfo, i:int;
if (time >= this.duration) {
time = this.duration;
factor = (this.ease == this.vars.ease || this.duration == 0.001) ? 1 : 0; //to accommodate TweenMax.reverse(). Without this, the last frame would render incorrectly
} else {
factor = this.ease(time, 0, 1, this.duration);
}
for (i = this.tweens.length - 1; i > -1; i--) {
ti = this.tweens[i];
ti.target[ti.property] = ti.start + (factor * ti.change); //tween index values: [object, property, start, change, name, isPlugin]
}
if (_hasUpdate) {
this.vars.onUpdate.apply(null, this.vars.onUpdateParams);
}
if (time == this.duration) { //Check to see if we're done
complete(true);
}
}
override public function complete($skipRender:Boolean = false):void {
if ((!isNaN(this.vars.yoyo) && (_repeatCount < this.vars.yoyo || this.vars.yoyo == 0)) || (!isNaN(this.vars.loop) && (_repeatCount < this.vars.loop || this.vars.loop == 0))) {
_repeatCount++;
if (!isNaN(this.vars.yoyo)) {
this.ease = (this.vars.ease == this.ease) ? reverseEase : this.vars.ease;
}
this.startTime = ($skipRender) ? this.startTime + (this.duration * (1000 / this.combinedTimeScale)) : currentTime; //for more accurate results, add the duration to the startTime, otherwise a few milliseconds might be skipped. You can occassionally see this if you have two simultaneous looping tweens with different end times that move objects that are butted up against each other.
this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale));
} else if (this.vars.persist == true) {
//super.complete($skipRender);
pause();
//return;
}
super.complete($skipRender);
}
//---- EVENT DISPATCHING ----------------------------------------------------------------------------------------------------------
protected function initDispatcher():void {
if (_dispatcher == null) {
_dispatcher = new EventDispatcher(this);
_callbacks = {onStart:this.vars.onStart, onUpdate:this.vars.onUpdate, onComplete:this.vars.onComplete}; //store the originals
if (this.vars.isTV == true) { //For TweenLiteVars, TweenFilterLiteVars, and TweenMaxVars compatibility
this.vars = this.vars.clone();
} else {
var v:Object = {}, p:String;
for (p in this.vars) {
v[p] = this.vars[p]; //Just in case the same vars Object is reused for multiple tweens, we need to copy all the properties and create a duplicate so that we don't interfere with other tweens.
}
this.vars = v;
}
this.vars.onStart = onStartDispatcher;
this.vars.onComplete = onCompleteDispatcher;
if (this.vars.onStartListener is Function) {
_dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true);
}
if (this.vars.onUpdateListener is Function) {
_dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true);
this.vars.onUpdate = onUpdateDispatcher; //To improve performance, we only want to add UPDATE dispatching if absolutely necessary.
_hasUpdate = true;
}
if (this.vars.onCompleteListener is Function) {
_dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true);
}
}
}
protected function onStartDispatcher(... $args):void {
if (_callbacks.onStart != null) {
_callbacks.onStart.apply(null, this.vars.onStartParams);
}
_dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START));
}
protected function onUpdateDispatcher(... $args):void {
if (_callbacks.onUpdate != null) {
_callbacks.onUpdate.apply(null, this.vars.onUpdateParams);
}
_dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE));
}
protected function onCompleteDispatcher(... $args):void {
if (_callbacks.onComplete != null) {
_callbacks.onComplete.apply(null, this.vars.onCompleteParams);
}
_dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE));
}
public function addEventListener($type:String, $listener:Function, $useCapture:Boolean = false, $priority:int = 0, $useWeakReference:Boolean = false):void {
if (_dispatcher == null) {
initDispatcher();
}
if ($type == TweenEvent.UPDATE && this.vars.onUpdate != onUpdateDispatcher) { //To improve performance, we only want to add UPDATE dispatching if absolutely necessary.
this.vars.onUpdate = onUpdateDispatcher;
_hasUpdate = true;
}
_dispatcher.addEventListener($type, $listener, $useCapture, $priority, $useWeakReference);
}
public function removeEventListener($type:String, $listener:Function, $useCapture:Boolean = false):void {
if (_dispatcher != null) {
_dispatcher.removeEventListener($type, $listener, $useCapture);
}
}
public function hasEventListener($type:String):Boolean {
if (_dispatcher == null) {
return false;
} else {
return _dispatcher.hasEventListener($type);
}
}
public function willTrigger($type:String):Boolean {
if (_dispatcher == null) {
return false;
} else {
return _dispatcher.willTrigger($type);
}
}
public function dispatchEvent($e:Event):Boolean {
if (_dispatcher == null) {
return false;
} else {
return _dispatcher.dispatchEvent($e);
}
}
//---- STATIC FUNCTIONS -----------------------------------------------------------------------------------------------------------
public static function to($target:Object, $duration:Number, $vars:Object):TweenMax {
return new TweenMax($target, $duration, $vars);
}
public static function from($target:Object, $duration:Number, $vars:Object):TweenMax {
$vars.runBackwards = true;
return new TweenMax($target, $duration, $vars);
}
public static function delayedCall($delay:Number, $onComplete:Function, $onCompleteParams:Array=null, $persist:Boolean=false):TweenMax {
return new TweenMax($onComplete, 0, {delay:$delay, onComplete:$onComplete, onCompleteParams:$onCompleteParams, persist:$persist, overwrite:0});
}
public static function setGlobalTimeScale($scale:Number):void {
if ($scale < 0.00001) {
$scale = 0.00001;
}
var ml:Dictionary = masterList, i:int, a:Array;
_globalTimeScale = $scale;
for each (a in ml) {
for (i = a.length - 1; i > -1; i--) {
if (a[i] is TweenMax) {
a[i].timeScale *= 1; //just forces combining of the _timeScale and _globalTimeScale.
}
}
}
}
public static function getTweensOf($target:Object):Array {
var a:Array = masterList[$target];
var toReturn:Array = [];
if(a != null) {
for (var i:int = a.length - 1; i > -1; i--) {
if (!a[i].gc) {
toReturn[toReturn.length] = a[i];
}
}
}
for each (var tween:TweenLite in _pausedTweens) {
if (tween.target == $target) {
toReturn[toReturn.length] = tween;
}
}
return toReturn;
}
public static function isTweening($target:Object):Boolean {
var a:Array = getTweensOf($target);
for (var i:int = a.length - 1; i > -1; i--) {
if ((a[i].active || a[i].startTime == currentTime) && !a[i].gc) {
return true;
}
}
return false;
}
public static function getAllTweens():Array {
var ml:Dictionary = masterList; //speeds things up slightly
var toReturn:Array = [], a:Array, i:int, tween:TweenLite;
for each (a in ml) {
for (i = a.length - 1; i > -1; i--) {
if (!a[i].gc) {
toReturn[toReturn.length] = a[i];
}
}
}
for each (tween in _pausedTweens) {
toReturn[toReturn.length] = tween;
}
return toReturn;
}
public static function killAllTweens($complete:Boolean = false):void {
killAll($complete, true, false);
}
public static function killAllDelayedCalls($complete:Boolean = false):void {
killAll($complete, false, true);
}
public static function killAll($complete:Boolean = false, $tweens:Boolean = true, $delayedCalls:Boolean = true):void {
var a:Array = getAllTweens();
var isDC:Boolean, i:int; //is delayedCall
for (i = a.length - 1; i > -1; i--) {
isDC = (a[i].target == a[i].vars.onComplete);
if (isDC == $delayedCalls || isDC != $tweens) {
if ($complete) {
a[i].complete(false);
a[i].clear();
} else {
TweenLite.removeTween(a[i], true);
}
}
}
}
public static function pauseAll($tweens:Boolean = true, $delayedCalls:Boolean = false):void {
changePause(true, $tweens, $delayedCalls);
}
public static function resumeAll($tweens:Boolean = true, $delayedCalls:Boolean = false):void {
changePause(false, $tweens, $delayedCalls);
}
public static function changePause($pause:Boolean, $tweens:Boolean = true, $delayedCalls:Boolean = false):void {
var a:Array = getAllTweens();
var isDC:Boolean; //is delayedCall
for (var i:int = a.length - 1; i > -1; i--) {
isDC = (a[i].target == a[i].vars.onComplete);
if (a[i] is TweenMax && (isDC == $delayedCalls || isDC != $tweens)) {
a[i].paused = $pause;
}
}
}
//---- GETTERS / SETTERS ----------------------------------------------------------------------------------------------------------
public function get paused():Boolean {
return !isNaN(this.pauseTime);
}
public function set paused($b:Boolean):void {
if ($b) {
pause();
} else {
resume();
}
}
public function get reversed():Boolean {
return (this.ease == reverseEase);
}
public function set reversed($b:Boolean):void {
if (this.reversed != $b) {
reverse();
}
}
public function get timeScale():Number {
return _timeScale;
}
public function set timeScale($n:Number):void {
if ($n < 0.00001) {
$n = _timeScale = 0.00001;
} else {
_timeScale = $n;
$n *= _globalTimeScale; //instead of doing _timeScale * _globalTimeScale in the render() and elsewhere, we improve performance by combining them here.
}
this.initTime = currentTime - ((currentTime - this.initTime - (this.delay * (1000 / this.combinedTimeScale))) * this.combinedTimeScale * (1 / $n)) - (this.delay * (1000 / $n));
if (this.startTime != 999999999999999) { //required for OverwriteManager (indicates a TweenMax instance that has been paused)
this.startTime = this.initTime + (this.delay * (1000 / $n));
}
this.combinedTimeScale = $n;
}
override public function set enabled($b:Boolean):void {
if (!$b) {
_pausedTweens[this] = null;
delete _pausedTweens[this];
}
super.enabled = $b;
if ($b) {
this.combinedTimeScale = _timeScale * _globalTimeScale;
}
}
public static function set globalTimeScale($n:Number):void {
setGlobalTimeScale($n);
}
public static function get globalTimeScale():Number {
return _globalTimeScale;
}
public function get progress():Number {
var t:Number = (!isNaN(this.pauseTime)) ? this.pauseTime : currentTime;
var p:Number = (((t - this.initTime) * 0.001) - this.delay / this.combinedTimeScale) / this.duration * this.combinedTimeScale;
if (p > 1) {
return 1;
} else if (p < 0) {
return 0;
} else {
return p;
}
}
public function set progress($n:Number):void {
this.startTime = currentTime - ((this.duration * $n) * 1000);
this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale));
if (!this.started) {
activate();//Just to trigger all the onStart stuff and make sure initTweenVals() has been called.
}
render(currentTime);
if (!isNaN(this.pauseTime)) {
this.pauseTime = currentTime;
this.startTime = 999999999999999; //required for OverwriteManager
this.active = false;
}
}
}
}",12521,False,1803.8109848525683,median
"// Urho3D material editor
Window@ particleEffectWindow;
ParticleEffect@ editParticleEffect;
XMLFile@ oldParticleEffectState;
bool inParticleEffectRefresh = false;
View3D@ particleEffectPreview;
Scene@ particlePreviewScene;
Node@ particleEffectPreviewNode;
Node@ particlePreviewCameraNode;
Node@ particlePreviewLightNode;
Light@ particlePreviewLight;
ParticleEmitter@ particleEffectEmitter;
float particleResetTimer;
void CreateParticleEffectEditor()
{
if (particleEffectWindow !is null)
return;
particleEffectWindow = LoadEditorUI(""UI/EditorParticleEffectWindow.xml"");
ui.root.AddChild(particleEffectWindow);
particleEffectWindow.opacity = uiMaxOpacity;
InitParticleEffectPreview();
InitParticleEffectBasicAttributes();
RefreshParticleEffectEditor();
int height = Min(ui.root.height - 60, 500);
particleEffectWindow.SetSize(300, height);
CenterDialog(particleEffectWindow);
HideParticleEffectEditor();
SubscribeToEvent(particleEffectWindow.GetChild(""NewButton"", true), ""Released"", ""NewParticleEffect"");
SubscribeToEvent(particleEffectWindow.GetChild(""RevertButton"", true), ""Released"", ""RevertParticleEffect"");
SubscribeToEvent(particleEffectWindow.GetChild(""SaveButton"", true), ""Released"", ""SaveParticleEffect"");
SubscribeToEvent(particleEffectWindow.GetChild(""SaveAsButton"", true), ""Released"", ""SaveParticleEffectAs"");
SubscribeToEvent(particleEffectWindow.GetChild(""CloseButton"", true), ""Released"", ""HideParticleEffectEditor"");
SubscribeToEvent(particleEffectWindow.GetChild(""NewColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameNew"");
SubscribeToEvent(particleEffectWindow.GetChild(""RemoveColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameRemove"");
SubscribeToEvent(particleEffectWindow.GetChild(""ColorFrameSort"", true), ""Released"", ""EditParticleEffectColorFrameSort"");
SubscribeToEvent(particleEffectWindow.GetChild(""NewTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameNew"");
SubscribeToEvent(particleEffectWindow.GetChild(""RemoveTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameRemove"");
SubscribeToEvent(particleEffectWindow.GetChild(""TextureFrameSort"", true), ""Released"", ""EditParticleEffectTextureFrameSort"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextChanged"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextChanged"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextChanged"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextChanged"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextChanged"", ""EditParticleEffectDampingForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextChanged"", ""EditParticleEffectActiveTime"");
SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextChanged"", ""EditParticleEffectInactiveTime"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextChanged"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextChanged"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextChanged"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextChanged"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextChanged"", ""EditParticleEffectTimeToLive"");
SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextChanged"", ""EditParticleEffectTimeToLive"");
SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextChanged"", ""EditParticleEffectVelocity"");
SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextChanged"", ""EditParticleEffectVelocity"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextChanged"", ""EditParticleEffectRotation"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextChanged"", ""EditParticleEffectRotation"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed"");
SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextChanged"", ""EditParticleEffectSizeAdd"");
SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextChanged"", ""EditParticleEffectSizeMultiply"");
SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextChanged"", ""EditParticleEffectAnimationLodBias"");
SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextChanged"", ""EditParticleEffectNumParticles"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextChanged"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextChanged"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextChanged"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextChanged"", ""EditParticleEffectEmissionRate"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextChanged"", ""EditParticleEffectEmissionRate"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextFinished"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextFinished"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextFinished"", ""EditParticleEffectConstantForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextFinished"", ""EditParticleEffectDirection"");
SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextFinished"", ""EditParticleEffectDampingForce"");
SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextFinished"", ""EditParticleEffectActiveTime"");
SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextFinished"", ""EditParticleEffectInactiveTime"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextFinished"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextFinished"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextFinished"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextFinished"", ""EditParticleEffectParticleSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextFinished"", ""EditParticleEffectTimeToLive"");
SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextFinished"", ""EditParticleEffectTimeToLive"");
SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextFinished"", ""EditParticleEffectVelocity"");
SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextFinished"", ""EditParticleEffectVelocity"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextFinished"", ""EditParticleEffectRotation"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextFinished"", ""EditParticleEffectRotation"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed"");
SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed"");
SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextFinished"", ""EditParticleEffectSizeAdd"");
SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextFinished"", ""EditParticleEffectSizeMultiply"");
SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextFinished"", ""EditParticleEffectAnimationLodBias"");
SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextFinished"", ""EditParticleEffectNumParticles"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextFinished"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextFinished"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextFinished"", ""EditParticleEffectEmitterSize"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextFinished"", ""EditParticleEffectEmissionRate"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextFinished"", ""EditParticleEffectEmissionRate"");
SubscribeToEvent(particleEffectWindow.GetChild(""EmitterShape"", true), ""ItemSelected"", ""EditParticleEffectEmitterShape"");
SubscribeToEvent(particleEffectWindow.GetChild(""Scaled"", true), ""Toggled"", ""EditParticleEffectScaled"");
SubscribeToEvent(particleEffectWindow.GetChild(""Sorted"", true), ""Toggled"", ""EditParticleEffectSorted"");
SubscribeToEvent(particleEffectWindow.GetChild(""Relative"", true), ""Toggled"", ""EditParticleEffectRelative"");
}
void EditParticleEffectColorFrameNew(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
uint num = editParticleEffect.numColorFrames;
editParticleEffect.numColorFrames = num + 1;
RefreshParticleEffectColorFrames();
EndParticleEffectEdit();
}
void EditParticleEffectTextureFrameNew(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
uint num = editParticleEffect.numTextureFrames;
editParticleEffect.numTextureFrames = num + 1;
RefreshParticleEffectTextureFrames();
EndParticleEffectEdit();
}
void EditParticleEffectColorFrameRemove(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true);
if (lv !is null && lv.selection != M_MAX_UNSIGNED )
{
BeginParticleEffectEdit();
editParticleEffect.RemoveColorFrame(lv.selection);
RefreshParticleEffectColorFrames();
EndParticleEffectEdit();
}
}
void EditParticleEffectTextureFrameRemove(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true);
if (lv !is null && lv.selection != M_MAX_UNSIGNED )
{
BeginParticleEffectEdit();
editParticleEffect.RemoveTextureFrame(lv.selection);
RefreshParticleEffectTextureFrames();
EndParticleEffectEdit();
}
}
void EditParticleEffectColorFrameSort(StringHash eventType, VariantMap& eventData)
{
RefreshParticleEffectColorFrames();
}
void EditParticleEffectTextureFrameSort(StringHash eventType, VariantMap& eventData)
{
RefreshParticleEffectTextureFrames();
}
void InitParticleEffectBasicAttributes()
{
CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceZ"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinZ"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""DampingForce"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ActiveTime"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""InactiveTime"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMin"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMax"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMin"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMax"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeAdd"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeMultiply"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""AnimationLodBias"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""NumParticles"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeX"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeY"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMin"", true)));
CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMax"", true)));
}
void EditParticleEffectConstantForce(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
Vector3 v = editParticleEffect.constantForce;
if (element.name == ""ConstantForceX"")
editParticleEffect.constantForce = Vector3(element.text.ToFloat(), v.y, v.z);
if (element.name == ""ConstantForceY"")
editParticleEffect.constantForce = Vector3(v.x, element.text.ToFloat(), v.z);
if (element.name == ""ConstantForceZ"")
editParticleEffect.constantForce = Vector3(v.x, v.y, element.text.ToFloat());
EndParticleEffectEdit();
}
void EditParticleEffectDirection(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
Vector3 vMin = editParticleEffect.minDirection;
Vector3 vMax = editParticleEffect.maxDirection;
if (element.name == ""DirectionMinX"")
editParticleEffect.minDirection = Vector3(element.text.ToFloat(), vMin.y, vMin.z);
if (element.name == ""DirectionMinY"")
editParticleEffect.minDirection = Vector3(vMin.x, element.text.ToFloat(), vMin.z);
if (element.name == ""DirectionMinZ"")
editParticleEffect.minDirection = Vector3(vMin.x, vMin.y, element.text.ToFloat());
if (element.name == ""DirectionMaxX"")
editParticleEffect.maxDirection = Vector3(element.text.ToFloat(), vMax.y, vMax.z);
if (element.name == ""DirectionMaxY"")
editParticleEffect.maxDirection = Vector3(vMax.x, element.text.ToFloat(), vMax.z);
if (element.name == ""DirectionMaxZ"")
editParticleEffect.maxDirection = Vector3(vMax.x, vMax.y, element.text.ToFloat());
EndParticleEffectEdit();
}
void EditParticleEffectDampingForce(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.dampingForce = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectActiveTime(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.activeTime = element.text.ToFloat();
particleEffectEmitter.Reset();
EndParticleEffectEdit();
}
void EditParticleEffectInactiveTime(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.inactiveTime = element.text.ToFloat();
particleEffectEmitter.Reset();
EndParticleEffectEdit();
}
void EditParticleEffectParticleSize(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
Vector2 vMin = editParticleEffect.minParticleSize;
Vector2 vMax = editParticleEffect.maxParticleSize;
if (element.name == ""ParticleSizeMinX"")
editParticleEffect.minParticleSize = Vector2(element.text.ToFloat(), vMin.y);
if (element.name == ""ParticleSizeMinY"")
editParticleEffect.minParticleSize = Vector2(vMin.x, element.text.ToFloat());
if (element.name == ""ParticleSizeMaxX"")
editParticleEffect.maxParticleSize = Vector2(element.text.ToFloat(), vMax.y);
if (element.name == ""ParticleSizeMaxY"")
editParticleEffect.maxParticleSize = Vector2(vMax.x, element.text.ToFloat());
EndParticleEffectEdit();
}
void EditParticleEffectTimeToLive(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
float vMin = editParticleEffect.minTimeToLive;
float vMax = editParticleEffect.maxTimeToLive;
if (element.name == ""TimeToLiveMin"")
editParticleEffect.minTimeToLive = element.text.ToFloat();
if (element.name == ""TimeToLiveMax"")
editParticleEffect.maxTimeToLive = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectVelocity(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
float vMin = editParticleEffect.minVelocity;
float vMax = editParticleEffect.maxVelocity;
if (element.name == ""VelocityMin"")
editParticleEffect.minVelocity = element.text.ToFloat();
if (element.name == ""VelocityMax"")
editParticleEffect.maxVelocity = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectRotation(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
float vMin = editParticleEffect.minRotation;
float vMax = editParticleEffect.maxRotation;
if (element.name == ""RotationMin"")
editParticleEffect.minRotation = element.text.ToFloat();
if (element.name == ""RotationMax"")
editParticleEffect.maxRotation = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectRotationSpeed(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
float vMin = editParticleEffect.minRotationSpeed;
float vMax = editParticleEffect.maxRotationSpeed;
if (element.name == ""RotationSpeedMin"")
editParticleEffect.minRotationSpeed = element.text.ToFloat();
if (element.name == ""RotationSpeedMax"")
editParticleEffect.maxRotationSpeed = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectSizeAdd(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.sizeAdd = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectSizeMultiply(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.sizeMul = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectAnimationLodBias(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.animationLodBias = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectNumParticles(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
editParticleEffect.numParticles = element.text.ToInt();
particleEffectEmitter.ApplyEffect();
EndParticleEffectEdit();
}
void EditParticleEffectEmitterSize(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
Vector3 v = editParticleEffect.emitterSize;
if (element.name == ""EmitterSizeX"")
editParticleEffect.emitterSize = Vector3(element.text.ToFloat(), v.y, v.z);
if (element.name == ""EmitterSizeY"")
editParticleEffect.emitterSize = Vector3(v.x, element.text.ToFloat(), v.z);
if (element.name == ""EmitterSizeZ"")
editParticleEffect.emitterSize = Vector3(v.x, v.y, element.text.ToFloat());
EndParticleEffectEdit();
}
void EditParticleEffectEmissionRate(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
if (element.name == ""EmissionRateMin"")
editParticleEffect.minEmissionRate = element.text.ToFloat();
if (element.name == ""EmissionRateMax"")
editParticleEffect.maxEmissionRate = element.text.ToFloat();
EndParticleEffectEdit();
}
void EditParticleEffectEmitterShape(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
BeginParticleEffectEdit();
DropDownList@ element = eventData[""Element""].GetPtr();
switch (element.selection)
{
case 0:
editParticleEffect.emitterType = EMITTER_BOX;
break;
case 1:
editParticleEffect.emitterType = EMITTER_SPHERE;
break;
}
EndParticleEffectEdit();
}
void EditParticleEffectMaterial(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
LineEdit@ element = eventData[""Element""].GetPtr();
Material@ res = cache.GetResource(""Material"", element.text);
if (res !is null)
{
BeginParticleEffectEdit();
editParticleEffect.material = res;
particleEffectEmitter.ApplyEffect();
EndParticleEffectEdit();
}
}
void PickEditParticleEffectMaterial(StringHash eventType, VariantMap& eventData)
{
@resourcePicker = GetResourcePicker(StringHash(""Material""));
if (resourcePicker is null)
return;
String lastPath = resourcePicker.lastPath;
if (lastPath.empty)
lastPath = sceneResourcePath;
CreateFileSelector(""Pick "" + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter);
SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectMaterialDone"");
}
void PickEditParticleEffectMaterialDone(StringHash eventType, VariantMap& eventData)
{
StoreResourcePickerPath();
CloseFileSelector();
if (!eventData[""OK""].GetBool())
{
@resourcePicker = null;
return;
}
String resourceName = eventData[""FileName""].GetString();
Resource@ res = GetPickedResource(resourceName);
if (res !is null && editParticleEffect !is null && particleEffectEmitter !is null)
{
editParticleEffect.material = res;
particleEffectEmitter.ApplyEffect();
RefreshParticleEffectMaterial();
}
@resourcePicker = null;
}
void EditParticleEffectScaled(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
CheckBox@ element = eventData[""Element""].GetPtr();
editParticleEffect.scaled = element.checked;
particleEffectEmitter.ApplyEffect();
EndParticleEffectEdit();
}
void EditParticleEffectSorted(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
CheckBox@ element = eventData[""Element""].GetPtr();
editParticleEffect.sorted = element.checked;
particleEffectEmitter.ApplyEffect();
EndParticleEffectEdit();
}
void EditParticleEffectRelative(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
CheckBox@ element = eventData[""Element""].GetPtr();
editParticleEffect.relative = element.checked;
particleEffectEmitter.ApplyEffect();
EndParticleEffectEdit();
}
bool ShowParticleEffectEditor()
{
RefreshParticleEffectEditor();
particleEffectWindow.visible = true;
particleEffectWindow.BringToFront();
return true;
}
void HideParticleEffectEditor()
{
if (particleEffectWindow !is null)
particleEffectWindow.visible = false;
}
void InitParticleEffectPreview()
{
particlePreviewScene = Scene(""particlePreviewScene"");
particlePreviewScene.CreateComponent(""Octree"");
Node@ zoneNode = particlePreviewScene.CreateChild(""Zone"");
Zone@ zone = zoneNode.CreateComponent(""Zone"");
zone.boundingBox = BoundingBox(-1000, 1000);
zone.ambientColor = Color(0.15, 0.15, 0.15);
zone.fogColor = Color(0, 0, 0);
zone.fogStart = 10.0;
zone.fogEnd = 100.0;
particlePreviewCameraNode = particlePreviewScene.CreateChild(""PreviewCamera"");
particlePreviewCameraNode.position = Vector3(0, 0, -2.5);
Camera@ camera = particlePreviewCameraNode.CreateComponent(""Camera"");
camera.nearClip = 0.1f;
camera.farClip = 100.0f;
particlePreviewLightNode = particlePreviewScene.CreateChild(""particlePreviewLight"");
particlePreviewLightNode.direction = Vector3(0.5, -0.5, 0.5);
particlePreviewLight = particlePreviewLightNode.CreateComponent(""Light"");
particlePreviewLight.lightType = LIGHT_DIRECTIONAL;
particlePreviewLight.specularIntensity = 0.5;
particleEffectPreviewNode = particlePreviewScene.CreateChild(""PreviewEmitter"");
particleEffectPreviewNode.rotation = Quaternion(0, 0, 0);
StaticModel@ gizmo = particleEffectPreviewNode.CreateComponent(""StaticModel"");
gizmo.model = cache.GetResource(""Model"", ""Models/Editor/Axes.mdl"");
gizmo.materials[0] = cache.GetResource(""Material"", ""Materials/Editor/RedUnlit.xml"");
gizmo.materials[1] = cache.GetResource(""Material"", ""Materials/Editor/GreenUnlit.xml"");
gizmo.materials[2] = cache.GetResource(""Material"", ""Materials/Editor/BlueUnlit.xml"");
gizmo.occludee = false;
particleEffectEmitter = particleEffectPreviewNode.CreateComponent(""ParticleEmitter"");
editParticleEffect = CreateNewParticleEffect();
particleEffectEmitter.effect = editParticleEffect;
particleEffectPreview = particleEffectWindow.GetChild(""ParticleEffectPreview"", true);
particleEffectPreview.SetFixedHeight(100);
particleEffectPreview.SetView(particlePreviewScene, camera);
SubscribeToEvent(particleEffectPreview, ""DragMove"", ""RotateParticleEffectPreview"");
}
ParticleEffect@ CreateNewParticleEffect()
{
ParticleEffect@ effect = ParticleEffect();
Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml"");
if (res is null)
log.Error(""Could not load default material for new particle effect."");
effect.material = res;
effect.AddColorTime(Color(1,1,1,1), 0.0f);
return effect;
}
void EditParticleEffect(ParticleEffect@ effect)
{
if (effect is null)
return;
if (editParticleEffect !is null)
UnsubscribeFromEvent(editParticleEffect, ""ReloadFinished"");
if (!effect.name.empty)
cache.ReloadResource(effect);
editParticleEffect = effect;
particleEffectEmitter.effect = editParticleEffect;
if (editParticleEffect !is null)
SubscribeToEvent(editParticleEffect, ""ReloadFinished"", ""RefreshParticleEffectEditor"");
ShowParticleEffectEditor();
}
void RefreshParticleEffectEditor()
{
inParticleEffectRefresh = true;
RefreshParticleEffectPreview();
RefreshParticleEffectName();
RefreshParticleEffectBasicAttributes();
RefreshParticleEffectMaterial();
RefreshParticleEffectColorFrames();
RefreshParticleEffectTextureFrames();
inParticleEffectRefresh = false;
}
void RefreshParticleEffectColorFrames()
{
if (editParticleEffect is null)
return;
editParticleEffect.SortColorFrames();
ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true);
if (lv is null)
return;
lv.RemoveAllItems();
for (uint i = 0; i < editParticleEffect.numColorFrames; i++)
{
ColorFrame@ colorFrame = editParticleEffect.GetColorFrame(i);
Button@ container = Button();
lv.AddItem(container);
container.style = ""Button"";
container.imageRect = IntRect(18, 2, 30, 14);
container.minSize = IntVector2(0, 20);
container.maxSize = IntVector2(2147483647, 20);
container.layoutMode = LM_HORIZONTAL;
container.layoutBorder = IntRect(3,1,3,1);
container.layoutSpacing = 4;
UIElement@ labelContainer = UIElement();
container.AddChild(labelContainer);
labelContainer.style = ""HorizontalPanel"";
labelContainer.minSize = IntVector2(0, 16);
labelContainer.maxSize = IntVector2(2147483647, 16);
labelContainer.verticalAlignment = VA_CENTER;
{
LineEdit@ le = LineEdit();
labelContainer.AddChild(le);
le.name = ""ColorTime"";
le.vars[""ColorFrame""] = i;
le.style = ""LineEdit"";
le.minSize = IntVector2(0, 16);
le.maxSize = IntVector2(40, 16);
le.text = colorFrame.time;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame"");
}
UIElement@ textContainer = UIElement();
labelContainer.AddChild(textContainer);
textContainer.minSize = IntVector2(0, 16);
textContainer.maxSize = IntVector2(2147483647, 16);
textContainer.verticalAlignment = VA_CENTER;
Text@ t = Text();
textContainer.AddChild(t);
t.style = ""Text"";
t.text = ""Color"";
UIElement@ editContainer = UIElement();
container.AddChild(editContainer);
editContainer.style = ""HorizontalPanel"";
editContainer.minSize = IntVector2(0, 16);
editContainer.maxSize = IntVector2(2147483647, 16);
editContainer.verticalAlignment = VA_CENTER;
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""ColorR"";
le.vars[""ColorFrame""] = i;
le.style = ""LineEdit"";
le.text = colorFrame.color.r;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""ColorG"";
le.vars[""ColorFrame""] = i;
le.style = ""LineEdit"";
le.text = colorFrame.color.g;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""ColorB"";
le.vars[""ColorFrame""] = i;
le.style = ""LineEdit"";
le.text = colorFrame.color.b;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""ColorA"";
le.vars[""ColorFrame""] = i;
le.style = ""LineEdit"";
le.text = colorFrame.color.a;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame"");
}
}
}
void RefreshParticleEffectTextureFrames()
{
if (editParticleEffect is null)
return;
editParticleEffect.SortTextureFrames();
ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true);
if (lv is null)
return;
lv.RemoveAllItems();
for (uint i = 0; i < editParticleEffect.numTextureFrames; i++)
{
TextureFrame@ textureFrame = editParticleEffect.GetTextureFrame(i);
if (textureFrame is null)
continue;
Button@ container = Button();
lv.AddItem(container);
container.style = ""Button"";
container.imageRect = IntRect(18, 2, 30, 14);
container.minSize = IntVector2(0, 20);
container.maxSize = IntVector2(2147483647, 20);
container.layoutMode = LM_HORIZONTAL;
container.layoutBorder = IntRect(1,1,1,1);
container.layoutSpacing = 4;
UIElement@ labelContainer = UIElement();
container.AddChild(labelContainer);
labelContainer.style = ""HorizontalPanel"";
labelContainer.minSize = IntVector2(0, 16);
labelContainer.maxSize = IntVector2(2147483647, 16);
labelContainer.verticalAlignment = VA_CENTER;
{
LineEdit@ le = LineEdit();
labelContainer.AddChild(le);
le.name = ""TextureTime"";
le.vars[""TextureFrame""] = i;
le.style = ""LineEdit"";
le.minSize = IntVector2(0, 16);
le.maxSize = IntVector2(40, 16);
le.text = textureFrame.time;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame"");
}
UIElement@ textContainer = UIElement();
labelContainer.AddChild(textContainer);
textContainer.minSize = IntVector2(0, 16);
textContainer.maxSize = IntVector2(2147483647, 16);
textContainer.verticalAlignment = VA_CENTER;
Text@ t = Text();
textContainer.AddChild(t);
t.style = ""Text"";
t.text = ""Texture"";
UIElement@ editContainer = UIElement();
container.AddChild(editContainer);
editContainer.style = ""HorizontalPanel"";
editContainer.minSize = IntVector2(0, 16);
editContainer.maxSize = IntVector2(2147483647, 16);
editContainer.verticalAlignment = VA_CENTER;
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""TextureMinX"";
le.vars[""TextureFrame""] = i;
le.style = ""LineEdit"";
le.text = textureFrame.uv.min.x;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""TextureMinY"";
le.vars[""TextureFrame""] = i;
le.style = ""LineEdit"";
le.text = textureFrame.uv.min.y;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""TextureMaxX"";
le.vars[""TextureFrame""] = i;
le.style = ""LineEdit"";
le.text = textureFrame.uv.max.x;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame"");
}
{
LineEdit@ le = LineEdit();
editContainer.AddChild(le);
le.name = ""TextureMaxY"";
le.vars[""TextureFrame""] = i;
le.style = ""LineEdit"";
le.text = textureFrame.uv.max.y;
le.cursorPosition = 0;
CreateDragSlider(le);
SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame"");
}
}
}
void EditParticleEffectColorFrame(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
uint i = element.vars[""ColorFrame""].GetInt();
ColorFrame@ cf = editParticleEffect.GetColorFrame(i);
if (element.name == ""ColorTime"")
cf.time = element.text.ToFloat();
if (element.name == ""ColorR"")
cf.color = Color(element.text.ToFloat(), cf.color.g, cf.color.b, cf.color.a);
if (element.name == ""ColorG"")
cf.color = Color(cf.color.r, element.text.ToFloat(), cf.color.b, cf.color.a);
if (element.name == ""ColorB"")
cf.color = Color(cf.color.r, cf.color.g, element.text.ToFloat(), cf.color.a);
if (element.name == ""ColorA"")
cf.color = Color(cf.color.r, cf.color.g, cf.color.b, element.text.ToFloat());
editParticleEffect.SetColorFrame(i, cf);
particleEffectEmitter.Reset();
EndParticleEffectEdit();
}
void EditParticleEffectTextureFrame(StringHash eventType, VariantMap& eventData)
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (particleEffectEmitter is null)
return;
BeginParticleEffectEdit();
LineEdit@ element = eventData[""Element""].GetPtr();
uint i = element.vars[""TextureFrame""].GetInt();
TextureFrame@ tf = editParticleEffect.GetTextureFrame(i);
if (element.name == ""TextureTime"")
tf.time = element.text.ToFloat();
if (element.name == ""TextureMinX"")
tf.uv = Rect(element.text.ToFloat(), tf.uv.min.y, tf.uv.max.x, tf.uv.max.y);
if (element.name == ""TextureMinY"")
tf.uv = Rect(tf.uv.min.x, element.text.ToFloat(), tf.uv.max.x, tf.uv.max.y);
if (element.name == ""TextureMaxX"")
tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, element.text.ToFloat(), tf.uv.max.y);
if (element.name == ""TextureMaxY"")
tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, tf.uv.max.x, element.text.ToFloat());
editParticleEffect.SetTextureFrame(i, tf);
particleEffectEmitter.Reset();
EndParticleEffectEdit();
}
void RefreshParticleEffectPreview()
{
if (particleEffectEmitter is null || editParticleEffect is null)
return;
particleEffectEmitter.effect = editParticleEffect;
particleEffectEmitter.Reset();
particleEffectPreview.QueueUpdate();
}
void RefreshParticleEffectName()
{
UIElement@ container = particleEffectWindow.GetChild(""NameContainer"", true);
if (container is null)
return;
container.RemoveAllChildren();
LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0);
if (editParticleEffect !is null)
nameEdit.text = editParticleEffect.name;
SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectName"");
Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""Pick"");
SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffect"");
}
void RefreshParticleEffectBasicAttributes()
{
if (editParticleEffect is null)
return;
cast(particleEffectWindow.GetChild(""ConstantForceX"", true)).text = editParticleEffect.constantForce.x;
cast(particleEffectWindow.GetChild(""ConstantForceY"", true)).text = editParticleEffect.constantForce.y;
cast(particleEffectWindow.GetChild(""ConstantForceZ"", true)).text = editParticleEffect.constantForce.z;
cast(particleEffectWindow.GetChild(""DirectionMinX"", true)).text = editParticleEffect.minDirection.x;
cast(particleEffectWindow.GetChild(""DirectionMinY"", true)).text = editParticleEffect.minDirection.y;
cast(particleEffectWindow.GetChild(""DirectionMinZ"", true)).text = editParticleEffect.minDirection.z;
cast(particleEffectWindow.GetChild(""DirectionMaxX"", true)).text = editParticleEffect.maxDirection.x;
cast(particleEffectWindow.GetChild(""DirectionMaxY"", true)).text = editParticleEffect.maxDirection.y;
cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true)).text = editParticleEffect.maxDirection.z;
cast(particleEffectWindow.GetChild(""DampingForce"", true)).text = editParticleEffect.dampingForce;
cast(particleEffectWindow.GetChild(""ActiveTime"", true)).text = editParticleEffect.activeTime;
cast(particleEffectWindow.GetChild(""InactiveTime"", true)).text = editParticleEffect.inactiveTime;
cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true)).text = editParticleEffect.minParticleSize.x;
cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true)).text = editParticleEffect.minParticleSize.y;
cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true)).text = editParticleEffect.maxParticleSize.x;
cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true)).text = editParticleEffect.maxParticleSize.y;
cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true)).text = editParticleEffect.minTimeToLive;
cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true)).text = editParticleEffect.maxTimeToLive;
cast(particleEffectWindow.GetChild(""VelocityMin"", true)).text = editParticleEffect.minVelocity;
cast(particleEffectWindow.GetChild(""VelocityMax"", true)).text = editParticleEffect.maxVelocity;
cast(particleEffectWindow.GetChild(""RotationMin"", true)).text = editParticleEffect.minRotation;
cast(particleEffectWindow.GetChild(""RotationMax"", true)).text = editParticleEffect.maxRotation;
cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true)).text = editParticleEffect.minRotationSpeed;
cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true)).text = editParticleEffect.maxRotationSpeed;
cast(particleEffectWindow.GetChild(""SizeAdd"", true)).text = editParticleEffect.sizeAdd;
cast(particleEffectWindow.GetChild(""SizeMultiply"", true)).text = editParticleEffect.sizeMul;
cast(particleEffectWindow.GetChild(""AnimationLodBias"", true)).text = editParticleEffect.animationLodBias;
cast(particleEffectWindow.GetChild(""NumParticles"", true)).text = editParticleEffect.numParticles;
cast(particleEffectWindow.GetChild(""EmitterSizeX"", true)).text = editParticleEffect.emitterSize.x;
cast(particleEffectWindow.GetChild(""EmitterSizeY"", true)).text = editParticleEffect.emitterSize.y;
cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true)).text = editParticleEffect.emitterSize.z;
cast(particleEffectWindow.GetChild(""EmissionRateMin"", true)).text = editParticleEffect.minEmissionRate;
cast(particleEffectWindow.GetChild(""EmissionRateMax"", true)).text = editParticleEffect.maxEmissionRate;
switch (editParticleEffect.emitterType)
{
case EMITTER_BOX:
cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 0;
break;
case EMITTER_SPHERE:
cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 1;
break;
}
cast(particleEffectWindow.GetChild(""Scaled"", true)).checked = editParticleEffect.scaled;
cast(particleEffectWindow.GetChild(""Sorted"", true)).checked = editParticleEffect.sorted;
cast(particleEffectWindow.GetChild(""Relative"", true)).checked = editParticleEffect.relative;
}
void RefreshParticleEffectMaterial()
{
UIElement@ container = particleEffectWindow.GetChild(""ParticleMaterialContainer"", true);
if (container is null)
return;
container.RemoveAllChildren();
LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0);
if (editParticleEffect !is null)
{
if (editParticleEffect.material !is null)
nameEdit.text = editParticleEffect.material.name;
else
{
nameEdit.text = ""Materials/Particle.xml"";
Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml"");
if (res !is null)
editParticleEffect.material = res;
}
}
SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectMaterial"");
Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""Pick"");
SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffectMaterial"");
}
void RotateParticleEffectPreview(StringHash eventType, VariantMap& eventData)
{
int elemX = eventData[""ElementX""].GetInt();
int elemY = eventData[""ElementY""].GetInt();
if (particleEffectPreview.height > 0 && particleEffectPreview.width > 0)
{
float yaw = ((particleEffectPreview.height / 2) - elemY) * (90.0 / particleEffectPreview.height);
float pitch = ((particleEffectPreview.width / 2) - elemX) * (90.0 / particleEffectPreview.width);
particleEffectPreviewNode.rotation = particleEffectPreviewNode.rotation.Slerp(Quaternion(yaw, pitch, 0), 0.1);
particleEffectPreview.QueueUpdate();
}
}
void EditParticleEffectName(StringHash eventType, VariantMap& eventData)
{
LineEdit@ nameEdit = eventData[""Element""].GetPtr();
String newParticleEffectName = nameEdit.text.Trimmed();
if (!newParticleEffectName.empty && !(editParticleEffect !is null && newParticleEffectName == editParticleEffect.name))
{
ParticleEffect@ newParticleEffect = cache.GetResource(""ParticleEffect"", newParticleEffectName);
if (newParticleEffect !is null)
EditParticleEffect(newParticleEffect);
}
}
void PickEditParticleEffect()
{
@resourcePicker = GetResourcePicker(StringHash(""ParticleEffect""));
if (resourcePicker is null)
return;
String lastPath = resourcePicker.lastPath;
if (lastPath.empty)
lastPath = sceneResourcePath;
CreateFileSelector(""Pick "" + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter);
SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectDone"");
}
void PickEditParticleEffectDone(StringHash eventType, VariantMap& eventData)
{
StoreResourcePickerPath();
CloseFileSelector();
if (!eventData[""OK""].GetBool())
{
@resourcePicker = null;
return;
}
String resourceName = eventData[""FileName""].GetString();
Resource@ res = GetPickedResource(resourceName);
if (res !is null)
EditParticleEffect(cast(res));
@resourcePicker = null;
}
void NewParticleEffect()
{
BeginParticleEffectEdit();
EditParticleEffect(CreateNewParticleEffect());
EndParticleEffectEdit();
}
void RevertParticleEffect()
{
if (inParticleEffectRefresh)
return;
if (editParticleEffect is null)
return;
if (editParticleEffect.name.empty)
{
NewParticleEffect();
return;
}
BeginParticleEffectEdit();
cache.ReloadResource(editParticleEffect);
EndParticleEffectEdit();
RefreshParticleEffectEditor();
}
void SaveParticleEffect()
{
if (editParticleEffect is null || editParticleEffect.name.empty)
return;
String fullName = cache.GetResourceFileName(editParticleEffect.name);
if (fullName.empty)
return;
File saveFile(fullName, FILE_WRITE);
editParticleEffect.Save(saveFile);
}
void SaveParticleEffectAs()
{
if (editParticleEffect is null)
return;
@resourcePicker = GetResourcePicker(StringHash(""ParticleEffect""));
if (resourcePicker is null)
return;
String lastPath = resourcePicker.lastPath;
if (lastPath.empty)
lastPath = sceneResourcePath;
CreateFileSelector(""Save material as"", ""Save"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter);
SubscribeToEvent(uiFileSelector, ""FileSelected"", ""SaveParticleEffectAsDone"");
}
void SaveParticleEffectAsDone(StringHash eventType, VariantMap& eventData)
{
StoreResourcePickerPath();
CloseFileSelector();
@resourcePicker = null;
if (editParticleEffect is null)
return;
if (!eventData[""OK""].GetBool())
{
@resourcePicker = null;
return;
}
String fullName = eventData[""FileName""].GetString();
// Add default extension for saving if not specified
String filter = eventData[""Filter""].GetString();
if (GetExtension(fullName).empty && filter != ""*.*"")
fullName = fullName + filter.Substring(1);
File saveFile(fullName, FILE_WRITE);
if (editParticleEffect.Save(saveFile))
{
saveFile.Close();
// Load the new resource to update the name in the editor
ParticleEffect@ newEffect = cache.GetResource(""ParticleEffect"", GetResourceNameFromFullName(fullName));
if (newEffect !is null)
EditParticleEffect(newEffect);
}
}
void BeginParticleEffectEdit()
{
if (editParticleEffect is null)
return;
inParticleEffectRefresh = true;
oldParticleEffectState = XMLFile();
XMLElement particleElem = oldParticleEffectState.CreateRoot(""particleeffect"");
editParticleEffect.Save(particleElem);
}
void EndParticleEffectEdit()
{
if (editParticleEffect is null)
return;
if (!dragEditAttribute)
{
EditParticleEffectAction@ action = EditParticleEffectAction();
action.Define(particleEffectEmitter, editParticleEffect, oldParticleEffectState);
SaveEditAction(action);
}
inParticleEffectRefresh = false;
particleEffectPreview.QueueUpdate();
}
",12061,False,2339.537508633485,median
"UIElement@ browserWindow;
Window@ browserFilterWindow;
ListView@ browserDirList;
ListView@ browserFileList;
LineEdit@ browserSearch;
BrowserFile@ browserDragFile;
Node@ browserDragNode;
Component@ browserDragComponent;
View3D@ resourceBrowserPreview;
Scene@ resourcePreviewScene;
Node@ resourcePreviewNode;
Node@ resourcePreviewCameraNode;
Node@ resourcePreviewLightNode;
Light@ resourcePreviewLight;
int browserSearchSortMode = 0;
BrowserDir@ rootDir;
Array browserFiles;
Dictionary browserDirs;
Array activeResourceTypeFilters;
Array activeResourceDirFilters;
Array browserFilesToScan;
const uint BROWSER_WORKER_ITEMS_PER_TICK = 10;
const uint BROWSER_SEARCH_LIMIT = 50;
const int BROWSER_SORT_MODE_ALPHA = 1;
const int BROWSER_SORT_MODE_SEARCH = 2;
const int RESOURCE_TYPE_UNUSABLE = -2;
const int RESOURCE_TYPE_UNKNOWN = -1;
const int RESOURCE_TYPE_NOTSET = 0;
const int RESOURCE_TYPE_SCENE = 1;
const int RESOURCE_TYPE_SCRIPTFILE = 2;
const int RESOURCE_TYPE_MODEL = 3;
const int RESOURCE_TYPE_MATERIAL = 4;
const int RESOURCE_TYPE_ANIMATION = 5;
const int RESOURCE_TYPE_IMAGE = 6;
const int RESOURCE_TYPE_SOUND = 7;
const int RESOURCE_TYPE_TEXTURE = 8;
const int RESOURCE_TYPE_FONT = 9;
const int RESOURCE_TYPE_PREFAB = 10;
const int RESOURCE_TYPE_TECHNIQUE = 11;
const int RESOURCE_TYPE_PARTICLEEFFECT = 12;
const int RESOURCE_TYPE_UIELEMENT = 13;
const int RESOURCE_TYPE_UIELEMENTS = 14;
const int RESOURCE_TYPE_ANIMATION_SETTINGS = 15;
const int RESOURCE_TYPE_RENDERPATH = 16;
const int RESOURCE_TYPE_TEXTURE_ATLAS = 17;
const int RESOURCE_TYPE_2D_PARTICLE_EFFECT = 18;
const int RESOURCE_TYPE_TEXTURE_3D = 19;
const int RESOURCE_TYPE_CUBEMAP = 20;
const int RESOURCE_TYPE_PARTICLEEMITTER = 21;
const int RESOURCE_TYPE_2D_ANIMATION_SET = 22;
// any resource type > 0 is valid
const int NUMBER_OF_VALID_RESOURCE_TYPES = 22;
const StringHash XML_TYPE_SCENE(""scene"");
const StringHash XML_TYPE_NODE(""node"");
const StringHash XML_TYPE_MATERIAL(""material"");
const StringHash XML_TYPE_TECHNIQUE(""technique"");
const StringHash XML_TYPE_PARTICLEEFFECT(""particleeffect"");
const StringHash XML_TYPE_PARTICLEEMITTER(""particleemitter"");
const StringHash XML_TYPE_TEXTURE(""texture"");
const StringHash XML_TYPE_ELEMENT(""element"");
const StringHash XML_TYPE_ELEMENTS(""elements"");
const StringHash XML_TYPE_ANIMATION_SETTINGS(""animation"");
const StringHash XML_TYPE_RENDERPATH(""renderpath"");
const StringHash XML_TYPE_TEXTURE_ATLAS(""TextureAtlas"");
const StringHash XML_TYPE_2D_PARTICLE_EFFECT(""particleEmitterConfig"");
const StringHash XML_TYPE_TEXTURE_3D(""texture3d"");
const StringHash XML_TYPE_CUBEMAP(""cubemap"");
const StringHash XML_TYPE_SPRITER_DATA(""spriter_data"");
const StringHash JSON_TYPE_SCENE(""scene"");
const StringHash JSON_TYPE_NODE(""node"");
const StringHash JSON_TYPE_MATERIAL(""material"");
const StringHash JSON_TYPE_TECHNIQUE(""technique"");
const StringHash JSON_TYPE_PARTICLEEFFECT(""particleeffect"");
const StringHash JSON_TYPE_PARTICLEEMITTER(""particleemitter"");
const StringHash JSON_TYPE_TEXTURE(""texture"");
const StringHash JSON_TYPE_ELEMENT(""element"");
const StringHash JSON_TYPE_ELEMENTS(""elements"");
const StringHash JSON_TYPE_ANIMATION_SETTINGS(""animation"");
const StringHash JSON_TYPE_RENDERPATH(""renderpath"");
const StringHash JSON_TYPE_TEXTURE_ATLAS(""TextureAtlas"");
const StringHash JSON_TYPE_2D_PARTICLE_EFFECT(""particleEmitterConfig"");
const StringHash JSON_TYPE_TEXTURE_3D(""texture3d"");
const StringHash JSON_TYPE_CUBEMAP(""cubemap"");
const StringHash JSON_TYPE_SPRITER_DATA(""spriter_data"");
const StringHash BINARY_TYPE_SCENE(""USCN"");
const StringHash BINARY_TYPE_PACKAGE(""UPAK"");
const StringHash BINARY_TYPE_COMPRESSED_PACKAGE(""ULZ4"");
const StringHash BINARY_TYPE_ANGLESCRIPT(""ASBC"");
const StringHash BINARY_TYPE_MODEL(""UMDL"");
const StringHash BINARY_TYPE_SHADER(""USHD"");
const StringHash BINARY_TYPE_ANIMATION(""UANI"");
const StringHash EXTENSION_TYPE_TTF("".ttf"");
const StringHash EXTENSION_TYPE_OTF("".otf"");
const StringHash EXTENSION_TYPE_OGG("".ogg"");
const StringHash EXTENSION_TYPE_WAV("".wav"");
const StringHash EXTENSION_TYPE_DDS("".dds"");
const StringHash EXTENSION_TYPE_PNG("".png"");
const StringHash EXTENSION_TYPE_JPG("".jpg"");
const StringHash EXTENSION_TYPE_JPEG("".jpeg"");
const StringHash EXTENSION_TYPE_BMP("".bmp"");
const StringHash EXTENSION_TYPE_TGA("".tga"");
const StringHash EXTENSION_TYPE_KTX("".ktx"");
const StringHash EXTENSION_TYPE_PVR("".pvr"");
const StringHash EXTENSION_TYPE_OBJ("".obj"");
const StringHash EXTENSION_TYPE_FBX("".fbx"");
const StringHash EXTENSION_TYPE_COLLADA("".dae"");
const StringHash EXTENSION_TYPE_BLEND("".blend"");
const StringHash EXTENSION_TYPE_ANGELSCRIPT("".as"");
const StringHash EXTENSION_TYPE_LUASCRIPT("".lua"");
const StringHash EXTENSION_TYPE_HLSL("".hlsl"");
const StringHash EXTENSION_TYPE_GLSL("".glsl"");
const StringHash EXTENSION_TYPE_FRAGMENTSHADER("".frag"");
const StringHash EXTENSION_TYPE_VERTEXSHADER("".vert"");
const StringHash EXTENSION_TYPE_HTML("".html"");
const StringHash TEXT_VAR_FILE_ID(""browser_file_id"");
const StringHash TEXT_VAR_DIR_ID(""browser_dir_id"");
const StringHash TEXT_VAR_RESOURCE_TYPE(""resource_type"");
const StringHash TEXT_VAR_RESOURCE_DIR_ID(""resource_dir_id"");
const int BROWSER_FILE_SOURCE_RESOURCE_DIR = 1;
uint browserDirIndex = 1;
uint browserFileIndex = 1;
BrowserDir@ selectedBrowserDirectory;
BrowserFile@ selectedBrowserFile;
Text@ browserStatusMessage;
Text@ browserResultsMessage;
bool ignoreRefreshBrowserResults = false;
String resourceDirsCache;
void CreateResourceBrowser()
{
if (browserWindow !is null) return;
CreateResourceBrowserUI();
InitResourceBrowserPreview();
RebuildResourceDatabase();
}
void RebuildResourceDatabase()
{
if (browserWindow is null)
return;
String newResourceDirsCache = Join(cache.resourceDirs, ';');
ScanResourceDirectories();
if (newResourceDirsCache != resourceDirsCache)
{
resourceDirsCache = newResourceDirsCache;
PopulateResourceDirFilters();
}
PopulateBrowserDirectories();
PopulateResourceBrowserFilesByDirectory(rootDir);
}
void ScanResourceDirectories()
{
browserDirs.Clear();
browserFiles.Clear();
browserFilesToScan.Clear();
rootDir = BrowserDir("""");
browserDirs.Set("""", @rootDir);
// collect all of the items and sort them afterwards
for(uint i=0; i < cache.resourceDirs.length; ++i)
{
if (activeResourceDirFilters.Find(i) > -1)
continue;
ScanResourceDir(i);
}
}
// used to stop ui from blocking while determining file types
void DoResourceBrowserWork()
{
if (browserFilesToScan.length == 0)
return;
int counter = 0;
bool updateBrowserUI = false;
BrowserFile@ scanItem = browserFilesToScan[0];
while(counter < BROWSER_WORKER_ITEMS_PER_TICK)
{
scanItem.DetermainResourceType();
// next
browserFilesToScan.Erase(0);
if (browserFilesToScan.length > 0)
@scanItem = browserFilesToScan[0];
else
break;
counter++;
}
if (browserFilesToScan.length > 0)
browserStatusMessage.text = localization.Get(""Files left to scan: "" )+ browserFilesToScan.length;
else
browserStatusMessage.text = localization.Get(""Scan complete"");
}
void CreateResourceBrowserUI()
{
browserWindow = LoadEditorUI(""UI/EditorResourceBrowser.xml"");
browserDirList = browserWindow.GetChild(""DirectoryList"", true);
browserFileList = browserWindow.GetChild(""FileList"", true);
browserSearch = browserWindow.GetChild(""Search"", true);
browserStatusMessage = browserWindow.GetChild(""StatusMessage"", true);
browserResultsMessage = browserWindow.GetChild(""ResultsMessage"", true);
// browserWindow.visible = false;
browserWindow.opacity = uiMaxOpacity;
browserFilterWindow = LoadEditorUI(""UI/EditorResourceFilterWindow.xml"");
CreateResourceFilterUI();
HideResourceFilterWindow();
int height = Min(ui.root.height / 4, 300);
browserWindow.SetSize(900, height);
browserWindow.SetPosition(35, ui.root.height - height - 25);
CloseContextMenu();
ui.root.AddChild(browserWindow);
ui.root.AddChild(browserFilterWindow);
SubscribeToEvent(browserWindow.GetChild(""CloseButton"", true), ""Released"", ""HideResourceBrowserWindow"");
SubscribeToEvent(browserWindow.GetChild(""RescanButton"", true), ""Released"", ""HandleRescanResourceBrowserClick"");
SubscribeToEvent(browserWindow.GetChild(""FilterButton"", true), ""Released"", ""ToggleResourceFilterWindow"");
SubscribeToEvent(browserDirList, ""SelectionChanged"", ""HandleResourceBrowserDirListSelectionChange"");
SubscribeToEvent(browserSearch, ""TextChanged"", ""HandleResourceBrowserSearchTextChange"");
SubscribeToEvent(browserFileList, ""ItemClicked"", ""HandleBrowserFileClick"");
SubscribeToEvent(browserFileList, ""SelectionChanged"", ""HandleResourceBrowserFileListSelectionChange"");
SubscribeToEvent(cache, ""FileChanged"", ""HandleFileChanged"");
}
void CreateResourceFilterUI()
{
UIElement@ options = browserFilterWindow.GetChild(""TypeOptions"", true);
CheckBox@ toggleAllTypes = browserFilterWindow.GetChild(""ToggleAllTypes"", true);
CheckBox@ toggleAllResourceDirs = browserFilterWindow.GetChild(""ToggleAllResourceDirs"", true);
SubscribeToEvent(toggleAllTypes, ""Toggled"", ""HandleResourceTypeFilterToggleAllTypesToggled"");
SubscribeToEvent(toggleAllResourceDirs, ""Toggled"", ""HandleResourceDirFilterToggleAllTypesToggled"");
SubscribeToEvent(browserFilterWindow.GetChild(""CloseButton"", true), ""Released"", ""HideResourceFilterWindow"");
int columns = 2;
UIElement@ col1 = browserFilterWindow.GetChild(""TypeFilterColumn1"", true);
UIElement@ col2 = browserFilterWindow.GetChild(""TypeFilterColumn2"", true);
// use array to get sort of items
Array sorted;
for (int i=1; i <= NUMBER_OF_VALID_RESOURCE_TYPES; ++i)
sorted.Push(ResourceType(i, ResourceTypeName(i)));
// 2 unknown types are reserved for the top, the rest are alphabetized
sorted.Sort();
sorted.Insert(0, ResourceType(RESOURCE_TYPE_UNKNOWN, ResourceTypeName(RESOURCE_TYPE_UNKNOWN)) );
sorted.Insert(0, ResourceType(RESOURCE_TYPE_UNUSABLE, ResourceTypeName(RESOURCE_TYPE_UNUSABLE)) );
int halfColumns = Ceil( float(sorted.length) / float(columns) );
for (uint i = 0; i < sorted.length; ++i)
{
ResourceType@ type = sorted[i];
UIElement@ resourceTypeHolder = UIElement();
if (i < halfColumns)
col1.AddChild(resourceTypeHolder);
else
col2.AddChild(resourceTypeHolder);
resourceTypeHolder.layoutMode = LM_HORIZONTAL;
resourceTypeHolder.layoutSpacing = 4;
Text@ label = Text();
label.style = ""EditorAttributeText"";
label.text = type.name;
CheckBox@ checkbox = CheckBox();
checkbox.name = type.id;
checkbox.SetStyleAuto();
checkbox.vars[TEXT_VAR_RESOURCE_TYPE] = i;
checkbox.checked = true;
SubscribeToEvent(checkbox, ""Toggled"", ""HandleResourceTypeFilterToggled"");
resourceTypeHolder.AddChild(checkbox);
resourceTypeHolder.AddChild(label);
}
}
void CreateDirList(BrowserDir@ dir, UIElement@ parentUI = null)
{
Text@ dirText = Text();
browserDirList.InsertItem(browserDirList.numItems, dirText, parentUI);
dirText.style = ""FileSelectorListText"";
dirText.text = dir.resourceKey.empty ? localization.Get(""Root"") : dir.name;
dirText.name = dir.resourceKey;
dirText.vars[TEXT_VAR_DIR_ID] = dir.resourceKey;
// Sort directories alphetically
browserSearchSortMode = BROWSER_SORT_MODE_ALPHA;
dir.children.Sort();
for(uint i=0; i 0)
fileText.dragDropMode = DD_SOURCE;
{
Text@ text = Text();
fileText.AddChild(text);
text.style = ""FileSelectorListText"";
text.text = file.fullname;
text.name = file.resourceKey;
}
{
Text@ text = Text();
fileText.AddChild(text);
text.style = ""FileSelectorListText"";
text.text = file.ResourceTypeName();
}
if (file.resourceType == RESOURCE_TYPE_MATERIAL ||
file.resourceType == RESOURCE_TYPE_MODEL ||
file.resourceType == RESOURCE_TYPE_PARTICLEEFFECT ||
file.resourceType == RESOURCE_TYPE_PREFAB
)
{
SubscribeToEvent(fileText, ""DragBegin"", ""HandleBrowserFileDragBegin"");
SubscribeToEvent(fileText, ""DragEnd"", ""HandleBrowserFileDragEnd"");
}
}
void InitResourceBrowserPreview()
{
resourcePreviewScene = Scene(""PreviewScene"");
resourcePreviewScene.CreateComponent(""Octree"");
PhysicsWorld@ physicsWorld = resourcePreviewScene.CreateComponent(""PhysicsWorld"");
physicsWorld.enabled = false;
physicsWorld.gravity = Vector3(0.0, 0.0, 0.0);
Node@ zoneNode = resourcePreviewScene.CreateChild(""Zone"");
Zone@ zone = zoneNode.CreateComponent(""Zone"");
zone.boundingBox = BoundingBox(-1000, 1000);
zone.ambientColor = Color(0.15, 0.15, 0.15);
zone.fogColor = Color(0, 0, 0);
zone.fogStart = 10.0;
zone.fogEnd = 100.0;
resourcePreviewCameraNode = resourcePreviewScene.CreateChild(""PreviewCamera"");
resourcePreviewCameraNode.position = Vector3(0, 0, -1.5);
Camera@ camera = resourcePreviewCameraNode.CreateComponent(""Camera"");
camera.nearClip = 0.1f;
camera.farClip = 100.0f;
resourcePreviewLightNode = resourcePreviewScene.CreateChild(""PreviewLight"");
resourcePreviewLightNode.direction = Vector3(0.5, -0.5, 0.5);
resourcePreviewLight = resourcePreviewLightNode.CreateComponent(""Light"");
resourcePreviewLight.lightType = LIGHT_DIRECTIONAL;
resourcePreviewLight.specularIntensity = 0.5;
resourceBrowserPreview = browserWindow.GetChild(""ResourceBrowserPreview"", true);
resourceBrowserPreview.SetFixedHeight(200);
resourceBrowserPreview.SetFixedWidth(266);
resourceBrowserPreview.SetView(resourcePreviewScene, camera);
resourceBrowserPreview.autoUpdate = false;
resourcePreviewNode = resourcePreviewScene.CreateChild(""PreviewNodeContainer"");
SubscribeToEvent(resourceBrowserPreview, ""DragMove"", ""RotateResourceBrowserPreview"");
RefreshBrowserPreview();
}
// Opens a contextual menu based on what resource item was actioned
void HandleBrowserFileClick(StringHash eventType, VariantMap& eventData)
{
if (eventData[""Button""].GetInt() != MOUSEB_RIGHT)
return;
UIElement@ uiElement = eventData[""Item""].GetPtr();
BrowserFile@ file = GetBrowserFileFromUIElement(uiElement);
if (file is null)
return;
Array actions;
if (file.resourceType == RESOURCE_TYPE_MATERIAL)
{
actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file));
}
else if (file.resourceType == RESOURCE_TYPE_MODEL)
{
actions.Push(CreateBrowserFileActionMenu(""Instance Animated Model"", ""HandleBrowserInstantiateAnimatedModel"", file));
actions.Push(CreateBrowserFileActionMenu(""Instance Static Model"", ""HandleBrowserInstantiateStaticModel"", file));
}
else if (file.resourceType == RESOURCE_TYPE_PREFAB)
{
actions.Push(CreateBrowserFileActionMenu(""Instance Prefab"", ""HandleBrowserInstantiatePrefab"", file));
actions.Push(CreateBrowserFileActionMenu(""Instance in Spawner"", ""HandleBrowserInstantiateInSpawnEditor"", file));
}
else if (file.fileType == EXTENSION_TYPE_OBJ ||
file.fileType == EXTENSION_TYPE_COLLADA ||
file.fileType == EXTENSION_TYPE_FBX ||
file.fileType == EXTENSION_TYPE_BLEND)
{
actions.Push(CreateBrowserFileActionMenu(""Import Model"", ""HandleBrowserImportModel"", file));
actions.Push(CreateBrowserFileActionMenu(""Import Scene"", ""HandleBrowserImportScene"", file));
}
else if (file.resourceType == RESOURCE_TYPE_UIELEMENT)
{
actions.Push(CreateBrowserFileActionMenu(""Open UI Layout"", ""HandleBrowserOpenUILayout"", file));
}
else if (file.resourceType == RESOURCE_TYPE_SCENE)
{
actions.Push(CreateBrowserFileActionMenu(""Load Scene"", ""HandleBrowserLoadScene"", file));
}
else if (file.resourceType == RESOURCE_TYPE_SCRIPTFILE)
{
actions.Push(CreateBrowserFileActionMenu(""Execute Script"", ""HandleBrowserRunScript"", file));
}
else if (file.resourceType == RESOURCE_TYPE_PARTICLEEFFECT)
{
actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file));
}
actions.Push(CreateBrowserFileActionMenu(""Open"", ""HandleBrowserOpenResource"", file));
ActivateContextMenu(actions);
}
BrowserDir@ GetBrowserDir(String path)
{
BrowserDir@ browserDir;
browserDirs.Get(path, @browserDir);
return browserDir;
}
// Makes sure the entire directory tree exists and new dir is linked to parent
BrowserDir@ InitBrowserDir(String path)
{
BrowserDir@ browserDir;
if (browserDirs.Get(path, @browserDir))
return browserDir;
Array parts = path.Split('/');
Array finishedParts;
if (parts.length > 0)
{
BrowserDir@ parent = rootDir;
for( uint i = 0; i < parts.length; ++i )
{
finishedParts.Push(parts[i]);
String currentPath = Join(finishedParts, ""/"");
if (!browserDirs.Get(currentPath, @browserDir))
{
browserDir = BrowserDir(currentPath);
browserDirs.Set(currentPath, @browserDir);
parent.children.Push(browserDir);
}
@parent = browserDir;
}
return browserDir;
}
return null;
}
void ScanResourceDir(uint resourceDirIndex)
{
String resourceDir = cache.resourceDirs[resourceDirIndex];
ScanResourceDirFiles("""", resourceDirIndex);
Array dirs = fileSystem.ScanDir(resourceDir, ""*"", SCAN_DIRS, true);
for (uint i=0; i < dirs.length; ++i)
{
String path = dirs[i];
if (path.EndsWith("".""))
continue;
InitBrowserDir(path);
ScanResourceDirFiles(path, resourceDirIndex);
}
}
void ScanResourceDirFiles(String path, uint resourceDirIndex)
{
String fullPath = cache.resourceDirs[resourceDirIndex] + path;
if (!fileSystem.DirExists(fullPath))
return;
BrowserDir@ dir = GetBrowserDir(path);
if (dir is null)
return;
// get files in directory
Array dirFiles = fileSystem.ScanDir(fullPath, ""*.*"", SCAN_FILES, false);
// add new files
for (uint x=0; x < dirFiles.length; x++)
{
String filename = dirFiles[x];
BrowserFile@ browserFile = dir.AddFile(filename, resourceDirIndex, BROWSER_FILE_SOURCE_RESOURCE_DIR);
browserFiles.Push(browserFile);
browserFilesToScan.Push(browserFile);
}
}
bool ToggleResourceBrowserWindow()
{
if (browserWindow.visible == false)
ShowResourceBrowserWindow();
else
HideResourceBrowserWindow();
return true;
}
void ShowResourceBrowserWindow()
{
browserWindow.visible = true;
browserWindow.BringToFront();
ui.focusElement = browserSearch;
}
void HideResourceBrowserWindow()
{
browserWindow.visible = false;
}
void ToggleResourceFilterWindow()
{
if (browserFilterWindow.visible)
HideResourceFilterWindow();
else
ShowResourceFilterWindow();
}
void HideResourceFilterWindow()
{
browserFilterWindow.visible = false;
}
void ShowResourceFilterWindow()
{
int x = browserWindow.position.x + browserWindow.width - browserFilterWindow.width;
int y = browserWindow.position.y - browserFilterWindow.height - 1;
browserFilterWindow.position = IntVector2(x,y);
browserFilterWindow.visible = true;
browserFilterWindow.BringToFront();
}
void PopulateResourceDirFilters()
{
UIElement@ resourceDirs = browserFilterWindow.GetChild(""DirFilters"", true);
resourceDirs.RemoveAllChildren();
activeResourceDirFilters.Clear();
for (uint i=0; i < cache.resourceDirs.length; ++i)
{
UIElement@ resourceDirHolder = UIElement();
resourceDirs.AddChild(resourceDirHolder);
resourceDirHolder.layoutMode = LM_HORIZONTAL;
resourceDirHolder.layoutSpacing = 4;
resourceDirHolder.SetFixedHeight(16);
Text@ label = Text();
label.style = ""EditorAttributeText"";
label.text = cache.resourceDirs[i].Replaced(fileSystem.programDir, """");
CheckBox@ checkbox = CheckBox();
checkbox.name = i;
checkbox.SetStyleAuto();
checkbox.vars[TEXT_VAR_RESOURCE_DIR_ID] = i;
checkbox.checked = true;
SubscribeToEvent(checkbox, ""Toggled"", ""HandleResourceDirFilterToggled"");
resourceDirHolder.AddChild(checkbox);
resourceDirHolder.AddChild(label);
}
}
void PopulateBrowserDirectories()
{
browserDirList.RemoveAllItems();
CreateDirList(rootDir);
browserDirList.selection = 0;
}
void PopulateResourceBrowserFilesByDirectory(BrowserDir@ dir)
{
@selectedBrowserDirectory = dir;
browserFileList.RemoveAllItems();
if (dir is null) return;
Array files;
for(uint x=0; x < dir.files.length; x++)
{
BrowserFile@ file = dir.files[x];
if (activeResourceTypeFilters.Find(file.resourceType) == -1)
files.Push(file);
}
// Sort alphetically
browserSearchSortMode = BROWSER_SORT_MODE_ALPHA;
files.Sort();
PopulateResourceBrowserResults(files);
browserResultsMessage.text = localization.Get(""Showing files: "") + files.length;
}
void PopulateResourceBrowserBySearch()
{
String query = browserSearch.text;
Array scores;
Array scored;
Array filtered;
{
BrowserFile@ file;
for(uint x=0; x < browserFiles.length; x++)
{
@file = browserFiles[x];
file.sortScore = -1;
if (activeResourceTypeFilters.Find(file.resourceType) > -1)
continue;
if (activeResourceDirFilters.Find(file.resourceSourceIndex) > -1)
continue;
int find = file.fullname.Find(query, 0, false);
if (find > -1)
{
int fudge = query.length - file.fullname.length;
int score = find * int(Abs(fudge*2)) + int(Abs(fudge));
file.sortScore = score;
scored.Push(file);
scores.Push(score);
}
}
}
// cut this down for a faster sort
if (scored.length > BROWSER_SEARCH_LIMIT)
{
scores.Sort();
int scoreThreshold = scores[BROWSER_SEARCH_LIMIT];
BrowserFile@ file;
for(uint x=0;x@ files)
{
browserFileList.RemoveAllItems();
for(uint i=0; i < files.length; ++i)
CreateFileList(files[i]);
}
void RefreshBrowserResults()
{
if (browserSearch.text.empty)
{
browserDirList.visible = true;
PopulateResourceBrowserFilesByDirectory(selectedBrowserDirectory);
}
else
{
browserDirList.visible = false;
PopulateResourceBrowserBySearch();
}
}
void HandleResourceTypeFilterToggleAllTypesToggled(StringHash eventType, VariantMap& eventData)
{
CheckBox@ checkbox = eventData[""Element""].GetPtr();
UIElement@ filterHolder = browserFilterWindow.GetChild(""TypeFilters"", true);
Array children = filterHolder.GetChildren(true);
ignoreRefreshBrowserResults = true;
for(uint i=0; i < children.length; ++i)
{
CheckBox@ filter = children[i];
if (filter !is null)
filter.checked = checkbox.checked;
}
ignoreRefreshBrowserResults = false;
RefreshBrowserResults();
}
void HandleResourceTypeFilterToggled(StringHash eventType, VariantMap& eventData)
{
CheckBox@ checkbox = eventData[""Element""].GetPtr();
if (!checkbox.vars.Contains(TEXT_VAR_RESOURCE_TYPE))
return;
int resourceType = checkbox.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt();
int find = activeResourceTypeFilters.Find(resourceType);
if (checkbox.checked && find != -1)
activeResourceTypeFilters.Erase(find);
else if (!checkbox.checked && find == -1)
activeResourceTypeFilters.Push(resourceType);
if (ignoreRefreshBrowserResults == false)
RefreshBrowserResults();
}
void HandleResourceDirFilterToggleAllTypesToggled(StringHash eventType, VariantMap& eventData)
{
CheckBox@ checkbox = eventData[""Element""].GetPtr();
UIElement@ filterHolder = browserFilterWindow.GetChild(""DirFilters"", true);
Array children = filterHolder.GetChildren(true);
ignoreRefreshBrowserResults = true;
for(uint i=0; i < children.length; ++i)
{
CheckBox@ filter = children[i];
if (filter !is null)
filter.checked = checkbox.checked;
}
ignoreRefreshBrowserResults = false;
RebuildResourceDatabase();
}
void HandleResourceDirFilterToggled(StringHash eventType, VariantMap& eventData)
{
CheckBox@ checkbox = eventData[""Element""].GetPtr();
if (!checkbox.vars.Contains(TEXT_VAR_RESOURCE_DIR_ID))
return;
int resourceDir = checkbox.GetVar(TEXT_VAR_RESOURCE_DIR_ID).GetInt();
int find = activeResourceDirFilters.Find(resourceDir);
if (checkbox.checked && find != -1)
activeResourceDirFilters.Erase(find);
else if (!checkbox.checked && find == -1)
activeResourceDirFilters.Push(resourceDir);
if (ignoreRefreshBrowserResults == false)
RebuildResourceDatabase();
}
void HandleRescanResourceBrowserClick(StringHash eventType, VariantMap& eventData)
{
RebuildResourceDatabase();
}
void HandleResourceBrowserDirListSelectionChange(StringHash eventType, VariantMap& eventData)
{
if (browserDirList.selection == M_MAX_UNSIGNED)
return;
UIElement@ uiElement = browserDirList.GetItems()[browserDirList.selection];
BrowserDir@ dir = GetBrowserDir(uiElement.vars[TEXT_VAR_DIR_ID].GetString());
if (dir is null)
return;
PopulateResourceBrowserFilesByDirectory(dir);
}
void HandleResourceBrowserFileListSelectionChange(StringHash eventType, VariantMap& eventData)
{
if (browserFileList.selection == M_MAX_UNSIGNED)
return;
UIElement@ uiElement = browserFileList.GetItems()[browserFileList.selection];
BrowserFile@ file = GetBrowserFileFromUIElement(uiElement);
if (file is null)
return;
if (resourcePreviewNode !is null)
resourcePreviewNode.Remove();
resourcePreviewNode = resourcePreviewScene.CreateChild(""PreviewNodeContainer"");
CreateResourcePreview(file.GetFullPath(), resourcePreviewNode);
if (resourcePreviewNode !is null)
{
Array boxes;
Array staticModels = resourcePreviewNode.GetComponents(""StaticModel"", true);
Array animatedModels = resourcePreviewNode.GetComponents(""AnimatedModel"", true);
for (uint i = 0; i < staticModels.length; ++i)
boxes.Push(cast(staticModels[i]).worldBoundingBox);
for (uint i = 0; i < animatedModels.length; ++i)
boxes.Push(cast(animatedModels[i]).worldBoundingBox);
if (boxes.length > 0)
{
Vector3 camPosition = Vector3(0.0, 0.0, -1.2);
BoundingBox biggestBox = boxes[0];
for (uint i = 1; i < boxes.length; ++i)
{
if (boxes[i].size.length > biggestBox.size.length)
biggestBox = boxes[i];
}
resourcePreviewCameraNode.position = biggestBox.center + camPosition * biggestBox.size.length;
}
resourcePreviewScene.AddChild(resourcePreviewNode);
RefreshBrowserPreview();
}
}
void HandleResourceBrowserSearchTextChange(StringHash eventType, VariantMap& eventData)
{
RefreshBrowserResults();
}
BrowserFile@ GetBrowserFileFromId(uint id)
{
if (id == 0)
return null;
BrowserFile@ file;
for(uint i=0; i(GetDrawableAtMousePostion());
if (model !is null)
{
AssignMaterial(model, browserDragFile.resourceKey);
}
}
browserDragFile = null;
browserDragComponent = null;
browserDragNode = null;
}
void HandleFileChanged(StringHash eventType, VariantMap& eventData)
{
String filename = eventData[""FileName""].GetString();
BrowserFile@ file = GetBrowserFileFromPath(filename);
if (file is null)
{
// TODO: new file logic when watchers are supported
return;
}
else
{
file.FileChanged();
}
}
Menu@ CreateBrowserFileActionMenu(String text, String handler, BrowserFile@ browserFile = null)
{
Menu@ menu = CreateContextMenuItem(text, handler);
if (browserFile !is null)
menu.vars[TEXT_VAR_FILE_ID] = browserFile.id;
return menu;
}
int GetResourceType(String path)
{
StringHash fileType;
return GetResourceType(path, fileType);
}
int GetResourceType(String path, StringHash &out fileType, bool useCache = false)
{
if (GetExtensionType(path, fileType) || GetBinaryType(path, fileType, useCache) || GetXmlType(path, fileType, useCache))
return GetResourceType(fileType);
return RESOURCE_TYPE_UNKNOWN;
}
int GetResourceType(StringHash fileType)
{
// binary fileTypes
if (fileType == BINARY_TYPE_SCENE)
return RESOURCE_TYPE_SCENE;
else if (fileType == BINARY_TYPE_PACKAGE)
return RESOURCE_TYPE_UNUSABLE;
else if (fileType == BINARY_TYPE_COMPRESSED_PACKAGE)
return RESOURCE_TYPE_UNUSABLE;
else if (fileType == BINARY_TYPE_ANGLESCRIPT)
return RESOURCE_TYPE_SCRIPTFILE;
else if (fileType == BINARY_TYPE_MODEL)
return RESOURCE_TYPE_MODEL;
else if (fileType == BINARY_TYPE_SHADER)
return RESOURCE_TYPE_UNUSABLE;
else if (fileType == BINARY_TYPE_ANIMATION)
return RESOURCE_TYPE_ANIMATION;
// xml fileTypes
else if (fileType == XML_TYPE_SCENE)
return RESOURCE_TYPE_SCENE;
else if (fileType == XML_TYPE_NODE)
return RESOURCE_TYPE_PREFAB;
else if(fileType == XML_TYPE_MATERIAL)
return RESOURCE_TYPE_MATERIAL;
else if(fileType == XML_TYPE_TECHNIQUE)
return RESOURCE_TYPE_TECHNIQUE;
else if(fileType == XML_TYPE_PARTICLEEFFECT)
return RESOURCE_TYPE_PARTICLEEFFECT;
else if(fileType == XML_TYPE_PARTICLEEMITTER)
return RESOURCE_TYPE_PARTICLEEMITTER;
else if(fileType == XML_TYPE_TEXTURE)
return RESOURCE_TYPE_TEXTURE;
else if(fileType == XML_TYPE_ELEMENT)
return RESOURCE_TYPE_UIELEMENT;
else if(fileType == XML_TYPE_ELEMENTS)
return RESOURCE_TYPE_UIELEMENTS;
else if (fileType == XML_TYPE_ANIMATION_SETTINGS)
return RESOURCE_TYPE_ANIMATION_SETTINGS;
else if (fileType == XML_TYPE_RENDERPATH)
return RESOURCE_TYPE_RENDERPATH;
else if (fileType == XML_TYPE_TEXTURE_ATLAS)
return RESOURCE_TYPE_TEXTURE_ATLAS;
else if (fileType == XML_TYPE_2D_PARTICLE_EFFECT)
return RESOURCE_TYPE_2D_PARTICLE_EFFECT;
else if (fileType == XML_TYPE_TEXTURE_3D)
return RESOURCE_TYPE_TEXTURE_3D;
else if (fileType == XML_TYPE_CUBEMAP)
return RESOURCE_TYPE_CUBEMAP;
else if (fileType == XML_TYPE_SPRITER_DATA)
return RESOURCE_TYPE_2D_ANIMATION_SET;
// JSON fileTypes
else if (fileType == JSON_TYPE_SCENE)
return RESOURCE_TYPE_SCENE;
else if (fileType == JSON_TYPE_NODE)
return RESOURCE_TYPE_PREFAB;
else if(fileType == JSON_TYPE_MATERIAL)
return RESOURCE_TYPE_MATERIAL;
else if(fileType == JSON_TYPE_TECHNIQUE)
return RESOURCE_TYPE_TECHNIQUE;
else if(fileType == JSON_TYPE_PARTICLEEFFECT)
return RESOURCE_TYPE_PARTICLEEFFECT;
else if(fileType == JSON_TYPE_PARTICLEEMITTER)
return RESOURCE_TYPE_PARTICLEEMITTER;
else if(fileType == JSON_TYPE_TEXTURE)
return RESOURCE_TYPE_TEXTURE;
else if(fileType == JSON_TYPE_ELEMENT)
return RESOURCE_TYPE_UIELEMENT;
else if(fileType == JSON_TYPE_ELEMENTS)
return RESOURCE_TYPE_UIELEMENTS;
else if (fileType == JSON_TYPE_ANIMATION_SETTINGS)
return RESOURCE_TYPE_ANIMATION_SETTINGS;
else if (fileType == JSON_TYPE_RENDERPATH)
return RESOURCE_TYPE_RENDERPATH;
else if (fileType == JSON_TYPE_TEXTURE_ATLAS)
return RESOURCE_TYPE_TEXTURE_ATLAS;
else if (fileType == JSON_TYPE_2D_PARTICLE_EFFECT)
return RESOURCE_TYPE_2D_PARTICLE_EFFECT;
else if (fileType == JSON_TYPE_TEXTURE_3D)
return RESOURCE_TYPE_TEXTURE_3D;
else if (fileType == JSON_TYPE_CUBEMAP)
return RESOURCE_TYPE_CUBEMAP;
else if (fileType == JSON_TYPE_SPRITER_DATA)
return RESOURCE_TYPE_2D_ANIMATION_SET;
// extension fileTypes
else if (fileType == EXTENSION_TYPE_TTF)
return RESOURCE_TYPE_FONT;
else if (fileType == EXTENSION_TYPE_OTF)
return RESOURCE_TYPE_FONT;
else if (fileType == EXTENSION_TYPE_OGG)
return RESOURCE_TYPE_SOUND;
else if(fileType == EXTENSION_TYPE_WAV)
return RESOURCE_TYPE_SOUND;
else if(fileType == EXTENSION_TYPE_DDS)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_PNG)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_JPG)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_JPEG)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_BMP)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_TGA)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_KTX)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_PVR)
return RESOURCE_TYPE_IMAGE;
else if(fileType == EXTENSION_TYPE_OBJ)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_FBX)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_COLLADA)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_BLEND)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_ANGELSCRIPT)
return RESOURCE_TYPE_SCRIPTFILE;
else if(fileType == EXTENSION_TYPE_LUASCRIPT)
return RESOURCE_TYPE_SCRIPTFILE;
else if(fileType == EXTENSION_TYPE_HLSL)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_GLSL)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_FRAGMENTSHADER)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_VERTEXSHADER)
return RESOURCE_TYPE_UNUSABLE;
else if(fileType == EXTENSION_TYPE_HTML)
return RESOURCE_TYPE_UNUSABLE;
return RESOURCE_TYPE_UNKNOWN;
}
bool GetExtensionType(String path, StringHash &out fileType)
{
StringHash type = StringHash(GetExtension(path));
if (type == EXTENSION_TYPE_TTF)
fileType = EXTENSION_TYPE_TTF;
else if (type == EXTENSION_TYPE_OTF)
fileType = EXTENSION_TYPE_OTF;
else if (type == EXTENSION_TYPE_OGG)
fileType = EXTENSION_TYPE_OGG;
else if(type == EXTENSION_TYPE_WAV)
fileType = EXTENSION_TYPE_WAV;
else if(type == EXTENSION_TYPE_DDS)
fileType = EXTENSION_TYPE_DDS;
else if(type == EXTENSION_TYPE_PNG)
fileType = EXTENSION_TYPE_PNG;
else if(type == EXTENSION_TYPE_JPG)
fileType = EXTENSION_TYPE_JPG;
else if(type == EXTENSION_TYPE_JPEG)
fileType = EXTENSION_TYPE_JPEG;
else if(type == EXTENSION_TYPE_BMP)
fileType = EXTENSION_TYPE_BMP;
else if(type == EXTENSION_TYPE_TGA)
fileType = EXTENSION_TYPE_TGA;
else if(type == EXTENSION_TYPE_KTX)
fileType = EXTENSION_TYPE_KTX;
else if(type == EXTENSION_TYPE_PVR)
fileType = EXTENSION_TYPE_PVR;
else if(type == EXTENSION_TYPE_OBJ)
fileType = EXTENSION_TYPE_OBJ;
else if(type == EXTENSION_TYPE_FBX)
fileType = EXTENSION_TYPE_FBX;
else if(type == EXTENSION_TYPE_COLLADA)
fileType = EXTENSION_TYPE_COLLADA;
else if(type == EXTENSION_TYPE_BLEND)
fileType = EXTENSION_TYPE_BLEND;
else if(type == EXTENSION_TYPE_ANGELSCRIPT)
fileType = EXTENSION_TYPE_ANGELSCRIPT;
else if(type == EXTENSION_TYPE_LUASCRIPT)
fileType = EXTENSION_TYPE_LUASCRIPT;
else if(type == EXTENSION_TYPE_HLSL)
fileType = EXTENSION_TYPE_HLSL;
else if(type == EXTENSION_TYPE_GLSL)
fileType = EXTENSION_TYPE_GLSL;
else if(type == EXTENSION_TYPE_FRAGMENTSHADER)
fileType = EXTENSION_TYPE_FRAGMENTSHADER;
else if(type == EXTENSION_TYPE_VERTEXSHADER)
fileType = EXTENSION_TYPE_VERTEXSHADER;
else if(type == EXTENSION_TYPE_HTML)
fileType = EXTENSION_TYPE_HTML;
else
return false;
return true;
}
bool GetBinaryType(String path, StringHash &out fileType, bool useCache = false)
{
StringHash type;
if (useCache)
{
File@ file = cache.GetFile(path);
if (file is null)
return false;
if (file.size == 0)
return false;
type = StringHash(file.ReadFileID());
}
else
{
File@ file = File();
if (!file.Open(path))
return false;
if (file.size == 0)
return false;
type = StringHash(file.ReadFileID());
}
if (type == BINARY_TYPE_SCENE)
fileType = BINARY_TYPE_SCENE;
else if (type == BINARY_TYPE_PACKAGE)
fileType = BINARY_TYPE_PACKAGE;
else if (type == BINARY_TYPE_COMPRESSED_PACKAGE)
fileType = BINARY_TYPE_COMPRESSED_PACKAGE;
else if (type == BINARY_TYPE_ANGLESCRIPT)
fileType = BINARY_TYPE_ANGLESCRIPT;
else if (type == BINARY_TYPE_MODEL)
fileType = BINARY_TYPE_MODEL;
else if (type == BINARY_TYPE_SHADER)
fileType = BINARY_TYPE_SHADER;
else if (type == BINARY_TYPE_ANIMATION)
fileType = BINARY_TYPE_ANIMATION;
else
return false;
return true;
}
bool GetXmlType(String path, StringHash &out fileType, bool useCache = false)
{
String extension = GetExtension(path);
if (extension == "".txt"" || extension == "".json"" || extension == "".icns"" || extension == "".atlas"")
return false;
String name;
if (useCache)
{
XMLFile@ xml = cache.GetResource(""XMLFile"", path);
if (xml is null)
return false;
name = xml.root.name;
}
else
{
File@ file = File();
if (!file.Open(path))
return false;
if (file.size == 0)
return false;
XMLFile@ xml = XMLFile();
if (xml.Load(file))
name = xml.root.name;
else
return false;
}
bool found = false;
if (!name.empty)
{
found = true;
StringHash type = StringHash(name);
if (type == XML_TYPE_SCENE)
fileType = XML_TYPE_SCENE;
else if (type == XML_TYPE_NODE)
fileType = XML_TYPE_NODE;
else if(type == XML_TYPE_MATERIAL)
fileType = XML_TYPE_MATERIAL;
else if(type == XML_TYPE_TECHNIQUE)
fileType = XML_TYPE_TECHNIQUE;
else if(type == XML_TYPE_PARTICLEEFFECT)
fileType = XML_TYPE_PARTICLEEFFECT;
else if(type == XML_TYPE_PARTICLEEMITTER)
fileType = XML_TYPE_PARTICLEEMITTER;
else if(type == XML_TYPE_TEXTURE)
fileType = XML_TYPE_TEXTURE;
else if(type == XML_TYPE_ELEMENT)
fileType = XML_TYPE_ELEMENT;
else if(type == XML_TYPE_ELEMENTS)
fileType = XML_TYPE_ELEMENTS;
else if (type == XML_TYPE_ANIMATION_SETTINGS)
fileType = XML_TYPE_ANIMATION_SETTINGS;
else if (type == XML_TYPE_RENDERPATH)
fileType = XML_TYPE_RENDERPATH;
else if (type == XML_TYPE_TEXTURE_ATLAS)
fileType = XML_TYPE_TEXTURE_ATLAS;
else if (type == XML_TYPE_2D_PARTICLE_EFFECT)
fileType = XML_TYPE_2D_PARTICLE_EFFECT;
else if (type == XML_TYPE_TEXTURE_3D)
fileType = XML_TYPE_TEXTURE_3D;
else if (type == XML_TYPE_CUBEMAP)
fileType = XML_TYPE_CUBEMAP;
else if (type == XML_TYPE_SPRITER_DATA)
fileType = XML_TYPE_SPRITER_DATA;
else
found = false;
}
return found;
}
String ResourceTypeName(int resourceType)
{
if (resourceType == RESOURCE_TYPE_UNUSABLE)
return ""Unusable"";
else if (resourceType == RESOURCE_TYPE_UNKNOWN)
return ""Unknown"";
else if (resourceType == RESOURCE_TYPE_NOTSET)
return ""Uninitialized"";
else if (resourceType == RESOURCE_TYPE_SCENE)
return ""Scene"";
else if (resourceType == RESOURCE_TYPE_SCRIPTFILE)
return ""Script File"";
else if (resourceType == RESOURCE_TYPE_MODEL)
return ""Model"";
else if (resourceType == RESOURCE_TYPE_MATERIAL)
return ""Material"";
else if (resourceType == RESOURCE_TYPE_ANIMATION)
return ""Animation"";
else if (resourceType == RESOURCE_TYPE_IMAGE)
return ""Image"";
else if (resourceType == RESOURCE_TYPE_SOUND)
return ""Sound"";
else if (resourceType == RESOURCE_TYPE_TEXTURE)
return ""Texture"";
else if (resourceType == RESOURCE_TYPE_FONT)
return ""Font"";
else if (resourceType == RESOURCE_TYPE_PREFAB)
return ""Prefab"";
else if (resourceType == RESOURCE_TYPE_TECHNIQUE)
return ""Render Technique"";
else if (resourceType == RESOURCE_TYPE_PARTICLEEFFECT)
return ""Particle Effect"";
else if (resourceType == RESOURCE_TYPE_PARTICLEEMITTER)
return ""Particle Emitter"";
else if (resourceType == RESOURCE_TYPE_UIELEMENT)
return ""UI Element"";
else if (resourceType == RESOURCE_TYPE_UIELEMENTS)
return ""UI Elements"";
else if (resourceType == RESOURCE_TYPE_ANIMATION_SETTINGS)
return ""Animation Settings"";
else if (resourceType == RESOURCE_TYPE_RENDERPATH)
return ""Render Path"";
else if (resourceType == RESOURCE_TYPE_TEXTURE_ATLAS)
return ""Texture Atlas"";
else if (resourceType == RESOURCE_TYPE_2D_PARTICLE_EFFECT)
return ""2D Particle Effect"";
else if (resourceType == RESOURCE_TYPE_TEXTURE_3D)
return ""Texture 3D"";
else if (resourceType == RESOURCE_TYPE_CUBEMAP)
return ""Cubemap"";
else if (resourceType == RESOURCE_TYPE_2D_ANIMATION_SET)
return ""2D Animation Set"";
else
return """";
}
class BrowserDir
{
uint id;
String resourceKey;
String name;
Array children;
Array files;
BrowserDir(String path_)
{
resourceKey = path_;
String parent = GetParentPath(path_);
name = path_;
name.Replace(parent, """");
id = browserDirIndex++;
}
int opCmp(BrowserDir@ b)
{
return name.opCmp(b.name);
}
BrowserFile@ AddFile(String name, uint resourceSourceIndex, uint sourceType)
{
String path = resourceKey + ""/"" + name;
BrowserFile@ file = BrowserFile(path, resourceSourceIndex, sourceType);
files.Push(file);
return file;
}
}
class BrowserFile
{
uint id;
uint resourceSourceIndex;
String resourceKey;
String name;
String fullname;
String extension;
StringHash fileType;
int resourceType = 0;
int sourceType = 0;
int sortScore = 0;
WeakHandle browserFileListRow;
BrowserFile(String path_, uint resourceSourceIndex_, int sourceType_)
{
sourceType = sourceType_;
resourceSourceIndex = resourceSourceIndex_;
resourceKey = path_;
name = GetFileName(path_);
extension = GetExtension(path_);
fullname = GetFileNameAndExtension(path_);
id = browserFileIndex++;
}
int opCmp(BrowserFile@ b)
{
if (browserSearchSortMode == 1)
return fullname.opCmp(b.fullname);
else
return sortScore - b.sortScore;
}
String GetResourceSource()
{
if (sourceType == BROWSER_FILE_SOURCE_RESOURCE_DIR)
return cache.resourceDirs[resourceSourceIndex];
else
return ""Unknown"";
}
String GetFullPath()
{
return String(cache.resourceDirs[resourceSourceIndex] + resourceKey);
}
String GetPath()
{
return resourceKey;
}
void DetermainResourceType()
{
resourceType = GetResourceType(GetFullPath(), fileType, false);
Text@ browserFileListRow_ = browserFileListRow.Get();
if (browserFileListRow_ !is null)
{
InitializeBrowserFileListRow(browserFileListRow_, this);
}
}
String ResourceTypeName()
{
return ::ResourceTypeName(resourceType);
}
void FileChanged()
{
if (!fileSystem.FileExists(GetFullPath()))
{
}
else
{
}
}
}
void CreateResourcePreview(String path, Node@ previewNode)
{
resourceBrowserPreview.autoUpdate = false;
int resourceType = GetResourceType(path);
if (resourceType > 0)
{
File file;
file.Open(path);
if (resourceType == RESOURCE_TYPE_MODEL)
{
Model@ model = Model();
if (model.Load(file))
{
StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel"");
staticModel.model = model;
return;
}
}
else if (resourceType == RESOURCE_TYPE_MATERIAL)
{
Material@ material = Material();
if (material.Load(file))
{
StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel"");
staticModel.model = cache.GetResource(""Model"", ""Models/Sphere.mdl"");
staticModel.material = material;
return;
}
}
else if (resourceType == RESOURCE_TYPE_IMAGE)
{
Image@ image = Image();
if (image.Load(file))
{
StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel"");
staticModel.model = cache.GetResource(""Model"", ""Models/Editor/ImagePlane.mdl"");
Material@ material = cache.GetResource(""Material"", ""Materials/Editor/TexturedUnlit.xml"");
Texture2D@ texture = Texture2D();
texture.SetData(@image, true);
material.textures[0] = texture;
staticModel.material = material;
return;
}
}
else if (resourceType == RESOURCE_TYPE_PREFAB)
{
if (GetExtension(path) == "".xml"")
{
XMLFile xmlFile;
if(xmlFile.Load(file))
if(previewNode.LoadXML(xmlFile.root, true) && (previewNode.GetComponents(""StaticModel"", true).length > 0 || previewNode.GetComponents(""AnimatedModel"", true).length > 0))
{
return;
}
}
else if(previewNode.Load(file, true) && (previewNode.GetComponents(""StaticModel"", true).length > 0 || previewNode.GetComponents(""AnimatedModel"", true).length > 0))
return;
previewNode.RemoveAllChildren();
previewNode.RemoveAllComponents();
}
else if (resourceType == RESOURCE_TYPE_PARTICLEEFFECT)
{
ParticleEffect@ particleEffect = ParticleEffect();
if (particleEffect.Load(file))
{
ParticleEmitter@ particleEmitter = previewNode.CreateComponent(""ParticleEmitter"");
particleEmitter.effect = particleEffect;
particleEffect.activeTime = 0.0;
particleEmitter.Reset();
resourceBrowserPreview.autoUpdate = true;
return;
}
}
}
StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel"");
staticModel.model = cache.GetResource(""Model"", ""Models/Editor/ImagePlane.mdl"");
Material@ material = cache.GetResource(""Material"", ""Materials/Editor/TexturedUnlit.xml"");
Texture2D@ texture = Texture2D();
Image@ noPreviewImage = cache.GetResource(""Image"", ""Textures/Editor/NoPreviewAvailable.png"");
texture.SetData(noPreviewImage, false);
material.textures[0] = texture;
staticModel.material = material;
return;
}
void RotateResourceBrowserPreview(StringHash eventType, VariantMap& eventData)
{
int elemX = eventData[""ElementX""].GetInt();
int elemY = eventData[""ElementY""].GetInt();
if (resourceBrowserPreview.height > 0 && resourceBrowserPreview.width > 0)
{
float yaw = ((resourceBrowserPreview.height / 2) - elemY) * (90.0 / resourceBrowserPreview.height);
float pitch = ((resourceBrowserPreview.width / 2) - elemX) * (90.0 / resourceBrowserPreview.width);
resourcePreviewNode.rotation = resourcePreviewNode.rotation.Slerp(Quaternion(yaw, pitch, 0), 0.1);
RefreshBrowserPreview();
}
}
void RefreshBrowserPreview()
{
resourceBrowserPreview.QueueUpdate();
}
class ResourceType
{
int id;
String name;
ResourceType(int id_, String name_)
{
id = id_;
name = name_;
}
int opCmp(ResourceType@ b)
{
return name.opCmp(b.name);
}
}
",12481,False,2446.249961562693,median
"= v1.ImageStream
{product-author}
{product-version}
:data-uri:
:icons:
:toc: macro
:toc-title:
:toclevels: 2
toc::[]
== Description
[%hardbreaks]
ImageStream stores a mapping of tags to images, metadata overrides that are applied when images are tagged in a stream, and an optional reference to a Docker image repository on a registry.
== Object Schema
Expand or mouse-over a field for more information about it.
++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
initializers:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
dockerImageRepository:
lookupPolicy:
local:
tags:
- annotations:
- [string]:
from:
apiVersion:
fieldPath:
kind:
name:
namespace:
resourceVersion:
uid:
generation:
importPolicy:
insecure:
scheduled:
name:
reference:
referencePolicy:
type:
status:
dockerImageRepository:
publicDockerImageRepository:
tags:
- conditions:
- - generation:
lastTransitionTime:
message:
reason:
status:
type:
items:
- created:
dockerImageReference:
generation:
image:
tag:
++++
== Operations
[[Post-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]]
=== Create a ImageStream in a namespace
Create an ImageStream
==== HTTP request
----
POST /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X POST \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams <<'EOF'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.ImageStream
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|201 Created|v1.ImageStream
|202 Accepted|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]]
=== Get a ImageStream in a namespace
Read the specified ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
|export|Should this value be exported. Export strips fields that a user can not specify.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-apis-image.openshift.io-v1-imagestreams]]
=== Get all ImageStreams
List or watch objects of kind ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams
----
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStreamList
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]]
=== Get all ImageStreams in a namespace
List or watch objects of kind ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStreamList
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams-name]]
=== Watch a ImageStream in a namespace
Watch changes to an object of kind ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-apis-image.openshift.io-v1-watch-imagestreams]]
=== Watch all ImageStreams
Watch individual changes to a list of ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/watch/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/watch/imagestreams
----
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams]]
=== Watch all ImageStreams in a namespace
Watch individual changes to a list of ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.WatchEvent
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
* application/json;stream=watch
* application/vnd.kubernetes.protobuf;stream=watch
[[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]]
=== Update a ImageStream in a namespace
Replace the specified ImageStream
==== HTTP request
----
PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.ImageStream
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|201 Created|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]]
=== Patch a ImageStream in a namespace
Partially update the specified ImageStream
==== HTTP request
----
PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json-patch+json'
{
...
}
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json-patch+json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF'
{
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Patch
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* application/json-patch+json
* application/merge-patch+json
* application/strategic-merge-patch+json
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]]
=== Delete a ImageStream in a namespace
Delete an ImageStream
==== HTTP request
----
DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
...
}
----
==== Curl request
----
$ curl -k \\
-X DELETE \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF'
{
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.DeleteOptions
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
|orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
|propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Status
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]]
=== Delete all ImageStreams in a namespace
Delete collection of ImageStream
==== HTTP request
----
DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-X DELETE \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.Status
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-layers]]
=== Get layers of a ImageStream in a namespace
Read layers of the specified ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/layers HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/layers
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStreamLayers
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStreamLayers
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-secrets]]
=== Get secrets of a ImageStream in a namespace
Read secrets of the specified ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the SecretList
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
|fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything.
|includeUninitialized|If true, partially initialized resources are included in the response.
|labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything.
|limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
|pretty|If 'true', then the output is pretty printed.
|resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
|timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
|watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.SecretList
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]]
=== Get status of a ImageStream in a namespace
Read status of the specified ImageStream
==== HTTP request
----
GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
----
==== Curl request
----
$ curl -k \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status
----
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]]
=== Update status of a ImageStream in a namespace
Replace status of the specified ImageStream
==== HTTP request
----
PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
----
==== Curl request
----
$ curl -k \\
-X PUT \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF'
{
""kind"": ""ImageStream"",
""apiVersion"": ""image.openshift.io/v1"",
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.ImageStream
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|201 Created|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* \\*/*
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
[[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]]
=== Patch status of a ImageStream in a namespace
Partially update status of the specified ImageStream
==== HTTP request
----
PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1
Authorization: Bearer $TOKEN
Accept: application/json
Connection: close
Content-Type: application/json-patch+json'
{
...
}
----
==== Curl request
----
$ curl -k \\
-X PATCH \\
-d @- \\
-H ""Authorization: Bearer $TOKEN"" \\
-H 'Accept: application/json' \\
-H 'Content-Type: application/json-patch+json' \\
https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF'
{
...
}
EOF
----
==== HTTP body
[cols=""1,5"", options=""header""]
|===
|Parameter|Schema
|body|v1.Patch
|===
==== Path parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|name|name of the ImageStream
|namespace|object name and auth scope, such as for teams and projects
|===
==== Query parameters
[cols=""1,5"", options=""header""]
|===
|Parameter|Description
|pretty|If 'true', then the output is pretty printed.
|===
==== Responses
[cols=""1,5"", options=""header""]
|===
|HTTP Code|Schema
|200 OK|v1.ImageStream
|401 Unauthorized|
|===
==== Consumes
* application/json-patch+json
* application/merge-patch+json
* application/strategic-merge-patch+json
==== Produces
* application/json
* application/yaml
* application/vnd.kubernetes.protobuf
",16252,True,3042.6257965008767,median
"////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the ""License""); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an ""AS IS"" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.containers
{
/*
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import mx.containers.dividedBoxClasses.BoxDivider;
import mx.core.EdgeMetrics;
import mx.core.IFlexDisplayObject;
import mx.core.IFlexModuleFactory;
import mx.core.IInvalidating;
*/
import mx.core.IUIComponent;
import mx.core.UIComponent;
/*
import mx.core.mx_internal;
import mx.events.ChildExistenceChangedEvent;
import mx.events.DividerEvent;
import mx.managers.CursorManager;
import mx.managers.CursorManagerPriority;
import mx.styles.IStyleManager2;
import mx.styles.StyleManager;
use namespace mx_internal;
*/
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched multiple times as the user drags any divider.
*
* The dividerDrag event is dispatched
* after the dividerPress event
* and before the dividerRelease event.
*
* @eventType mx.events.DividerEvent.DIVIDER_DRAG
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
//[Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")]
/**
* Dispatched when the user presses any divider in this container.
*
* The dividerPress event is dispatched
* before any dividerDrag events are dispatched.
*
* @eventType mx.events.DividerEvent.DIVIDER_PRESS
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
//[Event(name=""dividerPress"", type=""mx.events.DividerEvent"")]
/**
* Dispatched when the user releases a divider.
*
* The dividerRelease event is dispatched
* after the dividerDrag events,
* but before the container's children are resized.
* The divider's x and y properties are not updated until
* after this event is triggered. As a result, a call to
* hDividerBox.getDividerAt(0).x will return
* the value of the original x position of the first divider. If you want the
* position of the divider after the move, you can access it when the
* DividerBox's updateComplete event has been triggered.
*
* @eventType mx.events.DividerEvent.DIVIDER_RELEASE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
//[Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")]
/**
* A DividedBox container measures and lays out its children
* horizontally or vertically in exactly the same way as a
* Box container, but it inserts
* draggable dividers in the gaps between the children.
* Users can drag any divider to resize the children on each side.
*
*
The DividedBox class is the base class for the more commonly used
* HDividedBox and VDividedBox classes.
*
*
The direction property of a DividedBox container, inherited
* from Box container, determines whether it has horizontal
* or vertical layout.
*
*
A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:
*
*
*
Characteristic
*
Description
*
*
*
Default size
*
Vertical DividedBox Height is large enough to hold all of its children at the default or explicit
* heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the
* container. The width is the default or explicit width of the widest child, plus the left and right padding of
* the container.
* Horizontal DividedBox Width is large enough to hold all of its children at the
* default or explicit widths of the children, plus any horizontal gap between the children, plus the left and
* right padding of the container. Height is the default or explicit height of the tallest child
* plus the top and bottom padding of the container.
*
*
*
Default padding
*
0 pixels for the top, bottom, left, and right values.
*
*
*
Default gap
*
10 pixels for the horizontal and vertical gaps.
*
*
*
* @mxml
*
*
The <mx:DividedBox> tag inherits all of the tag
* attributes of its superclass, and adds the following tag attributes:
*
*
* <mx:DividedBox
* Properties
* liveDragging=""false|true""
* resizeToContent=""false|true""
*
* Styles
* dividerAffordance=""6""
* dividerAlpha=""0.75""
* dividerColor=""0x6F7777""
* dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
* dividerThickness=""3""
* horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
* verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
*
* Events
* dividerPress=""No default""
* dividerDrag=""No default""
* dividerRelease=""No default""
* >
* ...
* child tags
* ...
* </mx:DividedBox>
*
*
* @see mx.containers.HDividedBox
* @see mx.containers.VDividedBox
*
* @includeExample examples/DividedBoxExample.mxml
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class DividedBox extends Box
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
*/
private static const PROXY_DIVIDER_INDEX:int = 999;
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function DividedBox()
{
super();
// addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler);
// addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE,
// childRemoveHandler);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* Container for holding divider objects.
*/
private var dividerLayer:UIComponent = null;
/**
* @private
*/
//mx_internal var activeDivider:BoxDivider;
/**
* @private
*/
private var activeDividerIndex:int = -1;
/**
* @private
*/
private var activeDividerStartPosition:Number;
/**
* @private
*/
private var dragStartPosition:Number;
/**
* @private
*/
private var dragDelta:Number;
/**
* @private
*/
private var oldChildSizes:Array /* of ChildSizeInfo */;
/**
* @private
*/
private var minDelta:Number;
/**
* @private
*/
private var maxDelta:Number;
/**
* @private
* Only allow a single divider to move at a time.
*/
private var dontCoalesceDividers:Boolean;
/**
* @private
*/
//private var cursorID:int = CursorManager.NO_CURSOR;
/**
* @private
* We'll measure ourselves once and then store the results here
* for the lifetime of the DividedBox.
*/
private var dbMinWidth:Number;
private var dbMinHeight:Number;
private var dbPreferredWidth:Number;
private var dbPreferredHeight:Number;
/**
* @private
*/
private var layoutStyleChanged:Boolean = false;
/**
* @private
*/
private var _resizeToContent:Boolean = false;
/**
* @private
* Number of children with their includeInLayout set to true. The rest of
* the children don't count.
*/
private var numLayoutChildren:int = 0;
//--------------------------------------------------------------------------
//
// Overridden Properties
//
//--------------------------------------------------------------------------
/**
* @private
*/
// override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void
// {
// super.moduleFactory = moduleFactory;
//
// styleManager.registerSizeInvalidatingStyle(""dividerAffordance"");
// styleManager.registerSizeInvalidatingStyle(""dividerThickness"");
// }
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// direction
//----------------------------------
/**
* @private
*/
override public function set direction(value:String):void
{
if (super.direction != value)
{
super.direction = value;
// Need to invalidate all our dividers
// if (dividerLayer)
// {
// for (var i:int = 0; i < dividerLayer.numChildren; i++)
// getDividerAt(i).invalidateDisplayList();
// }
}
}
//----------------------------------
// dividerClass
//----------------------------------
/**
* The class for the divider between the children.
*
* @default mx.containers.dividedBoxClasses.BoxDivider
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
// protected var dividerClass:Class = BoxDivider;
//----------------------------------
// liveDragging
//----------------------------------
// [Inspectable(category=""General"")]
/**
* If true, the children adjacent to a divider
* are continuously resized while the user drags it.
* If false, they are not resized
* until the user releases the divider.
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
// public var liveDragging:Boolean = false;
//----------------------------------
// numDividers
//----------------------------------
/**
* The number of dividers.
* The count is always numChildren - 1.
*
* @return The number of dividers.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get numDividers():int
{
// if (dividerLayer)
// if (!liveDragging && activeDivider)
// return dividerLayer.numChildren-1;
// else
// return dividerLayer.numChildren;
// else
// return 0;
trace(""numDividers not implemented"");
return 0;
}
//----------------------------------
// resizeToContent
//----------------------------------
/**
* If true, the DividedBox automatically resizes to the size
* of its children.
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get resizeToContent():Boolean
{
return _resizeToContent;
}
/**
* @private
*/
public function set resizeToContent(value:Boolean):void
{
if (value != _resizeToContent)
{
_resizeToContent = value;
if (value)
invalidateSize();
}
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
* Override of the measure method of Box.
*
*
This function is almost identical to the Box version except
* that more extensive testing of the min, max
* boundary conditions is performed. This is because the DividedBox allows
* default values to be less than the min value of a control.
*/
// override protected function measure():void
// {
// super.measure();
//
// // We only measure ourselves once, since as we change the
// // size of children, they in turn change the preferred sizes
// //
// // We need to copy the cached values into the measured fields
// // again to handle the case where scaleX or scaleY is not 1.0.
// // When the ViewStack is zoomed, code in UIComponent.measureSizes
// // scales the measuredWidth/Height values every time that
// // measureSizes is called. (Bug 100749)
// if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged)
// {
// measuredMinWidth = dbMinWidth;
// measuredMinHeight = dbMinHeight;
// measuredWidth = dbPreferredWidth;
// measuredHeight = dbPreferredHeight;
// return;
// }
//
// layoutStyleChanged = false;
//
// var isVertical:Boolean = this.isVertical();
// var minWidth:Number = 0;
// var minHeight:Number = 0;
// var preferredWidth:Number = 0;
// var preferredHeight:Number = 0;
//
// var n:int = numChildren;
// for (var i:int = 0; i < n; i++)
// {
// var child:IUIComponent = getLayoutChildAt(i);
//
// if (!child.includeInLayout)
// continue;
//
// var prefW:Number = child.getExplicitOrMeasuredWidth();
// var prefH:Number = child.getExplicitOrMeasuredHeight();
//
// var minW:Number = child.minWidth;
// var minH:Number = child.minHeight;
//
// var wFlex:Boolean = !isNaN(child.percentWidth);
// var hFlex:Boolean = !isNaN(child.percentHeight);
//
// // Make sure we take the lowest of the low, since pref < min.
// var smallestMinW:Number = Math.min(prefW, minW);
// var smallestMinH:Number = Math.min(prefH, minH);
//
// if (isVertical)
// {
// minWidth = Math.max(wFlex ? minW : prefW, minWidth);
// preferredWidth = Math.max(prefW, preferredWidth);
// minHeight += hFlex ? smallestMinH : prefH;
// preferredHeight += prefH;
// }
// else
// {
// minWidth += wFlex ? smallestMinW : prefW;
// preferredWidth += prefW;
// minHeight = Math.max(hFlex ? minH : prefH, minHeight);
// preferredHeight = Math.max(prefH, preferredHeight);
// }
// }
//
// var wPadding:Number = layoutObject.widthPadding(numLayoutChildren);
// var hPadding:Number = layoutObject.heightPadding(numLayoutChildren);
//
// measuredMinWidth = dbMinWidth = minWidth + wPadding;
// measuredMinHeight = dbMinHeight = minHeight + hPadding;
// measuredWidth = dbPreferredWidth = preferredWidth + wPadding;
// measuredHeight = dbPreferredHeight = preferredHeight + hPadding;
// }
/**
* @private
*/
// override protected function updateDisplayList(unscaledWidth:Number,
// unscaledHeight:Number):void
// {
// var n:int;
// var i:int;
//
// // This method gets called while dragging a divider,
// // but we don't want to do anything then.
// if (!liveDragging && activeDivider)
// {
// n = numChildren;
// for (i = 0; i < n; i++)
// {
// var child:IUIComponent = getLayoutChildAt(i);
//
// if (!child.includeInLayout)
// continue;
//
// // Clear out measured min/max
// // so super.layout() doesn't use them.
// child.measuredMinWidth = 0;
// child.measuredMinHeight = 0;
// }
// return;
// }
//
// // Before we allow layout, let's clear out any measured min
// // values of our children so that they don't restrict us.
// // We only honour explicitly set mins/maxs.
// // We also try to remove any excess space, but tweaking
// // the % values on the flexible components.
// preLayoutAdjustment();
//
// // Let Box lay out the children.
// super.updateDisplayList(unscaledWidth, unscaledHeight);
//
// postLayoutAdjustment();
//
// // Lay out the dividers.
// if (!dividerLayer)
// return;
//
// var vm:EdgeMetrics = viewMetrics;
//
// dividerLayer.x = vm.left;
// dividerLayer.y = vm.top;
//
// var prevChild:IUIComponent = null;
// var dividerIndex:int = 0;
// n = numChildren;
// for (i = 0; i < n; i++)
// {
// child = UIComponent(getChildAt(i));
// if (child.includeInLayout)
// {
// if (prevChild)
// {
// layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child);
// dividerIndex++;
// }
// prevChild = child;
// }
// }
// }
/**
* @private
*/
// override protected function scrollChildren():void
// {
// super.scrollChildren();
//
// // Scroll divider layer.
// if (contentPane && dividerLayer)
// dividerLayer.scrollRect = contentPane.scrollRect;
// }
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* Returns a reference to the specified BoxDivider object
* in this DividedBox container or null if it doesn't exist.
*
* @param i Zero-based index of a divider, counting from
* the left for a horizontal DividedBox,
* or from the top for a vertical DividedBox.
*
* @return A BoxDivider object.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
// public function getDividerAt(i:int):BoxDivider
// {
// if (dividerLayer) {
// // Check whether this is a valid divider index.
// if (i < 0 || i >= dividerLayer.numChildren)
// return null;
// else
// return BoxDivider(dividerLayer.getChildAt(i));
// }
// else {
// return null;
// }
// }
/**
* Move a specific divider a given number of pixels.
*
* @param i Zero-based index of a divider, counting from
* the left for a horizontal DividedBox,
* or from the top for a vertical DividedBox.
*
* @param amt The number of pixels to move the divider.
* A negative number can be specified in order to move
* a divider up or left. The divider movement is
* constrained in the same manner as if a user
* had moved it.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
// public function moveDivider(i:int, amt:Number):void
// {
// // Check whether this is a valid divider index.
// if (i < 0 || i >= numDividers)
// return;
//
// // Make sure the user is not currently dragging.
// if (activeDividerIndex >= 0)
// return;
//
// // We have to first hit the children if we haven't
// // yet done so since the first movement .
//
// // Mimic a divider moving.
// activeDividerIndex = i;
//
// // Store away child sizes,
// // then determine the limits on our movement.
// cacheChildSizes();
// computeMinAndMaxDelta();
// dragDelta = limitDelta(amt);
//
// // Now update the children sizes accordingly.
// adjustChildSizes();
//
// invalidateSize();
// invalidateDisplayList();
//
// // Reset the divider tracking stuff.
// resetDividerTracking();
// }
/**
* @private
*/
// private function createDivider(i:int):BoxDivider
// {
// // Create separate layer for holding divider objects.
// if (!dividerLayer)
// {
// dividerLayer = UIComponent(rawChildren.addChild(new UIComponent()));
// }
//
// var divider:BoxDivider = BoxDivider(new dividerClass());
// dividerLayer.addChild(divider);
//
// // if we are creating the active divider bring the divider layer
// // to the top most so that users can see the divider line over
// // the other children
// if (i == PROXY_DIVIDER_INDEX)
// {
// rawChildren.setChildIndex(dividerLayer,
// rawChildren.numChildren-1);
// }
//
// // Tell BoxDivider to use DividedBox's styles,
// // unless we are sliding the divider; in that case,
// // use the styles of the divider we are sliding.
// var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ?
// getDividerAt(activeDividerIndex) :
// this;
//
// divider.styleName = basedOn;
//
// divider.owner = this;
//
// return divider;
// }
/**
* @private
*/
private function layoutDivider(i:int,
unscaledWidth:Number,
unscaledHeight:Number,
prevChild:IUIComponent,
nextChild:IUIComponent):void
{
// The mouse-over thickness of the divider is normally determined
// by the dividerAffordance style, and the visible thickness is
// normally determined by the dividerThickness style, assuming that
// the relationship thickness <= affordance <= gap applies. But if
// one of the other five orderings applies, here is a table of what
// happens:
//
// divider divider horizontalGap/ dividerWidth/ visible width/
// Thickness Affordance verticalGap dividerHeight visible height
//
// 4 6 8 6 4
// 4 8 6 6 4
// 6 4 8 6 6
// 6 8 4 4 4
// 8 4 6 6 6
// 8 6 4 4 4
// var divider:BoxDivider = BoxDivider(getDividerAt(i));
//
// var vm:EdgeMetrics = viewMetrics;
//
// var verticalGap:Number = getStyle(""verticalGap"");
// var horizontalGap:Number = getStyle(""horizontalGap"");
//
// var thickness:Number = divider.getStyle(""dividerThickness"");
// var affordance:Number = divider.getStyle(""dividerAffordance"");
//
// if (isVertical())
// {
// var dividerHeight:Number = affordance;
// // dividerHeight is the mouse-over height,
// // not necessarily the visible height.
//
// // The specified affordance should be greater than the thickness.
// // But if it isn't, use the thickness instead to determine the
// // divider height.
// if (dividerHeight < thickness)
// dividerHeight = thickness;
//
// // Don't let the divider overlap the children.
// if (dividerHeight > verticalGap)
// dividerHeight = verticalGap;
//
// divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight);
//
// divider.move(vm.left,
// Math.round((prevChild.y + prevChild.height +
// nextChild.y - dividerHeight) / 2));
// }
// else
// {
// var dividerWidth:Number = affordance;
// // dividerWidth is the mouse-over width,
// // not necessarily the visible width.
//
// // The specified affordance should be greater than the thickness.
// // But if it isn't, use the thickness instead to determine the
// // divider width.
// if (dividerWidth < thickness)
// dividerWidth = thickness;
//
// // Don't let the divider overlap the children.
// if (dividerWidth > horizontalGap)
// dividerWidth = horizontalGap;
//
// divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom);
//
// divider.move(Math.round((prevChild.x + prevChild.width +
// nextChild.x - dividerWidth) / 2),
// vm.top);
// }
//
// divider.invalidateDisplayList();
}
/**
* @private
*/
// mx_internal function changeCursor(divider:BoxDivider):void
// {
// if (cursorID == CursorManager.NO_CURSOR)
// {
// // If a cursor skin has been set for the specified BoxDivider,
// // use it. Otherwise, use the cursor skin for the DividedBox.
// var cursorClass:Class = isVertical() ?
// getStyle(""verticalDividerCursor"") as Class :
// getStyle(""horizontalDividerCursor"") as Class;
//
// cursorID = cursorManager.setCursor(cursorClass,
// CursorManagerPriority.HIGH, 0, 0);
// }
// }
/**
* @private
*/
// mx_internal function restoreCursor():void
// {
// if (cursorID != CursorManager.NO_CURSOR)
// {
// cursorManager.removeCursor(cursorID);
// cursorID = CursorManager.NO_CURSOR;
// }
// }
/**
* @private
*/
// mx_internal function getDividerIndex(divider:BoxDivider):int
// {
// var n:int = numChildren;
// for (var i:int = 0; i < n - 1; i++)
// {
// if (getDividerAt(i) == divider)
// return i;
// }
// return -1;
// }
/**
* @private
*/
// private function getMousePosition(event:MouseEvent):Number
// {
// var point:Point = new Point(event.stageX, event.stageY);
// point = globalToLocal(point);
// return isVertical() ? point.y : point.x;
// }
/**
* @private
*/
// mx_internal function startDividerDrag(divider:BoxDivider,
// trigger:MouseEvent):void
// {
// // Make sure the user is not currently dragging.
// if (activeDividerIndex >= 0)
// return;
//
// activeDividerIndex = getDividerIndex(divider);
//
// var event:DividerEvent =
// new DividerEvent(DividerEvent.DIVIDER_PRESS);
// event.dividerIndex = activeDividerIndex;
// dispatchEvent(event);
//
// if (liveDragging)
// activeDivider = divider;
// else
// {
// activeDivider = createDivider(PROXY_DIVIDER_INDEX);
// activeDivider.visible = false;
// activeDivider.state = DividerState.DOWN;
// activeDivider.setActualSize(divider.width, divider.height);
// activeDivider.move(divider.x, divider.y);
// activeDivider.visible = true;
// divider.state = DividerState.UP;
// }
//
// if (isVertical())
// activeDividerStartPosition = activeDivider.y;
// else
// activeDividerStartPosition = activeDivider.x;
//
// dragStartPosition = getMousePosition(trigger);
// dragDelta = 0;
//
// cacheChildSizes();
// adjustChildSizes();
//
// computeMinAndMaxDelta();
//
// systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true);
// systemManager.deployMouseShields(true);
// }
/**
* @private
* Store away some important information about
* each child for us to use while we move the divider.
*/
// private function cacheSizes():void
// {
// oldChildSizes = []; // empty array
//
// var vertical:Boolean = isVertical();
//
// var smallest:Number = Number.MAX_VALUE; // use a big number
//
// var n:int = numChildren;
// for (var i:int = 0; i < n; i++)
// {
// var child:IUIComponent = getLayoutChildAt(i);
// if (!child.includeInLayout)
// continue;
//
// var sz:Number = vertical ? child.height : child.width;
//
// var mx:Number = vertical ? child.maxHeight : child.maxWidth;
//
// var umn:Number = vertical ?
// child.explicitMinHeight :
// child.explicitMinWidth; // avoid measured values
//
// // A NaN min means 0.
// var mn:Number = (isNaN(umn)) ? 0 : umn;
//
// // Compute these for later use.
// var dMin:Number = Math.max(0, sz - mn);
// var dMax:Number = Math.max(0, mx - sz);
//
// if (sz > 0 && sz < smallest)
// smallest = sz;
//
// oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax));
// }
//
// // Remember the smallest child size we saw.
// oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest));
// }
/**
* @private
*/
// private function cacheChildSizes():void
// {
// oldChildSizes = []; // clear or store
//
// cacheSizes();
// }
/**
* @private
*/
// private function mouseMoveHandler(event:MouseEvent):void
// {
// dragDelta = limitDelta(getMousePosition(event) - dragStartPosition);
//
// var dividerEvent:DividerEvent =
// new DividerEvent(DividerEvent.DIVIDER_DRAG);
// dividerEvent.dividerIndex = activeDividerIndex;
// dividerEvent.delta = dragDelta;
// dispatchEvent(dividerEvent);
//
// if (liveDragging)
// {
// adjustChildSizes();
//
// invalidateDisplayList();
//
// updateDisplayList(unscaledWidth, unscaledHeight);
// }
// else
// {
// if (isVertical())
// activeDivider.move(0, activeDividerStartPosition + dragDelta);
// else
// activeDivider.move(activeDividerStartPosition + dragDelta, 0);
// }
// }
/**
* @private
*
* @param trigger May be null if the event is not a MouseEvent but
* a mouse event from another sandbox.
*/
// mx_internal function stopDividerDrag(divider:BoxDivider,
// trigger:MouseEvent):void
// {
// if (trigger)
// dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition);
//
// var event:DividerEvent =
// new DividerEvent(DividerEvent.DIVIDER_RELEASE);
// event.dividerIndex = activeDividerIndex;
// event.delta = dragDelta;
// dispatchEvent(event);
//
// if (!liveDragging)
// {
// if (dragDelta == 0)
// getDividerAt(activeDividerIndex).state = DividerState.OVER;
//
// if (activeDivider)
// dividerLayer.removeChild(activeDivider);
// activeDivider = null;
//
// adjustChildSizes();
//
// invalidateSize();
// invalidateDisplayList();
// }
//
// resetDividerTracking();
// systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true);
// systemManager.deployMouseShields(false);
// }
/**
* @private
*/
// private function resetDividerTracking():void
// {
// activeDivider = null;
// activeDividerIndex = -1;
// activeDividerStartPosition = NaN;
// dragStartPosition = NaN;
// dragDelta = NaN;
// oldChildSizes = null;
// minDelta = NaN;
// maxDelta = NaN;
// }
/**
* @private
* Determine the maximum amount of movement that
* a divider, i, can move both up and down.
*
* We base this calculation on the amount of
* travel that each divider supports, assuming
* that as one divider reaches its limits, the next
* divider will move. In this way dividers will
* cascade.
*/
// private function computeAllowableMovement(at:int):void
// {
// // We break the computation into two loops,
// // so that we can calc min and max travel
// // independently as one would move the divider
// // either up or down.
// var deltaMinAbove:Number = 0;
// var deltaMaxAbove:Number = 0;
// var deltaMinBelow:Number = 0;
// var deltaMaxBelow:Number = 0;
//
// var n:int = numLayoutChildren;
// var i:int;
// var child:ChildSizeInfo;
//
// if (at < 0)
// return;
//
// for (i = at; i >= 0; i--)
// {
// child = ChildSizeInfo(oldChildSizes[i]);
//
// deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ?
// 0 : child.deltaMin;
//
// deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ?
// 0 : child.deltaMax;
// }
//
// for (i = at + 1; i < n; i++)
// {
// child = ChildSizeInfo(oldChildSizes[i]);
//
// deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ?
// 0 : child.deltaMin;
//
// deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ?
// 0 : child.deltaMax;
// }
//
// // Now the maximum movement we can have if
// // the divider is moved up is equal to the
// // smaller of how much we can shrink all
// // components above our divider or the
// // maximum of how much the components below
// // our divider can grow. Similarly for the
// // divider moving in the opposite direction.
// var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow);
// var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove);
//
// // deltaUp needs to be in -ve in order for our
// // update logic to work
// minDelta = -deltaUp;
// maxDelta = deltaDn;
// }
/**
* @private
*/
// private function computeMinAndMaxDelta():void
// {
// computeAllowableMovement(activeDividerIndex);
// }
/**
* @private
*/
// private function limitDelta(delta:Number):Number
// {
// if (delta < minDelta)
// delta = minDelta;
// else if (delta > maxDelta)
// delta = maxDelta;
//
// // Make sure it is not fractional,
// // otherwise we lose pixels. (Bug 87339)
// delta = Math.round(delta);
// return delta;
// }
/**
* @private
* We distribute the delta space in the same
* fashion that we calculated it. That is we
* start at the divider and give out space
* until we hit a limit on the component or
* we run out of space to distribute.
* We need to do this in both directions since
* in one direction we are shrinking and
* in the other we are growing.
*/
// private function distributeDelta():void
// {
// // if there is no movement of divider we need not
// // do any child resizing.
// if (!dragDelta)
// return;
//
// var vertical:Boolean = isVertical();
// var n:int = numLayoutChildren;
// var k:int = activeDividerIndex;
// var smallest:Number = oldChildSizes[n].size -
// Math.abs(dragDelta); // smallest possible child size
//
// if (smallest <= 0 || isNaN(smallest))
// smallest = 1;
//
// var i:int;
// var size:ChildSizeInfo;
// var move:Number;
// var newSize:Number;
// var child:IUIComponent;
// var childSize:Number;
//
// // Find the index of the child before the active divider
// var activeDividerChildIndex:int = -1;
// var dividerIndex:int = -1;
// while (dividerIndex < activeDividerIndex)
// {
// if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout)
// ++dividerIndex;
// }
//
// // Distribute space starting from the center and
// // moving upwards.
// var curChildIndex:int = activeDividerChildIndex;
// var amt:Number = dragDelta;
// for (i = k; i >= 0; i--)
// {
// // If dragDelta -ve => shrink upper components
// // otherwise grow them.
// size = ChildSizeInfo(oldChildSizes[i]);
// move = (amt < 0) ?
// -Math.min(-amt, size.deltaMin) :
// Math.min(amt, size.deltaMax);
//
// // Adjust the component and reduce the remaining delta
// newSize = size.size + move;
// amt -= move;
//
// // Find the previous child included in the layout
// do
// {
// child = IUIComponent(getChildAt(curChildIndex--));
// }
// while (!child.includeInLayout);
//
// // Adjust the child size.
// childSize = (newSize / smallest) * 100;
//
// if (vertical)
// child.percentHeight = childSize;
// else
// child.percentWidth = childSize;
//
// // Force a re-measure.
// if (child is IInvalidating)
// IInvalidating(child).invalidateSize();
// }
//
// // assert(amt == 0)
//
// // Now do the same distribution but moving downwards.
// curChildIndex = activeDividerChildIndex + 1;
// amt = dragDelta;
// for (i = k + 1; i < n; i++)
// {
// // If dragDelta -ve => grow lower components
// // otherwise shrink them.
// size = ChildSizeInfo(oldChildSizes[i]);
// move = (amt < 0) ?
// Math.min(-amt, size.deltaMax) :
// -Math.min(amt, size.deltaMin);
//
// // Adjust the component and reduce the remaining delta.
// newSize = size.size + move;
// amt += move;
//
// // Find the next child included in the layout
// do
// {
// child = IUIComponent(getChildAt(curChildIndex++));
// }
// while (!child.includeInLayout);
//
// childSize = (newSize / smallest) * 100;
//
// if (vertical)
// child.percentHeight = childSize;
// else
// child.percentWidth = childSize;
//
// // Force a re-measure.
// if (child is IInvalidating)
// IInvalidating(child).invalidateSize();
// }
// }
/**
* @private
* For 1.5 we normalize all children to the smallest one
* So that we can remove n-1 children and still guarantee
* one child can consume 100%.
* Also we support the concept of fixed sized children,
* which allows us to have one or more children be rigid
* in the DividedBox in this case, the dividers above
* and below the fixed component move in unison.
*/
// private function adjustChildSizes():void
// {
// distributeDelta();
// }
/**
* @private
* Algorithm employed pre-layout to ensure that
* we don't leave any dangling space and to ensure
* that only explicit min/max values are honored.
*
* We first compute the sum of %'s across all
* children to ensure that we have at least 100%.
* If so, we are done. If not, then we attempt
* to attach the remaining amount to the last
* component, if not, then we distribute the
* percentages evenly across all % components.
*
*/
// private function preLayoutAdjustment():void
// {
// // Calculate the total %
// var vertical:Boolean = isVertical();
//
// var totalPerc:Number = 0;
// var percCount:Number = 0;
//
// var n:int = numChildren;
// var i:int;
// var child:IUIComponent;
// var perc:Number;
//
// for (i = 0; i < n; i++)
// {
// child = getLayoutChildAt(i);
//
// if (!child.includeInLayout)
// continue;
//
// // Clear out measured min/max
// // so super.layout() doesn't use them.
// child.measuredMinWidth = 0;
// child.measuredMinHeight = 0;
//
// perc = vertical ? child.percentHeight : child.percentWidth;
//
// if (!isNaN(perc))
// {
// totalPerc += perc;
// percCount++;
// }
// }
//
// // during preLayoutAdjustment, we make some changes to the children's
// // widths and heights. We keep track of the original values in postLayoutChanges
// // so we can later go back and reset them so another layout pass is working
// // with the correct values rather than these modified values.
// postLayoutChanges = [];
// var changeObject:Object;
//
// // No flexible children, so we make the last one 100%.
// if (totalPerc == 0 && percCount == 0)
// {
// // Everyone is fixed and we can give 100% to the last
// // included in layout one without concern.
// for (i = n-1; i >= 0; i--)
// {
// child = UIComponent(getChildAt(i));
// if (child.includeInLayout)
// {
// // create a changeObject to keep track of the original values
// // that this child had for width and height
// changeObject = {child: child};
// if (vertical)
// {
// // we know there's no percentHeight originally
// if (child.explicitHeight)
// changeObject.explicitHeight = child.explicitHeight;
// else
// changeObject.percentHeight = NaN;
//
// child.percentHeight = 100;
// }
// else
// {
// // we know there's no percentWidth originally
// if (child.explicitWidth)
// changeObject.explicitWidth = child.explicitWidth;
// else if (child.percentWidth)
// changeObject.percentWidth = NaN;
//
// child.percentWidth = 100;
// }
// postLayoutChanges.push(changeObject);
// break;
// }
// }
// }
// else if (totalPerc < 100)
// {
// // We have some %s but they don't total to 100, so lets
// // distribute the delta across all of them and in the
// // meantime normalize all %s to unscaledHeight/Width.
// // The normalization takes care of the case where any one
// // of the components hits a min/max limit on their size,
// // which could result in the others filling less than 100%.
// var delta:Number = Math.ceil((100 - totalPerc) / percCount);
// for (i = 0; i < n; i++)
// {
// child = getLayoutChildAt(i);
//
// if (!child.includeInLayout)
// continue;
//
// changeObject = {child: child};
//
// if (vertical)
// {
// perc = child.percentHeight;
// if (!isNaN(perc))
// {
// changeObject.percentHeight = child.percentHeight;
// postLayoutChanges.push(changeObject);
//
// child.percentHeight = (perc + delta) * unscaledHeight;
// }
// }
// else
// {
// perc = child.percentWidth;
// if (!isNaN(perc))
// {
// changeObject.percentWidth = child.percentWidth;
// postLayoutChanges.push(changeObject);
//
// child.percentWidth = (perc + delta) * unscaledWidth;
// }
// }
// }
// }
//
// // OK after all this magic we still can't guarantee that the space is
// // entirely filled. For example, all percent components hit their max
// // values. In this case, the layout will include empty space at the end,
// // and once the divider is touched, the non-percent based components
// // will be converted into percent based ones and fill the remaining
// // space. It seems to me that this scenario is highly unlikely.
// // Thus I've choosen the route of stretching the percent based
// // components and not touching the explicitly sized or default
// // sized ones.
// //
// // Another option would be to stretch the default sized components
// // either in addition to the percent based ones or instead of.
// // This seemed a little odd to me as the user never indicated
// // that these components are to be stretched initially, so in the end
// // I choose to tweak the components that the user has indicated
// // as being stretchable.
// }
/**
* @private
* During preLayoutAdjustment, we make some changes to the children's
* widths and heights. We keep track of the original values in postLayoutChanges
* so we can later go back and reset them so another layout pass is working
* with the correct values rather than these modified values.
*/
// private var postLayoutChanges:Array;
/**
* @private
* Post layout work. In preLayoutAdjustment()
* sometimes we set a child's percentWidth/percentHeight.
* postLayoutAdjustment() will reset the child's width or height
* back to what it was.
*/
// private function postLayoutAdjustment():void
// {
// // each object has a child property and may have a set of width/height
// // properties that it would like to be set
// var len:int = postLayoutChanges.length;
// for (var i:int = 0; i < len; i++)
// {
// var changeObject:Object = postLayoutChanges[i];
//
// if (changeObject.percentWidth !== undefined)
// changeObject.child.percentWidth = changeObject.percentWidth;
//
// if (changeObject.percentHeight !== undefined)
// changeObject.child.percentHeight = changeObject.percentHeight;
//
// if (changeObject.explicitWidth !== undefined)
// changeObject.child.explicitWidth = changeObject.explicitWidth;
//
// if (changeObject.explicitHeight !== undefined)
// changeObject.child.explicitHeight = changeObject.explicitHeight;
// }
// postLayoutChanges = null;
// }
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
// private function childAddHandler(event:ChildExistenceChangedEvent):void
// {
// var child:DisplayObject = event.relatedObject;
//
// child.addEventListener(""includeInLayoutChanged"",
// child_includeInLayoutChangedHandler);
//
// if (!IUIComponent(child).includeInLayout)
// return;
//
// numLayoutChildren++;
//
// if (numLayoutChildren > 1)
// createDivider(numLayoutChildren - 2);
//
// // Clear the cached values so that we do another
// // measurement pass.
// dbMinWidth = NaN;
// dbMinHeight = NaN;
// dbPreferredWidth = NaN;
// dbPreferredHeight = NaN;
// }
/**
* @private
*/
// private function childRemoveHandler(event:ChildExistenceChangedEvent):void
// {
// var child:DisplayObject = event.relatedObject;
//
// child.removeEventListener(""includeInLayoutChanged"",
// child_includeInLayoutChangedHandler);
//
// if (!IUIComponent(child).includeInLayout)
// return;
//
// numLayoutChildren--;
//
// if (numLayoutChildren > 0)
// dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1));
//
// // Clear the cached values so that we do another
// // measurement pass.
// dbMinWidth = NaN;
// dbMinHeight = NaN;
// dbPreferredWidth = NaN;
// dbPreferredHeight = NaN;
// invalidateSize();
// }
/**
* @private
* When a child's includeInLayout changes, we either remove or add a
* divider.
*/
// private function child_includeInLayoutChangedHandler(event:Event):void
// {
// var child:UIComponent = UIComponent(event.target);
//
// if (child.includeInLayout && ++numLayoutChildren > 1)
// createDivider(numLayoutChildren - 2);
//
// else if (!child.includeInLayout && --numLayoutChildren > 0)
// dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1));
//
// // Clear the cached values so that we do another
// // measurement pass.
// dbMinWidth = NaN;
// dbMinHeight = NaN;
// dbPreferredWidth = NaN;
// dbPreferredHeight = NaN;
// invalidateSize();
// }
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Helper class: ChildSizeInfo
//
////////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
//class ChildSizeInfo
//{
// //--------------------------------------------------------------------------
// //
// // Constructor
// //
// //--------------------------------------------------------------------------
//
// /**
// * @private
// */
// public function ChildSizeInfo(size:Number,
// min:Number = 0, max:Number = 0,
// deltaMin:Number = 0, deltaMax:Number = 0)
// {
// super();
//
// this.size = size;
// this.min = min;
// this.max = max;
// this.deltaMin = deltaMin;
// this.deltaMax = deltaMax;
// }
//
// //--------------------------------------------------------------------------
// //
// // Properties
// //
// //--------------------------------------------------------------------------
//
// //----------------------------------
// // deltaMin
// //----------------------------------
//
// /**
// * @private
// */
// public var deltaMin:Number;
//
// //----------------------------------
// // deltaMax
// //----------------------------------
//
// /**
// * @private
// */
// public var deltaMax:Number;
//
// //----------------------------------
// // min
// //----------------------------------
//
// /**
// * @private
// */
// public var min:Number;
//
// //----------------------------------
// // max
// //----------------------------------
//
// /**
// * @private
// */
// public var max:Number;
//
// //----------------------------------
// // size
// //----------------------------------
//
// /**
// * @private
// */
// public var size:Number;
//}
",12352,False,2341.7994138412378,median
"////
This guide is maintained in the main Quarkus repository
and pull requests should be submitted there:
https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc
////
= Writing REST Services with RESTEasy Reactive
include::./attributes.adoc[]
:jaxrsapi: https://javadoc.io/doc/javax.ws.rs/javax.ws.rs-api/2.1.1
:jaxrsspec: /specs/jaxrs/2.1/index.html
:jdkapi: https://docs.oracle.com/en/java/javase/11/docs/api/java.base
:mutinyapi: https://smallrye.io/smallrye-mutiny/apidocs
:httpspec: https://tools.ietf.org/html/rfc7231
:jsonpapi: https://javadoc.io/doc/javax.json/javax.json-api/1.1.4
:vertxapi: https://javadoc.io/static/io.vertx/vertx-core/4.1.0
:resteasy-reactive-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive/2.0.0.Final
:resteasy-reactive-common-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive-common/2.0.0.Final
This guide explains how to write REST Services with RESTEasy Reactive in Quarkus.
== What is RESTEasy Reactive?
RESTEasy Reactive is a new link:{jaxrsspec}[JAX-RS]
implementation written from the ground up to work on our
common https://vertx.io/[Vert.x] layer and is thus fully reactive, while also being very tightly integrated with
Quarkus and consequently moving a lot of work to build time.
You should be able to use it in place of any JAX-RS implementation, but on top of that it has
great performance for both blocking and non-blocking endpoints, and a lot of new features on top
of what JAX-RS provides.
== Writing endpoints
=== Getting started
Add the following import to your build file:
[source,xml,role=""primary asciidoc-tabs-target-sync-cli asciidoc-tabs-target-sync-maven""]
.pom.xml
----
io.quarkusquarkus-resteasy-reactive
----
[source,gradle,role=""secondary asciidoc-tabs-target-sync-gradle""]
.build.gradle
----
implementation(""io.quarkus:quarkus-resteasy-reactive"")
----
You can now write your first endpoint in the `org.acme.rest.Endpoint` class:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("""")
public class Endpoint {
@GET
public String hello() {
return ""Hello, World!"";
}
}
----
=== Terminology
REST:: https://en.wikipedia.org/wiki/Representational_state_transfer[REpresentational State Transfer]
Endpoint:: Java method which is called to serve a REST call
URL / URI (Uniform Resource Locator / Identifier):: Used to identify the location of REST resources (https://tools.ietf.org/html/rfc7230#section-2.7[specification])
Resource:: Represents your domain object. This is what your API serves and modifies. Also called an `entity` in JAX-RS.
Representation:: How your resource is represented on the wire, can vary depending on content types
Content type:: Designates a particular representation (also called a media type), for example `text/plain` or `application/json`
HTTP:: Underlying wire protocol for routing REST calls (see https://tools.ietf.org/html/rfc7230[HTTP specifications])
HTTP request:: the request part of the HTTP call, consisting of an HTTP method, a target URI, headers and an optional message body
HTTP response:: the response part of the HTTP call, consisting of an HTTP response status, headers and an optional message body
=== Declaring endpoints: URI mapping
Any class annotated with a link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation can have its methods exposed as REST endpoints,
provided they have an HTTP method annotation (see below).
That link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation defines the URI prefix under which those methods will be exposed. It can
be empty, or contain a prefix such as `rest` or `rest/V1`.
Each exposed endpoint method can in turn have another link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation which adds to its containing
class annotation. For example, this defines a `rest/hello` endpoint:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path(""rest"")
public class Endpoint {
@Path(""hello"")
@GET
public String hello() {
return ""Hello, World!"";
}
}
----
See <> for more information about URI mapping.
You can set the root path for all rest endpoints using the `@ApplicationPath` annotation, as shown below.
[source,java]
----
package org.acme.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath(""/api"")
public static class MyApplication extends Application {
}
----
This will cause all rest endpoints to be resolve relative to `/api`, so the endpoint above with `@Path(""rest"")` would
be accessible at `/api/rest/. You can also set the `quarkus.rest.path` build time property to set the root path if you
don't want to use an annotation.
=== Declaring endpoints: HTTP methods
Each endpoint method must be annotated with one of the following annotations, which defines which HTTP
method will be mapped to the method:
.Table HTTP method annotations
|===
|Annotation|Usage
|link:{jaxrsapi}/javax/ws/rs/GET.html[`@GET`]
|Obtain a resource representation, should not modify state, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.1[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/HEAD.html[`@HEAD`]
|Obtain metadata about a resource, similar to `GET` with no body (link:{httpspec}#section-4.3.2[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/POST.html[`@POST`]
|Create a resource and obtain a link to it (link:{httpspec}#section-4.3.3[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/PUT.html[`@PUT`]
|Replace a resource or create one, should be link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.4[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/DELETE.html[`@DELETE`]
|Delete an existing resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.5[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/OPTIONS.html[`@OPTIONS`]
|Obtain information about a resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.7[HTTP docs])
|link:{jaxrsapi}/javax/ws/rs/PATCH.html[`@PATCH`]
|Update a resource, or create one, not link:{httpspec}#section-4.2.2[idempotent] (https://tools.ietf.org/html/rfc5789#section-2[HTTP docs])
|===
You can also declare other HTTP methods by declaring them as an annotation with the
link:{jaxrsapi}/javax/ws/rs/HttpMethod.html[`@HttpMethod`] annotation:
[source,java]
----
package org.acme.rest;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(""FROMAGE"")
@interface FROMAGE {
}
@Path("""")
public class Endpoint {
@FROMAGE
public String hello() {
return ""Hello, Cheese World!"";
}
}
----
=== Declaring endpoints: representation / content types
Each endpoint method may consume or produce specific resource representations, which are indicated by
the HTTP link:{httpspec}#section-3.1.1.5[`Content-Type`] header, which in turn contains
link:{httpspec}#section-3.1.1.1[MIME (Media Type)] values, such as the following:
- `text/plain` which is the default for any endpoint returning a `String`.
- `text/html` for HTML (such as with xref:qute.adoc[Qute templating])
- `application/json` for a <>
- `text/*` which is a sub-type wildcard for any text media type
- `\\*/*` which is a wildcard for any media type
You may annotate your endpoint class with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`]
or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, which
allow you to specify one or more media types that your endpoint may accept as HTTP request body
or produce as HTTP response body. Those class annotations apply to each method.
Any method may also be annotated with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`]
or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, in which
case they override any eventual class annotation.
The link:{jaxrsapi}/javax/ws/rs/core/MediaType.html[`MediaType`] class has many constants you
can use to point to specific pre-defined media types.
See <> for more information.
=== Accessing request parameters
[[request-parameters]]
NOTE: don't forget to configure your compiler to generate parameter name information with `-parameters` (javac)
or `` or `` (https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#parameters[Maven]).
The following HTTP request elements may be obtained by your endpoint method:
.Table HTTP request parameter annotations
|===
|HTTP element|Annotation|Usage
|[[path-parameter]]Path parameter
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`] (or nothing)
|URI template parameter (simplified version of the https://tools.ietf.org/html/rfc6570[URI Template specification]),
see <> for more information.
|Query parameter
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestQuery.html[`@RestQuery`]
|The value of an https://tools.ietf.org/html/rfc3986#section-3.4[URI query parameter]
|Header
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestHeader.html[`@RestHeader`]
|The value of an https://tools.ietf.org/html/rfc7230#section-3.2[HTTP header]
|Cookie
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestCookie.html[`@RestCookie`]
|The value of an https://tools.ietf.org/html/rfc6265#section-4.2[HTTP cookie]
|Form parameter
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`]
|The value of an https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST[HTTP URL-encoded FORM]
|Matrix parameter
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestMatrix.html[`@RestMatrix`]
|The value of an https://tools.ietf.org/html/rfc3986#section-3.3[URI path segment parameter]
|===
For each of those annotations, you may specify the name of the element they refer to, otherwise
they will use the name of the annotated method parameter.
If a client made the following HTTP call:
[source,http]
----
POST /cheeses;variant=goat/tomme?age=matured HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Cookie: level=hardcore
X-Cheese-Secret-Handshake: fist-bump
smell=strong
----
Then you could obtain all the various parameters with this endpoint method:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import org.jboss.resteasy.reactive.RestCookie;
import org.jboss.resteasy.reactive.RestForm;
import org.jboss.resteasy.reactive.RestHeader;
import org.jboss.resteasy.reactive.RestMatrix;
import org.jboss.resteasy.reactive.RestPath;
import org.jboss.resteasy.reactive.RestQuery;
@Path(""/cheeses/{type}"")
public class Endpoint {
@POST
public String allParams(@RestPath String type,
@RestMatrix String variant,
@RestQuery String age,
@RestCookie String level,
@RestHeader(""X-Cheese-Secret-Handshake"")
String secretHandshake,
@RestForm String smell) {
return type + ""/"" + variant + ""/"" + age + ""/"" + level + ""/"" + secretHandshake + ""/"" + smell;
}
}
----
NOTE: the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`]
annotation is optional: any parameter whose name matches an existing URI
template variable will be automatically assumed to have link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`].
You can also use any of the JAX-RS annotations link:{jaxrsapi}/javax/ws/rs/PathParam.html[`@PathParam`],
link:{jaxrsapi}/javax/ws/rs/QueryParam.html[`@QueryParam`],
link:{jaxrsapi}/javax/ws/rs/HeaderParam.html[`@HeaderParam`],
link:{jaxrsapi}/javax/ws/rs/CookieParam.html[`@CookieParam`],
link:{jaxrsapi}/javax/ws/rs/FormParam.html[`@FormParam`] or
link:{jaxrsapi}/javax/ws/rs/MatrixParam.html[`@MatrixParam`] for this,
but they require you to specify the parameter name.
See <> for more advanced use-cases.
=== Declaring URI parameters
[[uri-parameters]]
You can declare URI parameters and use regular expressions in your path, so for instance
the following endpoint will serve requests for `/hello/stef/23` and `/hello` but not
`/hello/stef/0x23`:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path(""hello"")
public class Endpoint {
@Path(""{name}/{age:\\\\d+}"")
@GET
public String personalisedHello(String name, int age) {
return ""Hello "" + name + "" is your age really "" + age + ""?"";
}
@GET
public String genericHello() {
return ""Hello stranger"";
}
}
----
=== Accessing the request body
Any method parameter with no annotation will receive the method body.footnote:[Unless it is a
<> or a <>.], after it has been mapped from
its HTTP representation to the Java type of the parameter.
The following parameter types will be supported out of the box:
[[resource-types]]
.Table Request body parameter type
|===
|Type|Usage
|link:{jdkapi}/java/io/File.html[`File`]
|The entire request body in a temporary file
|`byte[]`
|The entire request body, not decoded
|`char[]`
|The entire request body, decoded
|link:{jdkapi}/java/lang/String.html[`String`]
|The entire request body, decoded
|link:{jdkapi}/java/io/InputStream.html[`InputStream`]
|The request body in a blocking stream
|link:{jdkapi}/java/io/Reader.html[`Reader`]
|The request body in a blocking stream
|All Java primitives and their wrapper classes
|Java primitive types
|link:{jdkapi}/java/math/BigDecimal.html[`BigDecimal`], link:{jdkapi}/java/math/BigInteger.html[`BigInteger`]
|Large integers and decimals.
|link:{jsonpapi}/javax/json/JsonArray.html[`JsonArray`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonObject`],
link:{jsonpapi}/javax/json/JsonArray.html[`JsonStructure`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonValue`]
|JSON value types
|link:{vertxapi}io/vertx/core/buffer/Buffer.html[`Buffer`]
|Vert.x Buffer
|any other type
|Will be <>
|===
NOTE: You can add support for more <>.
=== Handling Multipart Form data
To handle HTTP requests that have `multipart/form-data` as their content type, RESTEasy Reactive introduces the
link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] annotation.
Let us look at an example of its use.
Assuming an HTTP request containing a file upload and a form value containing a string description need to be handled, we could write a POJO
that will hold this information like so:
[source,java]
----
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.reactive.PartType;
import org.jboss.resteasy.reactive.RestForm;
import org.jboss.resteasy.reactive.multipart.FileUpload;
public class FormData {
@RestForm
@PartType(MediaType.TEXT_PLAIN)
public String description;
@RestForm(""image"")
public FileUpload file;
}
----
The `name` field will contain the data contained in the part of HTTP request called `description` (because
link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] does not define a value, the field name is used),
while the `file` field will contain data about the uploaded file in the `image` part of HTTP request.
NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/multipart/FileUpload.html[`FileUpload`]
provides access to various metadata of the uploaded file. If however all you need is a handle to the uploaded file, `java.nio.file.Path` or `java.io.File` could be used.
NOTE: When access to all uploaded files without specifying the form names is needed, RESTEasy Reactive allows the use of `@RestForm List`, where it is important to **not** set a name for the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] annotation.
NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PartType.html[`@PartType`] is used to aid
in deserialization of the corresponding part of the request into the desired Java type. It is very useful when
for example the corresponding body part is JSON and needs to be converted to a POJO.
This POJO could be used in a Resource method like so:
[source,java]
----
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.reactive.MultipartForm;
@Path(""multipart"")
public class Endpoint {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path(""form"")
public String form(@MultipartForm FormData formData) {
// return something
}
}
----
The use of link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] as
method parameter makes RESTEasy Reactive handle the request as a multipart form request.
TIP: The use of `@MultipartForm` is actually unnecessary as RESTEasy Reactive can infer this information from the use of `@Consumes(MediaType.MULTIPART_FORM_DATA)`
WARNING: When handling file uploads, it is very important to move the file to permanent storage (like a database, a dedicated file system or a cloud storage) in your code that handles the POJO.
Otherwise, the file will no longer be accessible when the request terminates.
Moreoever if `quarkus.http.body.delete-uploaded-files-on-end` is set to true, Quarkus will delete the uploaded file when the HTTP response is sent. If the setting is disabled,
the file will reside on the file system of the server (in the directory defined by the `quarkus.http.body.uploads-directory` configuration option), but as the uploaded files are saved
with a UUID file name and no additional metadata is saved, these files are essentially a random dump of files.
Similarly, RESTEasy Reactive can produce Multipart Form data to allow users download files from the server. For example, we could write a POJO
that will hold the information we want to expose as:
[source,java]
----
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.reactive.PartType;
import org.jboss.resteasy.reactive.RestForm;
public class DownloadFormData {
@RestForm
String name;
@RestForm
@PartType(MediaType.APPLICATION_OCTET_STREAM)
File file;
}
----
And then expose this POJO via a Resource like so:
[source,java]
----
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path(""multipart"")
public class Endpoint {
@GET
@Produces(MediaType.MULTIPART_FORM_DATA)
@Path(""file"")
public DownloadFormData getFile() {
// return something
}
}
----
WARNING: For the time being, returning Multipart data is limited to be blocking endpoints.
=== Returning a response body
In order to return an HTTP response, simply return the resource you want from your method. The method
return type and its optional content type will be used to decide how to serialise it to the HTTP
response (see <> for more advanced information).
You can return any of the pre-defined types that you can read from the <>,
and any other type will be mapped <>.
In addition, the following return types are also supported:
.Table Additional response body parameter type
|===
|Type|Usage
|link:{jdkapi}/java/nio/file/Path.html[`Path`]
|The contents of the file specified by the given path
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PathPart.html[`PathPart`]
|The partial contents of the file specified by the given path
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/FilePart.html[`FilePart`]
|The partial contents of a file
|link:{vertxapi}/io/vertx/core/file/AsyncFile.html[`AsyncFile`]
|Vert.x AsyncFile, which can be in full, or partial
|===
Alternately, you can also return a <> such as link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`],
link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] or
link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`]
that resolve to one of the mentioned return types.
=== Setting other response properties
==== Manually setting the response
If you need to set more properties on the HTTP response than just the body, such as the status code
or headers, you can make your method return `org.jboss.resteasy.reactive.RestResponse` from a resource method.
An example of this could look like:
[source,java]
----
package org.acme.rest;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import org.jboss.resteasy.reactive.RestResponse;
import org.jboss.resteasy.reactive.RestResponse.ResponseBuilder;
@Path("""")
public class Endpoint {
@GET
public RestResponse hello() {
// HTTP OK status with text/plain content type
return ResponseBuilder.ok(""Hello, World!"", MediaType.TEXT_PLAIN_TYPE)
// set a response header
.header(""X-FroMage"", ""Camembert"")
// set the Expires response header to two days from now
.expires(Date.from(Instant.now().plus(Duration.ofDays(2))))
// send a new cookie
.cookie(new NewCookie(""Flavour"", ""praliné""))
// end of builder API
.build();
}
}
----
NOTE: You can also use the JAX-RS type link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] but it is
not strongly typed to your entity.
==== Using annotations
Alternatively, if you only need to set the status code and / or HTTP headers with static values, you can use `@org.jboss.resteasy.reactive.ResponseStatus` and /or `ResponseHeader` respectively.
An example of this could look like:
[source,java]
----
package org.acme.rest;
import org.jboss.resteasy.reactive.Header;
import org.jboss.resteasy.reactive.ResponseHeaders;
import org.jboss.resteasy.reactive.ResponseStatus;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("""")
public class Endpoint {
@ResponseStatus(201)
@ResponseHeader(name = ""X-FroMage"", value = ""Camembert"")
@GET
public String hello() {
return ""Hello, World!"";
}
}
----
=== Async/reactive support
[[reactive]]
If your endpoint method needs to accomplish an asynchronous or reactive task before
being able to answer, you can declare your method to return the
link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]), in which
case the current HTTP request will be automatically suspended after your method, until
the returned link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] instance resolves to a value,
which will be mapped to a response exactly according to the previously described rules:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import io.smallrye.mutiny.Uni;
@Path(""escoffier"")
public class Endpoint {
@GET
public Uni culinaryGuide() {
return Book.findByIsbn(""978-2081229297"");
}
}
----
This allows you to not block the event-loop thread while the book is being fetched from the
database, and allows Quarkus to serve more requests until your book is ready to
be sent to the client and terminate this request. Check out our
<> for more information.
The link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] return
type is also supported.
=== Streaming support
If you want to stream your response element by element, you can make your endpoint method return a
link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]).
This is especially useful for streaming text or binary data.
This example, using https://github.com/quarkiverse/quarkus-reactive-messaging-http[Reactive Messaging HTTP] shows how to stream
text data:
[source,java]
----
package org.acme.rest;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.eclipse.microprofile.reactive.messaging.Channel;
import io.smallrye.mutiny.Multi;
@Path(""logs"")
public class Endpoint {
@Inject
@Channel(""log-out"")
Multi logs;
@GET
public Multi streamLogs() {
return logs;
}
}
----
NOTE: Response filters are not invoked on streamed responses, because they would give a false
impression that you can set headers or HTTP status codes, which is not true after the initial
response.
=== Server-Sent Event (SSE) support
If you want to stream JSON objects in your response, you can use
https://html.spec.whatwg.org/multipage/server-sent-events.html[Server-Sent Events]
by just annotating your endpoint method with
link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces(MediaType.SERVER_SENT_EVENTS)`]
and specifying that each element should be <> with
`@RestStreamElementType(MediaType.APPLICATION_JSON)`.
[source,java]
----
package org.acme.rest;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.reactive.RestStreamElementType;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import io.smallrye.reactive.messaging.annotations.Channel;
@Path(""escoffier"")
public class Endpoint {
// Inject our Book channel
@Inject
@Channel(""book-out"")
Multi books;
@GET
// Send the stream over SSE
@Produces(MediaType.SERVER_SENT_EVENTS)
// Each element will be sent as JSON
@RestStreamElementType(MediaType.APPLICATION_JSON)
public Multi stream() {
return books;
}
}
----
=== Controlling HTTP Caching features
RESTEasy Reactive provides the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`]
and link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`] annotations to facilitate
handling HTTP caching semantics, i.e. setting the 'Cache-Control' HTTP header.
These annotations can be placed either on a Resource Method or a Resource Class (in which case it applies to all Resource Methods of the class that do *not* contain the same annotation) and allow users
to return domain objects and not have to deal with building up the `Cache-Control` HTTP header explicitly.
While link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`]
builds a complex `Cache-Control` header, link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`]
is a simplified notation to say that you don't want anything cached; i.e. `Cache-Control: nocache`.
NOTE: More information on the `Cache-Control` header and be found in link:https://datatracker.ietf.org/doc/html/rfc7234[RFC 7234]
=== Accessing context objects
[[context-objects]]
There are a number of contextual objects that the framework will give you, if your endpoint
method takes parameters of the following type:
.Table Context object
|===
|Type|Usage
|link:{jaxrsapi}/javax/ws/rs/core/HttpHeaders.html[`HttpHeaders`]
|All the request headers
|link:{jaxrsapi}/javax/ws/rs/container/ResourceInfo.html[`ResourceInfo`]
|Information about the current endpoint method and class (requires reflection)
|link:{jaxrsapi}/javax/ws/rs/core/SecurityContext.html[`SecurityContext`]
|Access to the current user and roles
|link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/SimpleResourceInfo.html[`SimpleResourceInfo`]
|Information about the current endpoint method and class (no reflection required)
|link:{jaxrsapi}/javax/ws/rs/core/UriInfo.html[`UriInfo`]
|Provides information about the current endpoint and application URI
|link:{jaxrsapi}/javax/ws/rs/core/Application.html[`Application`]
|Advanced: Current JAX-RS application class
|link:{jaxrsapi}/javax/ws/rs/core/Configuration.html[`Configuration`]
|Advanced: Configuration about the deployed JAX-RS application
|link:{jaxrsapi}/javax/ws/rs/ext/Providers.html[`Providers`]
|Advanced: Runtime access to JAX-RS providers
|link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`]
|Advanced: Access to the current HTTP method and <>
|link:{jaxrsapi}/javax/ws/rs/core/ResourceContext.html[`ResourceContext`]
|Advanced: access to instances of endpoints
|link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerRequestContext.html[`ServerRequestContext`]
|Advanced: RESTEasy Reactive access to the current request/response
|link:{jaxrsapi}/javax/ws/rs/sse/Sse.html[`Sse`]
|Advanced: Complex SSE use-cases
|link:{vertxapi}/io/vertx/core/http/HttpServerRequest.html[`HttpServerRequest`]
|Advanced: Vert.x HTTP Request
|link:{vertxapi}/io/vertx/core/http/HttpServerResponse.html[`HttpServerResponse`]
|Advanced: Vert.x HTTP Response
|===
For example, here is how you can return the name of the currently logged-in user:
[source,java]
----
package org.acme.rest;
import java.security.Principal;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.SecurityContext;
@Path(""user"")
public class Endpoint {
@GET
public String userName(SecurityContext security) {
Principal user = security.getUserPrincipal();
return user != null ? user.getName() : """";
}
}
----
You can also inject those context objects using
https://javadoc.io/static/javax.inject/javax.inject/1/javax/inject/Inject.html[`@Inject`] on fields of the same
type:
[source,java]
----
package org.acme.rest;
import java.security.Principal;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.SecurityContext;
@Path(""user"")
public class Endpoint {
@Inject
SecurityContext security;
@GET
public String userName() {
Principal user = security.getUserPrincipal();
return user != null ? user.getName() : """";
}
}
----
Or even on your endpoint constructor:
[source,java]
----
package org.acme.rest;
import java.security.Principal;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.SecurityContext;
@Path(""user"")
public class Endpoint {
SecurityContext security;
Endpoint(SecurityContext security) {
this.security = security;
}
@GET
public String userName() {
Principal user = security.getUserPrincipal();
return user != null ? user.getName() : """";
}
}
----
=== JSON serialisation
[[json]]
Instead of importing `io.quarkus:quarkus-resteasy-reactive`, you can import either of the following modules to get support for JSON:
.Table Context object
|===
|GAV|Usage
|`io.quarkus:quarkus-resteasy-reactive-jackson`
|https://github.com/FasterXML/jackson[Jackson support]
|`io.quarkus:quarkus-resteasy-reactive-jsonb`
|https://eclipse-ee4j.github.io/jsonb-api/[JSON-B support]
|===
In both cases, importing those modules will allow HTTP message bodies to be read from JSON
and serialised to JSON, for <>.
==== Advanced Jackson-specific features
When using the `quarkus-resteasy-reactive-jackson` extension there are some advanced features that RESTEasy Reactive supports.
[[secure-serialization]]
===== Secure serialization
When used with Jackson to perform JSON serialization, RESTEasy Reactive provides the ability to limit the set of fields that are serialized based on the roles of the current user.
This is achieved by simply annotating the fields (or getters) of the POJO being returned with `@io.quarkus.resteasy.reactive.jackson.SecureField`.
A simple example could be the following:
Assume we have a POJO named `Person` which looks like so:
[source,java]
----
package org.acme.rest;
import io.quarkus.resteasy.reactive.jackson.SecureField;
public class Person {
@SecureField(rolesAllowed = ""admin"")
private final Long id;
private final String first;
private final String last;
public Person(Long id, String first, String last) {
this.id = id;
this.first = first;
this.last = last;
}
public Long getId() {
return id;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
}
----
A very simple JAX-RS Resource that uses `Person` could be:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path(""person"")
public class Person {
@Path(""{id}"")
@GET
public Person getPerson(Long id) {
return new Person(id, ""foo"", ""bar"");
}
}
----
Assuming security has been set up for the application (see our xref:security.adoc[guide] for more details), when a user with the `admin` role
performs an HTTP GET on `/person/1` they will receive:
[source,json]
----
{
""id"": 1,
""first"": ""foo"",
""last"": ""bar""
}
----
as the response.
Any user however that does not have the `admin` role will receive:
[source,json]
----
{
""first"": ""foo"",
""last"": ""bar""
}
----
NOTE: No additional configuration needs to be applied for this secure serialization to take place. However, users can use the `@io.quarkus.resteasy.reactive.jackson.EnableSecureSerialization` and `@io.quarkus.resteasy.reactive.jackson.DisableSecureSerialization`
annotation to opt-in or out for specific JAX-RS Resource classes or methods.
===== @JsonView support
JAX-RS methods can be annotated with https://fasterxml.github.io/jackson-annotations/javadoc/2.10/com/fasterxml/jackson/annotation/JsonView.html[@JsonView]
in order to customize the serialization of the returned POJO, on a per method-basis. This is best explained with an example.
A typical use of `@JsonView` is to hide certain fields on certain methods. In that vein, let's define two views:
[source,java]
----
public class Views {
public static class Public {
}
public static class Private extends Public {
}
}
----
Let's assume we have the `User` POJO on which we want to hide some field during serialization. A simple example of this is:
[source,java]
----
public class User {
@JsonView(Views.Private.class)
public int id;
@JsonView(Views.Public.class)
public String name;
}
----
Depending on the JAX-RS method that returns this user, we might want to exclude the `id` field from serialization - for example you might want an insecure method
to not expose this field. The way we can achieve that in RESTEasy Reactive is shown in the following example:
[source,java]
----
@JsonView(Views.Public.class)
@GET
@Path(""/public"")
public User userPublic() {
return testUser();
}
@JsonView(Views.Private.class)
@GET
@Path(""/private"")
public User userPrivate() {
return testUser();
}
----
When the result the `userPublic` method is serialized, the `id` field will not be contained in the response as the `Public` view does not include it.
The result of `userPrivate` however will include the `id` as expected when serialized.
===== Completely customized per method serialization
There are times when you need to completely customize the serialization of a POJO on a per JAX-RS method basis. For such use cases, the `@io.quarkus.resteasy.reactive.jackson.CustomSerialization` annotation
is a great tool, as it allows you to configure a per-method `com.fasterxml.jackson.databind.ObjectWriter` which can be configured at will.
Here is an example use case:
[source,java]
----
@CustomSerialization(UnquotedFields.class)
@GET
@Path(""/invalid-use-of-custom-serializer"")
public User invalidUseOfCustomSerializer() {
return testUser();
}
----
where `UnquotedFields` is a `BiFunction` defined as so:
[source,java]
----
public static class UnquotedFields implements BiFunction {
@Override
public ObjectWriter apply(ObjectMapper objectMapper, Type type) {
return objectMapper.writer().without(JsonWriteFeature.QUOTE_FIELD_NAMES);
}
}
----
Essentially what this class does is force Jackson to not include quotes in the field names.
It is important to note that this customization is only performed for the serialization of the JAX-RS methods that use `@CustomSerialization(UnquotedFields.class)`.
=== XML serialisation
[[xml]]
To enable XML support, add the `quarkus-resteasy-reactive-jaxb` extension to your project.
.Table Context object
|===
|GAV|Usage
|`io.quarkus:quarkus-resteasy-reactive-jaxb`
|https://javaee.github.io/jaxb-v2/[XML support]
|===
Importing this module will allow HTTP message bodies to be read from XML
and serialised to XML, for <>.
== More advanced usage
Here are some more advanced topics that you may not need to know about initially, but
could prove useful for more complex use cases.
=== Execution model, blocking, non-blocking
[[execution-model]]
RESTEasy Reactive is implemented using two main thread types:
- Event-loop threads: which are responsible, among other things, for reading bytes from the HTTP request and
writing bytes back to the HTTP response
- Worker threads: they are pooled and can be used to offload long-running operations
The event-loop threads (also called IO threads) are responsible for actually performing all the IO
operations in an asynchronous way, and to trigger any listener interested in the completion of those
IO operations.
By default, the thread RESTEasy Reactive will run endpoint methods on depends on the signature of the method.
If a method returns one of the following types then it is considered non-blocking, and will be run on the IO thread
by default:
- `io.smallrye.mutiny.Uni`
- `io.smallrye.mutiny.Multi`
- `java.util.concurrent.CompletionStage`
- `org.reactivestreams.Publisher`
- Kotlin `suspended` methods
This 'best guess' approach means that the majority of operations will run on the correct thread by default. If you are
writing reactive code then your method will generally return one of these types, and will be executed on the IO thread.
If you are writing blocking code your methods will generally return the result directly, and these will be run on a worker
thread.
You can override this behaviour using the
https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/Blocking.html[`@Blocking`]
and
https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/NonBlocking.html[`@NonBlocking`]
annotations. This can be applied at the method, class or `javax.ws.rs.core.Application` level.
The example below will override the default behaviour and always run on a worker thread, even though it returns a `Uni`.
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import io.smallrye.common.annotation.Blocking;
@Path(""yawn"")
public class Endpoint {
@Blocking
@GET
public Uni blockingHello() throws InterruptedException {
// do a blocking operation
Thread.sleep(1000);
return Uni.createFrom().item(""Yaaaawwwwnnnnnn…"");
}
}
----
Most of the time, there are ways to achieve the same blocking operations in an asynchronous/reactive
way, using https://smallrye.io/smallrye-mutiny/[Mutiny], http://hibernate.org/reactive/[Hibernate Reactive]
or any of the xref:quarkus-reactive-architecture.adoc#quarkus-extensions-enabling-reactive[Quarkus Reactive extensions] for example:
[source,java]
----
package org.acme.rest;
import java.time.Duration;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import io.smallrye.mutiny.Uni;
@Path(""yawn"")
public class Endpoint {
@GET
public Uni blockingHello() throws InterruptedException {
return Uni.createFrom().item(""Yaaaawwwwnnnnnn…"")
// do a non-blocking sleep
.onItem().delayIt().by(Duration.ofSeconds(2));
}
}
----
If a method or class is annotated with `javax.transaction.Transactional` then it will also be treated as a blocking
method. This is because JTA is a blocking technology, and is generally used with other blocking technology such as
Hibernate and JDBC. An explicit `@Blocking` or `@NonBlocking` on the class will override this behaviour.
==== Overriding the default behaviour
If you want to override the default behaviour you can annotate a `javax.ws.rs.core.Application` subclass in your application
with `@Blocking` or `@NonBlocking`, and this will set the default for every method that does not have an explicit annotation.
Behaviour can still be overridden on a class or method level by annotating them directly, however all endpoints without
an annotation will now follow the default, no matter their method signature.
=== Exception mapping
If your application needs to return non-nominal HTTP codes in error cases, the best is
to throw exceptions that will result in the proper HTTP response being sent by the
framework using link:{jaxrsapi}/javax/ws/rs/WebApplicationException.html[`WebApplicationException`] or any of its subtypes:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Path;
@Path(""fromages/{fromage}"")
public class Endpoint {
@GET
public String findFromage(String fromage) {
if(fromage == null)
// send a 400
throw new BadRequestException();
if(!fromage.equals(""camembert""))
// send a 404
throw new NotFoundException(""Unknown cheese: "" + fromage);
return ""Camembert is a very nice cheese"";
}
}
----
If your endpoint method is delegating calls to another service layer which
does not know of JAX-RS, you need a way to turn service exceptions to an
HTTP response, and you can do that using the
link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerExceptionMapper.html[`@ServerExceptionMapper`]
annotation on a method, with one parameter of the exception type you want to handle, and turning
that exception into a link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] (or a
link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`]):
[source,java]
----
package org.acme.rest;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.jboss.resteasy.reactive.RestResponse;
class UnknownCheeseException extends RuntimeException {
public final String name;
public UnknownCheeseException(String name) {
this.name = name;
}
}
@ApplicationScoped
class CheeseService {
private static final Map cheeses =
Map.of(""camembert"", ""Camembert is a very nice cheese"",
""gouda"", ""Gouda is acceptable too, especially with cumin"");
public String findCheese(String name) {
String ret = cheeses.get(name);
if(ret != null)
return ret;
throw new UnknownCheeseException(name);
}
}
@Path(""fromages/{fromage}"")
public class Endpoint {
@Inject
CheeseService cheeses;
@ServerExceptionMapper
public RestResponse mapException(UnknownCheeseException x) {
return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name);
}
@GET
public String findFromage(String fromage) {
if(fromage == null)
// send a 400
throw new BadRequestException();
return cheeses.findCheese(fromage);
}
}
----
NOTE: exception mappers defined in REST endpoint classes will only be called if the
exception is thrown in the same class. If you want to define global exception mappers,
simply define them outside a REST endpoint class:
[source,java]
----
package org.acme.rest;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.jboss.resteasy.reactive.RestResponse;
class ExceptionMappers {
@ServerExceptionMapper
public RestResponse mapException(UnknownCheeseException x) {
return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name);
}
}
----
You can also declare link:{jaxrsspec}#exceptionmapper[exception mappers in the JAX-RS way].
Your exception mapper may declare any of the following parameter types:
.Table Exception mapper parameters
|===
|Type|Usage
|An exception type
|Defines the exception type you want to handle
|Any of the <>
|
|link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`]
|A context object to access the current request
|===
It may declare any of the following return types:
.Table Exception mapper return types
|===
|Type|Usage
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`]
|The response to send to the client when the exception occurs
|link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`]
|An asynchronous response to send to the client when the exception occurs
|===
=== Request or response filters
You can declare functions which are invoked in the following phases of the request processing:
- Before the endpoint method is identified: pre-routing request filter
- After routing, but before the endpoint method is called: normal request filter
- After the endpoint method is called: response filter
These filters allow you to do various things such as examine the request URI,
HTTP method, influence routing, look or change request headers, abort the request,
or modify the response.
Request filters can be declared with the
link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerRequestFilter.html[`@ServerRequestFilter`]
annotation:
[source,java]
----
import java.util.Optional;
class Filters {
@ServerRequestFilter(preMatching = true)
public void preMatchingFilter(ContainerRequestContext requestContext) {
// make sure we don't lose cheese lovers
if(""yes"".equals(requestContext.getHeaderString(""Cheese""))) {
requestContext.setRequestUri(URI.create(""/cheese""));
}
}
@ServerRequestFilter
public Optional> getFilter(ContainerRequestContext ctx) {
// only allow GET methods for now
if(ctx.getMethod().equals(HttpMethod.GET)) {
return Optional.of(RestResponse.status(Response.Status.METHOD_NOT_ALLOWED));
}
return Optional.empty();
}
}
----
[IMPORTANT]
====
Request filters are usually executed on the same thread that the method that handles the request will be executed.
That means that if the method servicing the request is annotated with `@Blocking`, then the filters will also be run
on the worker thread.
If the method is annotated with `@NonBlocking` (or is not annotated at all), then the filters will also be run
on the same event-loop thread.
If however a filter needs to be run on the event-loop despite the fact that the method servicing the request will be
run on a worker thread, then `@ServerRequestFilter(nonBlocking=true)` can be used.
Note however, that these filters need to be run before **any** filter that does not use that setting and would run on a worker thread.
====
Similarly, response filters can be declared with the
link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerResponseFilter.html[`@ServerResponseFilter`]
annotation:
[source,java]
----
class Filters {
@ServerResponseFilter
public void getFilter(ContainerResponseContext responseContext) {
Object entity = responseContext.getEntity();
if(entity instanceof String) {
// make it shout
responseContext.setEntity(((String)entity).toUpperCase());
}
}
}
----
You can also link:{jaxrsspec}#filters[declare request and response filters in the JAX-RS way].
Your filters may declare any of the following parameter types:
.Table Filter parameters
|===
|Type|Usage
|Any of the <>
|
|link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`]
|A context object to access the current request
|link:{jaxrsapi}/javax/ws/rs/container/ContainerResponseContext.html[`ContainerResponseContext`]
|A context object to access the current response
|link:{jdkapi}/java/lang/Throwable.html[`Throwable`]
|Any thrown exception, or `null` (only for response filters)
|===
It may declare any of the following return types:
.Table Filter return types
|===
|Type|Usage
|link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse>`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`]
|The response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed
|link:{jdkapi}/java/util/Optional.html[`Optional>`] or link:{jdkapi}/java/util/Optional.html[`Optional`]
|An optional response to send to the client instead of continuing the filter chain, or an empty value if the filter chain should proceed
|link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`]
|An asynchronous response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed
|===
NOTE: You can restrict the Resource methods for which a filter runs, by using link:{jaxrsapi}/javax/ws/rs/NameBinding.html[`@NameBinding`] meta-annotations.
=== Readers and Writers: mapping entities and HTTP bodies
[[readers-writers]]
Whenever your endpoint methods return a object (of when they return a
link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse>`]
or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] with
an entity), RESTEasy Reactive will look for a way to map that into an HTTP response body.
Similarly, whenever your endpoint method takes an object as parameter, we will look for
a way to map the HTTP request body into that object.
This is done via a pluggable system of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyReader.html[`MessageBodyReader`]
and link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] interfaces,
which are responsible for defining which Java type they map from/to, for which media types,
and how they turn HTTP bodies to/from Java instances of that type.
For example, if we have our own `FroMage` type on our endpoint:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
class FroMage {
public String name;
public FroMage(String name) {
this.name = name;
}
}
@Path(""cheese"")
public class Endpoint {
@GET
public FroMage sayCheese() {
return new FroMage(""Cheeeeeese"");
}
@PUT
public void addCheese(FroMage fromage) {
System.err.println(""Received a new cheese: "" + fromage.name);
}
}
----
Then we can define how to read and write it with our body reader/writers, annotated
with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]:
[source,java]
----
package org.acme.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
@Provider
public class FroMageBodyHandler implements MessageBodyReader,
MessageBodyWriter {
@Override
public boolean isWriteable(Class> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return type == FroMage.class;
}
@Override
public void writeTo(FroMage t, Class> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap httpHeaders,
OutputStream entityStream)
throws IOException, WebApplicationException {
entityStream.write((""[FroMageV1]"" + t.name)
.getBytes(StandardCharsets.UTF_8));
}
@Override
public boolean isReadable(Class> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return type == FroMage.class;
}
@Override
public FroMage readFrom(Class type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
String body = new String(entityStream.readAllBytes(), StandardCharsets.UTF_8);
if(body.startsWith(""[FroMageV1]""))
return new FroMage(body.substring(11));
throw new IOException(""Invalid fromage: "" + body);
}
}
----
If you want to get the most performance our of your writer, you can extend the
link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerMessageBodyWriter.html[`ServerMessageBodyWriter`]
instead of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`]
where you will be able to use less reflection and bypass the blocking IO layer:
[source,java]
----
package org.acme.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter;
import org.jboss.resteasy.reactive.server.spi.ServerRequestContext;
@Provider
public class FroMageBodyHandler implements MessageBodyReader,
ServerMessageBodyWriter {
// …
@Override
public boolean isWriteable(Class> type, ResteasyReactiveResourceInfo target,
MediaType mediaType) {
return type == FroMage.class;
}
@Override
public void writeResponse(FroMage t, ServerRequestContext context)
throws WebApplicationException, IOException {
context.serverResponse().end(""[FroMageV1]"" + t.name);
}
}
----
NOTE: You can restrict which content-types your reader/writer apply to by adding
link:{jaxrsapi}/javax/ws/rs/Consumes.html[`Consumes`]/link:{jaxrsapi}/javax/ws/rs/Produces.html[`Produces`] annotations
on your provider class.
=== Reader and Writer interceptors
Just as you can intercept requests and responses, you can also intercept readers and writers, by
extending the link:{jaxrsapi}/javax/ws/rs/ext/ReaderInterceptor.html[`ReaderInterceptor`] or
link:{jaxrsapi}/javax/ws/rs/ext/WriterInterceptor.html[`WriterInterceptor`] on a class annotated with
link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`].
If we look at this endpoint:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@Path(""cheese"")
public class Endpoint {
@GET
public String sayCheese() {
return ""Cheeeeeese"";
}
@PUT
public void addCheese(String fromage) {
System.err.println(""Received a new cheese: "" + fromage);
}
}
----
We can add reader and writer interceptors like this:
[source,java]
----
package org.acme.rest;
import java.io.IOException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
@Provider
public class FroMageIOInterceptor implements ReaderInterceptor, WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
System.err.println(""Before writing "" + context.getEntity());
context.proceed();
System.err.println(""After writing "" + context.getEntity());
}
@Override
public Object aroundReadFrom(ReaderInterceptorContext context)
throws IOException, WebApplicationException {
System.err.println(""Before reading "" + context.getGenericType());
Object entity = context.proceed();
System.err.println(""After reading "" + entity);
return entity;
}
}
----
=== Parameter mapping
All <> can be declared as link:{jdkapi}/java/lang/String.html[`String`], but also
any of the following types:
- Types for which a link:{jaxrsapi}/javax/ws/rs/ext/ParamConverter.html[`ParamConverter`] is available via a registered
link:{jaxrsapi}/javax/ws/rs/ext/ParamConverterProvider.html[`ParamConverterProvider`].
- Primitive types.
- Types that have a constructor that accepts a single link:{jdkapi}/java/lang/String.html[`String`] argument.
- Types that have a static method named `valueOf` or `fromString` with a single link:{jdkapi}/java/lang/String.html[`String`] argument
that return an instance of the type. If both methods are present then `valueOf` will be used unless
the type is an `enum` in which case `fromString` will be used.
- link:{jdkapi}/java/util/List.html[`List`], link:{jdkapi}/java/util/Set.html[`Set`], or
link:{jdkapi}/java/util/SortedSet.html[`SortedSet`], where `T` satisfies any above criterion.
The following example illustrates all those possibilities:
[source,java]
----
package org.acme.rest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.reactive.RestQuery;
@Provider
class MyConverterProvider implements ParamConverterProvider {
@Override
public ParamConverter getConverter(Class rawType, Type genericType,
Annotation[] annotations) {
// declare a converter for this type
if(rawType == Converter.class) {
return (ParamConverter) new MyConverter();
}
return null;
}
}
// this is my custom converter
class MyConverter implements ParamConverter {
@Override
public Converter fromString(String value) {
return new Converter(value);
}
@Override
public String toString(Converter value) {
return value.value;
}
}
// this uses a converter
class Converter {
String value;
Converter(String value) {
this.value = value;
}
}
class Constructor {
String value;
// this will use the constructor
public Constructor(String value) {
this.value = value;
}
}
class ValueOf {
String value;
private ValueOf(String value) {
this.value = value;
}
// this will use the valueOf method
public static ValueOf valueOf(String value) {
return new ValueOf(value);
}
}
@Path(""hello"")
public class Endpoint {
@Path(""{converter}/{constructor}/{primitive}/{valueOf}"")
@GET
public String convertions(Converter converter, Constructor constructor,
int primitive, ValueOf valueOf,
@RestQuery List list) {
return converter + ""/"" + constructor + ""/"" + primitive
+ ""/"" + valueOf + ""/"" + list;
}
}
----
==== Handling dates
RESTEasy Reactive supports the use of the implementations of `java.time.Temporal` (like `java.time.LocalDateTime`) as query, path or form params. Furthermore it provides the `@org.jboss.resteasy.reactive.DateFormat` annotation which can be used to
set a custom expected pattern (otherwise the JDK's default format for each type is used implicitly).
=== Preconditions
https://tools.ietf.org/html/rfc7232[HTTP allows requests to be conditional], based on a number of
conditions, such as:
- Date of last resource modification
- A resource tag, similar to a hash code of the resource to designate its state or version
Let's see how you can do conditional request validation using the
link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] context object:
[source,java]
----
package org.acme.rest;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path(""conditional"")
public class Endpoint {
// It's important to keep our date on seconds because that's how it's sent to the
// user in the Last-Modified header
private Date date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS));
private int version = 1;
private EntityTag tag = new EntityTag(""v1"");
private String resource = ""Some resource"";
@GET
public Response get(Request request) {
// first evaluate preconditions
ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag);
if(conditionalResponse != null)
return conditionalResponse.build();
// preconditions are OK
return Response.ok(resource)
.lastModified(date)
.tag(tag)
.build();
}
@PUT
public Response put(Request request, String body) {
// first evaluate preconditions
ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag);
if(conditionalResponse != null)
return conditionalResponse.build();
// preconditions are OK, we can update our resource
resource = body;
date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS));
version++;
tag = new EntityTag(""v"" + version);
return Response.ok(resource)
.lastModified(date)
.tag(tag)
.build();
}
}
----
When we call `GET /conditional` the first time, we will get this response:
[source]
----
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
ETag: ""v1""
Last-Modified: Wed, 09 Dec 2020 16:10:19 GMT
Content-Length: 13
Some resource
----
So now if we want to check if we need to fetch a new version, we can make the following request:
[source]
----
GET /conditional HTTP/1.1
Host: localhost:8080
If-Modified-Since: Wed, 09 Dec 2020 16:10:19 GMT
----
And we would get the following response:
[source]
----
HTTP/1.1 304 Not Modified
----
Because the resource has not been modified since that date. This saves on sending the resource,
but can also help your users detect concurrent modification, for example, let's suppose that one
client wants to update the resource, but another user has modified it since. You can follow the
previous `GET` request with this update:
[source]
----
PUT /conditional HTTP/1.1
Host: localhost:8080
If-Unmodified-Since: Wed, 09 Dec 2020 16:25:43 GMT
If-Match: v1
Content-Length: 8
Content-Type: text/plain
newstuff
----
And if some other user has modified the resource between your `GET` and your `PUT` you would
get this answer back:
[source]
----
HTTP/1.1 412 Precondition Failed
ETag: ""v2""
Content-Length: 0
----
=== Negotiation
One of the main ideas of REST (https://tools.ietf.org/html/rfc7231#section-3.4[and HTTP]) is that
your resource is independent from its representation, and
that both the client and server are free to represent their resources in as many media types as
they want. This allows the server to declare support for multiple representations and let the
client declare which ones it supports and get served something appropriate.
The following endpoint supports serving cheese in plain text or JSON:
[source,java]
----
package org.acme.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.fasterxml.jackson.annotation.JsonCreator;
class FroMage {
public String name;
@JsonCreator
public FroMage(String name) {
this.name = name;
}
@Override
public String toString() {
return ""Cheese: "" + name;
}
}
@Path(""negotiated"")
public class Endpoint {
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
@GET
public FroMage get() {
return new FroMage(""Morbier"");
}
@Consumes(MediaType.TEXT_PLAIN)
@PUT
public FroMage putString(String cheese) {
return new FroMage(cheese);
}
@Consumes(MediaType.APPLICATION_JSON)
@PUT
public FroMage putJson(FroMage fromage) {
return fromage;
}
}
----
The user will be able to select which representation it gets with the
link:{httpspec}#section-5.3.2[`Accept`] header, in the case of JSON:
[source,sh]
----
> GET /negotiated HTTP/1.1
> Host: localhost:8080
> Accept: application/json
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 18
<
< {""name"":""Morbier""}
----
And for text:
[source,sh]
----
> GET /negotiated HTTP/1.1
> Host: localhost:8080
> Accept: text/plain
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Content-Length: 15
<
< Cheese: Morbier
----
Similarly, you can `PUT` two different representations. JSON:
[source,sh]
----
> PUT /negotiated HTTP/1.1
> Host: localhost:8080
> Content-Type: application/json
> Content-Length: 16
>
> {""name"": ""brie""}
< HTTP/1.1 200 OK
< Content-Type: application/json;charset=UTF-8
< Content-Length: 15
<
< {""name"":""brie""}
----
Or plain text:
[source,sh]
----
> PUT /negotiated HTTP/1.1
> Host: localhost:8080
> Content-Type: text/plain
> Content-Length: 9
>
> roquefort
< HTTP/1.1 200 OK
< Content-Type: application/json;charset=UTF-8
< Content-Length: 20
<
< {""name"":""roquefort""}
----
== Include/Exclude JAX-RS classes with build time conditions
Quarkus enables the inclusion or exclusion of JAX-RS Resources, Providers and Features directly thanks to build time conditions in the same that it does for CDI beans.
Thus, the various JAX-RS classes can be annotated with profile conditions (`@io.quarkus.arc.profile.IfBuildProfile` or `@io.quarkus.arc.profile.UnlessBuildProfile`) and/or with property conditions (`io.quarkus.arc.properties.IfBuildProperty` or `io.quarkus.arc.properties.UnlessBuildProperty`) to indicate to Quarkus at build time under which conditions these JAX-RS classes should be included.
In the following example, Quarkus includes the endpoint `sayHello` if and only if the build profile `app1` has been enabled.
[source,java]
----
@IfBuildProfile(""app1"")
public class ResourceForApp1Only {
@GET
@Path(""sayHello"")
public String sayHello() {
return ""hello"";
}
}
----
Please note that if a JAX-RS Application has been detected and the method `getClasses()` and/or `getSingletons()` has/have been overridden, Quarkus will ignore the build time conditions and consider only what has been defined in the JAX-RS Application.
== RESTEasy Reactive client
In addition to the Server side, RESTEasy Reactive comes with a new MicroProfile Rest Client implementation that is non-blocking at its core.
Please note that the `quarkus-rest-client` extension may not be used with RESTEasy Reactive, use `quarkus-rest-client-reactive` instead.
See the xref:rest-client-reactive.adoc[REST Client Reactive Guide] for more information about the reactive REST client.
",16227,True,2828.218477172241,median
"[[spring-cloud-dataflow-task]]
= Tasks
[partintro]
--
This section goes into more detail about how you can orchestrate https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] applications on Spring Cloud Data Flow.
If you are just starting out with Spring Cloud Data Flow, you should probably read the Getting Started guide for ""`<>`"" , ""`<>`"", ""`<>`"" before diving into this section.
--
[[spring-cloud-dataflow-task-intro]]
== Introduction
A task application is short lived, meaning it stops running on purpose, and can be executed on demand or scheduled for execution.
A use case might be to scrape a web page and write to the database.
The https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] framework is based on Spring Boot and adds the capability for Boot applications to record the lifecycle events of a short lived application such as when it starts, when it ends and the exit status.
The https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#features-task-execution-details[TaskExecution] documentation shows which information is stored in the database.
The entry point for code execution in a Spring Cloud Task application is most often an implementation of Boot's `CommandLineRunner` interface, as shown in this https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#getting-started-writing-the-code[example].
The Spring Batch project is probably what comes to mind for Spring developers writing short lived applications.
Spring Batch provides a much richer set of functionality than Spring Cloud Task and is recommended when processing large volumes of data.
A use case might be to read many CSV files, transform each row of data, and write each transformed row to a database.
Spring Batch provides its own database schema with a much more rich https://docs.spring.io/spring-batch/{spring-batch-doc-version}/reference/html/schema-appendix.html#metaDataSchema[set of information] about the execution of a Spring Batch job.
Spring Cloud Task is integrated with Spring Batch so that if a Spring Cloud Task application defined a Spring Batch `Job`, a link between the Spring Cloud Task and Spring Cloud Batch execution tables is created.
When running Data Flow on your local machine, Tasks are launched in a separate JVM.
When running on Cloud Foundry, tasks are launched using https://docs.cloudfoundry.org/devguide/using-tasks.html[Cloud Foundry's Task] functionality and when running on Kubernetes, tasks are launched using either a `Pod` or a `Job` resource.
== The Lifecycle of a Task
Before we dive deeper into the details of creating Tasks, we need to understand the typical lifecycle for tasks in the context of Spring Cloud Data Flow:
. <>
. <>
. <>
. <>
. <>
. <>
. <>
[[spring-cloud-dataflow-create-task-apps]]
=== Creating a Task Application
While Spring Cloud Task does provide a number of out-of-the-box applications (at https://github.com/spring-cloud-task-app-starters[spring-cloud-task-app-starters]), most task applications require custom development.
To create a custom task application:
. Use the https://start.spring.io[Spring Initializer] to create a new project, making sure to select the following starters:
.. `Cloud Task`: This dependency is the `spring-cloud-starter-task`.
.. `JDBC`: This dependency is the `spring-jdbc` starter.
.. Select your database dependency: Enter the database dependency that Data Flow is currently using. For example: `H2`.
. Within your new project, create a new class to serve as your main class, as follows:
+
[source,java]
----
@EnableTask
@SpringBootApplication
public class MyTask {
public static void main(String[] args) {
SpringApplication.run(MyTask.class, args);
}
}
----
+
. With this class, you need one or more `CommandLineRunner` or `ApplicationRunner` implementations within your application. You can either implement your own or use the ones provided by Spring Boot (there is one for running batch jobs, for example).
. Packaging your application with Spring Boot into an über jar is done through the standard {spring-boot-docs-reference}/html/getting-started-first-application.html#getting-started-first-application-executable-jar[Spring Boot conventions].
The packaged application can be registered and deployed as noted below.
==== Task Database Configuration
CAUTION: When launching a task application, be sure that the database driver that is being used by Spring Cloud Data Flow is also a dependency on the task application.
For example, if your Spring Cloud Data Flow is set to use Postgresql, be sure that the task application also has Postgresql as a dependency.
TIP: When you run tasks externally (that is, from the command line) and you want Spring Cloud Data Flow to show the TaskExecutions in its UI, be sure that common datasource settings are shared among the both.
By default, Spring Cloud Task uses a local H2 instance, and the execution is recorded to the database used by Spring Cloud Data Flow.
[[spring-cloud-dataflow-register-task-apps]]
=== Registering a Task Application
You can register a Task App with the App Registry by using the Spring Cloud Data Flow Shell `app register` command.
You must provide a unique name and a URI that can be resolved to the app artifact. For the type, specify ""task"".
The following listing shows three examples:
[source,bash]
----
dataflow:>app register --name task1 --type task --uri maven://com.example:mytask:1.0.2
dataflow:>app register --name task2 --type task --uri file:///Users/example/mytask-1.0.2.jar
dataflow:>app register --name task3 --type task --uri https://example.com/mytask-1.0.2.jar
----
When providing a URI with the `maven` scheme, the format should conform to the following:
`maven://:[:[:]]:`
If you would like to register multiple apps at one time, you can store them in a properties file where the keys are formatted as `.` and the values are the URIs.
For example, the followinng listing would be a valid properties file:
[source]
----
task.foo=file:///tmp/foo-1.2.1.BUILD-SNAPSHOT.jar
task.bar=file:///tmp/bar-1.2.1.BUILD-SNAPSHOT.jar
----
Then you can use the `app import` command and provide the location of the properties file by using the `--uri` option, as follows:
```
app import --uri file:///tmp/task-apps.properties
```
For example, if you would like to register all out-of-the-box task applications in bulk, you can do so with the following command:
```
dataflow:>app import --uri https://dataflow.spring.io/task-maven-latest
```
You can also pass the `--local` option (which is `TRUE` by default) to indicate whether the properties file location should be resolved within the shell process itself.
If the location should be resolved from the Data Flow Server process, specify `--local false`.
When using either `app register` or `app import`, if a task app is already registered with
the provided name and version, it is not overridden by default. If you would like to override the
pre-existing task app with a different uri or uri-metadata location, then include the `--force` option.
[NOTE]
In some cases, the Resource is resolved on the server side.
In other cases, the URI is passed to a runtime container instance where it is resolved.
Consult the specific documentation of each Data Flow Server for more detail.
[[spring-cloud-dataflow-create-task-definition]]
=== Creating a Task Definition
You can create a task Definition from a task app by providing a definition name as well as
properties that apply to the task execution. Creating a task definition can be done through
the RESTful API or the shell. To create a task definition by using the shell, use the
`task create` command to create the task definition, as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:>task create mytask --definition ""timestamp --format=\\""yyyy\\""""
Created new task 'mytask'
----
A listing of the current task definitions can be obtained through the RESTful API or the shell.
To get the task definition list by using the shell, use the `task list` command.
==== Automating the Creation of Task Definitions
As of version 2.3.0, the Data Flow server can be configured to auto create task definitions by setting `spring.cloud.dataflow.task.autocreate-task-definitions` to `true`.
This is not the default behavior but provided as a convenience.
When this property is enabled, a task launch request can specify the registered task application name as the task name.
If the task application is registered, the server will create a basic task definition that specifies only the app name, as required. This eliminates a manual step equivalent to something like:
[source,bash,subs=attributes]
----
dataflow:>task create mytask --definition ""mytask""
----
Command line arguments and deployment properties can still be specified for each task launch request.
[[spring-cloud-dataflow-task-launch]]
=== Launching a Task
An adhoc task can be launched through the RESTful API or the shell.
To launch an ad-hoc task through the shell, use the `task launch` command, as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:>task launch mytask
Launched task 'mytask'
----
When a task is launched, any properties that need to be passed as command line arguments to the task application can be set when launching the task, as follows:
[source,bash,subs=attributes]
----
dataflow:>task launch mytask --arguments ""--server.port=8080 --custom=value""
----
[NOTE]
The arguments need to be passed as `space` delimited values.
Additional properties meant for a `TaskLauncher` itself can be passed in by using a `--properties` option.
The format of this option is a comma-separated string of properties prefixed with `app..`.
Properties are passed to `TaskLauncher` as application properties.
It is up to an implementation to choose how those are passed into an actual task application.
If the property is prefixed with `deployer` instead of `app`, it is passed to `TaskLauncher` as a deployment property and its meaning may be `TaskLauncher` implementation specific.
`dataflow:>task launch mytask --properties ""deployer.timestamp.custom1=value1,app.timestamp.custom2=value2""`
==== Application properties
Each application takes properties to customize its behavior. As an example, the `timestamp` task `format` setting establishes a output format that is different from the default value.
`dataflow:> task create --definition ""timestamp --format=\\""yyyy\\"""" --name printTimeStamp`
This `timestamp` property is actually the same as the `timestamp.format` property specified by the timestamp application.
Data Flow adds the ability to use the shorthand form `format` instead of `timestamp.format`.
One may also specify the longhand version as well, as shown in the following example:
`dataflow:> task create --definition ""timestamp --timestamp.format=\\""yyyy\\"""" --name printTimeStamp`
This shorthand behavior is discussed more in the section on <>.
If you have <> you can use tab completion in the shell after typing `--` to get a list of candidate property names.
The shell provides tab completion for application properties. The shell command `app info --name --type ` provides additional documentation for all the supported properties. The supported Task `` is task.
NOTE: When restarting Spring Batch Jobs on Kubernetes, you must use the entry point of `shell` or `boot`.
===== Application Properties With Sensitive Information on Kubernetes
When launching task applications where some of the properties may contain sensitive information, use the `shell` or `boot` as the `entryPointStyle`. This is because the `exec` (default) converts all properties to command line arguments and thus may not be secure in some environments.
==== Common application properties
In addition to configuration through DSL, Spring Cloud Data Flow provides a mechanism for setting common properties to all the task applications that are launched by it.
This can be done by adding properties prefixed with `spring.cloud.dataflow.applicationProperties.task` when starting the server.
When doing so, the server passes all the properties, without the prefix, to the instances it launches.
For example, all the launched applications can be configured to use the properties `prop1` and `prop2` by launching the Data Flow server with the following options:
[source,bash,subs=attributes]
----
--spring.cloud.dataflow.applicationProperties.task.prop1=value1
--spring.cloud.dataflow.applicationProperties.task.prop2=value2
----
This causes the properties, `prop1=value1` and `prop2=value2`, to be passed to all the launched applications.
[NOTE]
Properties configured by using this mechanism have lower precedence than task deployment properties.
They are overridden if a property with the same key is specified at task launch time (for example, `app.trigger.prop2`
overrides the common property).
[[spring-cloud-dataflow-task-limit-concurrent-executions]]
=== Limit the number concurrent task launches
Spring Cloud Data Flow allows a user to limit the maximum number of concurrently running tasks for each configured platform to prevent the saturation of IaaS/hardware resources.
The limit is set to `20` for all supported platforms by default. If the number of concurrently running tasks on a platform instance is greater or equal to the limit, the next task launch request will fail and an error message will be returned via the RESTful API, Shell or UI.
This limit can be configured for a platform instance by setting the corresponding deployer property, `spring.cloud.dataflow.task.platform..accounts[].deployment.maximumConcurrentTasks` property, where `` is the name of a configured platform account (`default` if no accounts are explicitly configured).
The `` refers to one of the currently supported deployers: `local`, `cloudfoundry`, or `kubernetes`.
The TaskLauncher implementation for each supported platform determines the number of currently executing tasks by querying the underlying platform's runtime state if possible. The method for identifying a `task` varies by platform.
For example, launching a task on the local host uses the `LocalTaskLauncher`. The LocalTaskLauncher executes a process for each launch request and keeps track of these processes in memory. In this case, we don't query the underlying OS, as it is impractical to identify tasks this way.
For Cloud Foundry, tasks are a core concept supported by its deployment model. The state of all tasks, running, completed, or failed, is available directly via the API.
This means that every running task container in the account's org and space is included in the running execution count, whether or not it was launched using Spring Cloud Data Flow, or invoking the `CloudFoundryTaskLauncher` directly.
For Kubernetes, launching a task via the `KubernetesTaskLauncher`, if successful, results in a running pod which we expect to eventually complete or fail.
In this environment there is generally no easy way to identify pods that correspond to a task.
For this reason, we only count pods that were launched by the `KubernetesTaskLauncher`.
Since the task launcher provides `task-name` label in the pod's metadata, we filter all running pods by the presence of this label.
[[spring-cloud-dataflow-task-review-executions]]
=== Reviewing Task Executions
Once the task is launched, the state of the task is stored in a relational DB. The state
includes:
* Task Name
* Start Time
* End Time
* Exit Code
* Exit Message
* Last Updated Time
* Parameters
A user can check the status of their task executions through the RESTful API or the shell.
To display the latest task executions through the shell, use the `task execution list` command.
To get a list of task executions for just one task definition, add `--name` and
the task definition name, for example `task execution list --name foo`. To retrieve full
details for a task execution use the `task execution status` command with the id of the task execution,
for example `task execution status --id 549`.
[[spring-cloud-dataflow-task-definition-destroying]]
=== Destroying a Task Definition
Destroying a Task Definition removes the definition from the definition repository.
This can be done through the RESTful API or the shell.
To destroy a task through the shell, use the `task destroy` command, as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:>task destroy mytask
Destroyed task 'mytask'
----
The `task destroy` command also has an option to `cleanup` the task executions of the task being destroyed, as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:>task destroy mytask --cleanup
Destroyed task 'mytask'
----
By default, the `cleanup` option is set to `false` (ie., by default, the task executions are not cleaned up when destroying the task).
To destroy all tasks through the shell, use the `task all destroy` command as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:>task all destroy
Really destroy all tasks? [y, n]: y
All tasks destroyed
----
Or use the force command:
[source,bash,subs=attributes]
----
dataflow:>task all destroy --force
All tasks destroyed
----
The task execution information for previously launched tasks for the definition remains in the task repository.
NOTE: This does not stop any currently executing tasks for this definition. Instead, it removes the task definition from the database.
NOTE: The `task destroy ` deletes only the definition and not the task deployed on Cloud Foundry.
The only way to do this now is through the CLI in two steps. First, obtain a list of the apps by using the `cf apps` command.
. Identify the task application to be deleted and run the `cf delete ` command.
[[spring-cloud-dataflow-validate-task]]
=== Validating a Task
Sometimes the one or more of the apps contained within a task definition contain an invalid URI in its registration.
This can be caused by an invalid URI entered at app registration time or the app was removed from the repository from which it was to be drawn.
To verify that all the apps contained in a task are resolve-able, a user can use the `validate` command.
For example:
[source,bash]
----
dataflow:>task validate time-stamp
╔══════════╤═══════════════╗
║Task Name │Task Definition║
╠══════════╪═══════════════╣
║time-stamp│timestamp ║
╚══════════╧═══════════════╝
time-stamp is a valid task.
╔═══════════════╤═════════════════╗
║ App Name │Validation Status║
╠═══════════════╪═════════════════╣
║task:timestamp │valid ║
╚═══════════════╧═════════════════╝
----
In the example above the user validated their time-stamp task. As we see `task:timestamp` app is valid.
Now let's see what happens if we have a stream definition with a registered app with an invalid URI.
[source,bash]
----
dataflow:>task validate bad-timestamp
╔═════════════╤═══════════════╗
║ Task Name │Task Definition║
╠═════════════╪═══════════════╣
║bad-timestamp│badtimestamp ║
╚═════════════╧═══════════════╝
bad-timestamp is an invalid task.
╔══════════════════╤═════════════════╗
║ App Name │Validation Status║
╠══════════════════╪═════════════════╣
║task:badtimestamp │invalid ║
╚══════════════════╧═════════════════╝
----
In this case Spring Cloud Data Flow states that the task is invalid because task:badtimestamp has an invalid URI.
[[spring-cloud-dataflow-stopping-task-execution]]
=== Stopping a Task Execution
In some cases a task that is executing on a platform may not stop because of a problem on the platform or the application business logic itself.
For such cases Spring Cloud Data Flow offers the user the ability to send a request to the platform to terminate the task execution.
To do this a user can submit a `task execution stop` for a given set of task executions. For example:
[source,bash]
----
task execution stop --ids 5
Request to stop the task execution with id(s): 5 has been submitted
----
With the above command, the trigger to stop the execution of id=5 will be submitted to the underlying deployer implementation, and as a result, the operation will stop the execution of that task. When we view the result for the task execution, we will see that the task execution completed with a 0 exit code.
[source,bash]
----
dataflow:>task execution list
╔══════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗
║Task Name │ID│ Start Time │ End Time │Exit Code║
╠══════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣
║batch-demo│5 │Mon Jul 15 13:58:41 EDT 2019│Mon Jul 15 13:58:55 EDT 2019│0 ║
║timestamp │1 │Mon Jul 15 09:26:41 EDT 2019│Mon Jul 15 09:26:41 EDT 2019│0 ║
╚══════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝
----
If a user submits a stop for a task execution that has child task executions associated with it, like a composed task, a stop request will be sent for each of the child task executions.
[WARNING]
====
When stopping a task execution that has a running Spring Batch job, the job will be left with the batch status of `STARTED`.
Each of the supported platforms send a SIG-INT to the task application when a stop is requested that allows Spring Cloud Task to capture the state of the app, however Spring Batch does not handle a SIG-INT and thus the job stops in the STARTED status.
====
==== Stopping a Task Execution that was started outside of Spring Cloud Data Flow
You may wish to stop a task that has been launched outside of Spring Cloud Data Flow. An example of this is the worker applications launched by a Remote Batch Partitioned application.
In such cases the Remote Batch Partitioned Application stores the external-execution-id for each of the worker applications, however no platform information is stored.
So when Spring Cloud Data Flow has to stop a Remote Batch Partitioned application and its worker applications, you will need to specify the platform name as shown below:
[source,bash]
----
dataflow:>task execution stop --ids 1 --platform myplatform
Request to stop the task execution with id(s): 1 for platform myplatform has been submitted
----
[[spring-cloud-dataflow-task-events]]
== Subscribing to Task/Batch Events
You can also tap into various task and batch events when the task is launched.
If the task is enabled to generate task or batch events (with the additional dependencies `spring-cloud-task-stream` and, in the case of Kafka as the binder, `spring-cloud-stream-binder-kafka`), those events are published during the task lifecycle.
By default, the destination names for those published events on the broker (Rabbit, Kafka, and others) are the event names themselves (for instance: `task-events`, `job-execution-events`, and so on).
[source,bash,subs=attributes]
----
dataflow:>task create myTask --definition ""myBatchJob""
dataflow:>stream create task-event-subscriber1 --definition "":task-events > log"" --deploy
dataflow:>task launch myTask
----
You can control the destination name for those events by specifying explicit names when launching the task, as follows:
[source,bash,subs=attributes]
----
dataflow:>stream create task-event-subscriber2 --definition "":myTaskEvents > log"" --deploy
dataflow:>task launch myTask --properties ""app.myBatchJob.spring.cloud.stream.bindings.task-events.destination=myTaskEvents""
----
The following table lists the default task and batch event and destination names on the broker:
.Task and Batch Event Destinations
[cols=""2*""]
|===
|*Event*|*Destination*
|Task events
|`task-events`
|Job Execution events |`job-execution-events`
|Step Execution events|`step-execution-events`
|Item Read events|`item-read-events`
|Item Process events|`item-process-events`
|Item Write events|`item-write-events`
|Skip events|`skip-events`
|===
[[spring-cloud-dataflow-composed-tasks]]
== Composed Tasks
Spring Cloud Data Flow lets a user create a directed graph where each node of the graph is a task application.
This is done by using the DSL for composed tasks.
A composed task can be created through the RESTful API, the Spring Cloud Data Flow Shell, or the Spring Cloud Data Flow UI.
=== Configuring the Composed Task Runner
Composed tasks are executed through a task application called the https://github.com/spring-cloud-task-app-starters/composed-task-runner[Composed Task Runner].
==== Registering the Composed Task Runner
By default, Spring Cloud Data Flow retrieves the Composed Task Runner application from
Maven Central for Cloud Foundry and local deployments and DockerHub for Kubernetes. It
retrieves the Composed Task Runner upon the first use of composed tasks.
If Maven Central or DockerHub cannot be reached for a given Spring Cloud Data Flow
deployment a new URI can be specified to retrieve the Composed Task Runner using the
`spring.cloud.dataflow.task.composed.task.runner.uri` property.
==== Configuring the Composed Task Runner
The Composed Task Runner application has a `dataflow.server.uri` property that is used for validation and for launching child tasks.
This defaults to `http://localhost:9393`. If you run a distributed Spring Cloud Data Flow server, as you would if you deploy the server on Cloud Foundry or Kubernetes, you need to provide the URI that can be used to access the server.
You can either provide this `dataflow.server.uri` property for the Composed Task Runner application when launching a composed task or you can provide a `spring.cloud.dataflow.server.uri` property for the Spring Cloud Data Flow server when it is started.
For the latter case, the `dataflow.server.uri` Composed Task Runner application property is automatically set when a composed task is launched.
===== Configuration Options
The ComposedTaskRunner task has the following options:
* *composed-task-arguments*
The command line arguments to be used for each of the tasks. (String, default: ).
* *increment-instance-enabled*
Allows a single ComposedTaskRunner instance to be re-executed without changing the parameters. Default is false which means a ComposedTaskRunner instance can only be executed once with a given set of parameters, if true it can be re-executed. (Boolean, default: false).
ComposedTaskRunner is built using https://github.com/spring-projects/spring-batch[Spring Batch] and thus upon a successful execution the batch job is considered complete.
To launch the same ComposedTaskRunner definition multiple times you must set the `increment-instance-enabled` property to true or change the parameters for the definition for each launch.
When using this option it must be applied for all task launches for the desired application including the first launch.
* *interval-time-between-checks*
The amount of time in millis that the ComposedTaskRunner will wait between checks of the database to see if a task has completed. (Integer, default: 10000).
ComposedTaskRunner uses the datastore to determine the status of each child tasks. This interval indicates to ComposedTaskRunner how often it should check the status its child tasks.
* *max-wait-time*
The maximum amount of time in millis that a individual step can run before the execution of the Composed task is failed (Integer, default: 0).
Determines the maximum time each child task is allowed to run before the CTR will terminate with a failure. The default of `0` indicates no timeout.
* *split-thread-allow-core-thread-timeout*
Specifies whether to allow split core threads to timeout. Default is false; (Boolean, default: false)
Sets the policy governing whether core threads may timeout and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.
* *split-thread-core-pool-size*
Split's core pool size. Default is 1; (Integer, default: 1)
Each child task contained in a split requires a thread in order to execute. So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3.
This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run.
Then `DDD` and `EEE` would run in parallel.
* *split-thread-keep-alive-seconds*
Split's thread keep alive seconds. Default is 60. (Integer, default: 60)
If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime.
* *split-thread-max-pool-size*
Split's maximum pool size. Default is {@code Integer.MAX_VALUE} (Integer, default: ).
Establish the maximum number of threads allowed for the thread pool.
* *split-thread-queue-capacity*
Capacity for Split's BlockingQueue. Default is {@code Integer.MAX_VALUE}. (Integer, default: )
** If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
** If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
** If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.
* *split-thread-wait-for-tasks-to-complete-on-shutdown*
Whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. Default is false; (Boolean, default: false)
* *dataflow-server-uri*
The URI for the dataflow server that will receive task launch requests. (String, default: http://localhost:9393)
* *dataflow-server-username*
The optional username for the dataflow server that will receive task launch requests.
Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set.
* *dataflow-server-password*
The optional password for the dataflow server that will receive task launch requests.
Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set.
* *dataflow-server-access-token*
This property sets optional OAuth2 Access Token.
Typically the value is automatically set using the token from the currently logged in user, if available.
However, for special use-cases this value can also be set explicitly.
[INFO]
====
A special boolean property `dataflow-server-use-user-access-token` exists for the case
where you want to use the access token of the currently logged user and propgate it to the Composed Task Runner. This property is only used
by Spring Cloud Data Flow and if set to `true` will auto-populate the property `dataflow-server-access-token`.
====
Note when using the options above as environment variables, convert to uppercase, remove the dash character and replace with the underscore character. For example: increment-instance-enabled would be INCREMENT_INSTANCE_ENABLED.
NOTE: For the latest configuration options for Composed Task Runner click the link https://github.com/spring-cloud-task-app-starters/composed-task-runner/blob/master/spring-cloud-starter-task-composedtaskrunner/README.adoc#options[here].
=== The Lifecycle of a Composed Task
The lifecycle of a composed task has three parts:
* <>
* <>
* <>
[[spring-cloud-data-flow-composed-task-creating]]
==== Creating a Composed Task
The DSL for the composed tasks is used when creating a task definition through the task create command, as shown in the following example:
[source,bash,subs=attributes]
----
dataflow:> app register --name timestamp --type task --uri maven://org.springframework.cloud.task.app:timestamp-task:
dataflow:> app register --name mytaskapp --type task --uri file:///home/tasks/mytask.jar
dataflow:> task create my-composed-task --definition ""mytaskapp && timestamp""
dataflow:> task launch my-composed-task
----
In the preceding example, we assume that the applications to be used by our composed task have not been registered yet.
Consequently, in the first two steps, we register two task applications.
We then create our composed task definition by using the `task create` command.
The composed task DSL in the preceding example, when launched, runs mytaskapp and then runs the timestamp application.
But before we launch the `my-composed-task` definition, we can view what Spring Cloud Data Flow generated for us.
This can be done by executing the task list command, as shown (including its output) in the following example:
[source,bash,options=""nowrap""]
----
dataflow:>task list
╔══════════════════════════╤══════════════════════╤═══════════╗
║ Task Name │ Task Definition │Task Status║
╠══════════════════════════╪══════════════════════╪═══════════╣
║my-composed-task │mytaskapp && timestamp│unknown ║
║my-composed-task-mytaskapp│mytaskapp │unknown ║
║my-composed-task-timestamp│timestamp │unknown ║
╚══════════════════════════╧══════════════════════╧═══════════╝
----
In the example, Spring Cloud Data Flow created three task definitions, one for each of the applications that makes up our composed task (`my-composed-task-mytaskapp` and `my-composed-task-timestamp`) as well as the composed task (`my-composed-task`) definition.
We also see that each of the generated names for the child tasks is made up of the name of the composed task and the name of the application, separated by a dash `-` (as in _my-composed-task_ `-` _mytaskapp_).
===== Task Application Parameters
The task applications that make up the composed task definition can also contain parameters, as shown in the following example:
`dataflow:> task create my-composed-task --definition ""mytaskapp --displayMessage=hello && timestamp --format=YYYY""`
==== Launching a Composed Task
Launching a composed task is done the same way as launching a stand-alone task, as follows:
`task launch my-composed-task`
Once the task is launched, and assuming all the tasks complete successfully, you can see three task executions when executing a `task execution list`, as shown in the following example:
[source,bash,options=""nowrap""]
----
dataflow:>task execution list
╔══════════════════════════╤═══╤════════════════════════════╤════════════════════════════╤═════════╗
║ Task Name │ID │ Start Time │ End Time │Exit Code║
╠══════════════════════════╪═══╪════════════════════════════╪════════════════════════════╪═════════╣
║my-composed-task-timestamp│713│Wed Apr 12 16:43:07 EDT 2017│Wed Apr 12 16:43:07 EDT 2017│0 ║
║my-composed-task-mytaskapp│712│Wed Apr 12 16:42:57 EDT 2017│Wed Apr 12 16:42:57 EDT 2017│0 ║
║my-composed-task │711│Wed Apr 12 16:42:55 EDT 2017│Wed Apr 12 16:43:15 EDT 2017│0 ║
╚══════════════════════════╧═══╧════════════════════════════╧════════════════════════════╧═════════╝
----
In the preceding example, we see that `my-compose-task` launched and that it also launched the other tasks in sequential order.
All of them executed successfully with `Exit Code` as `0`.
===== Passing properties to the child tasks
To set the properties for child tasks in a composed task graph at task launch time,
you would use the following format of `app...`.
Using the following Composed Task definition as an example:
[source,bash]
----
dataflow:> task create my-composed-task --definition ""mytaskapp && mytimestamp""
----
To have mytaskapp display 'HELLO' and set the mytimestamp timestamp format to 'YYYY' for the Composed Task definition, you would use the following task launch format:
[source,bash]
----
task launch my-composed-task --properties ""app.my-composed-task.mytaskapp.displayMessage=HELLO,app.my-composed-task.mytimestamp.timestamp.format=YYYY""
----
Similar to application properties, the `deployer` properties can also be set for child tasks using the format format of `deployer...`.
[source,bash]
----
task launch my-composed-task --properties ""deployer.my-composed-task.mytaskapp.memory=2048m,app.my-composed-task.mytimestamp.timestamp.format=HH:mm:ss""
Launched task 'a1'
----
===== Passing arguments to the composed task runner
Command line arguments for the composed task runner can be passed using `--arguments` option.
For example:
[source,bash]
----
dataflow:>task create my-composed-task --definition """"
Created new task 'my-composed-task'
dataflow:>task launch my-composed-task --arguments ""--increment-instance-enabled=true --max-wait-time=50000 --split-thread-core-pool-size=4"" --properties ""app.my-composed-task.bbb.timestamp.format=dd/MM/yyyy HH:mm:ss""
Launched task 'my-composed-task'
----
===== Launching a Composed Task using Custom Composed Task Runner
In some cases a user will need to launch a composed task using a custom version of a Composed Task Runner other than default application that is shipped out-of-the-box.
To do this, a user will need to register the custom version of the Composed Task Runner and then specify the --composedTaskRunnerName property pointing to the custom application at task launch as shown below:
[source,bash,options=""nowrap""]
----
dataflow:>app register --name best-ctr --type task --uri maven://the.best.ctr.composed-task-runner:1.0.0.RELEASE
dataflow:>task create mycomposedtask --definition ""te:timestamp && tr:timestamp""
Created new task 'mycomposedtask'
dataflow:>task launch --name mycomposedtask --composedTaskRunnerName best-ctr
----
NOTE: The app specified by the `composedTaskRunnerName` needs to be a task registered in the Application Registry.
===== Exit Statuses
The following list shows how the Exit Status is set for each step (task) contained in the composed task following each step execution:
* If the `TaskExecution` has an `ExitMessage`, that is used as the `ExitStatus`.
* If no `ExitMessage` is present and the `ExitCode` is set to zero, then the `ExitStatus` for the step is `COMPLETED`.
* If no `ExitMessage` is present and the `ExitCode` is set to any non-zero number, the `ExitStatus` for the step is `FAILED`.
==== Destroying a Composed Task
The command used to destroy a stand-alone task is the same as the command used to destroy a composed task.
The only difference is that destroying a composed task also destroys the child tasks associated with it.
The following example shows the task list before and after using the `destroy` command:
[source,bash,options=""nowrap""]
----
dataflow:>task list
╔══════════════════════════╤══════════════════════╤═══════════╗
║ Task Name │ Task Definition │Task Status║
╠══════════════════════════╪══════════════════════╪═══════════╣
║my-composed-task │mytaskapp && timestamp│COMPLETED ║
║my-composed-task-mytaskapp│mytaskapp │COMPLETED ║
║my-composed-task-timestamp│timestamp │COMPLETED ║
╚══════════════════════════╧══════════════════════╧═══════════╝
...
dataflow:>task destroy my-composed-task
dataflow:>task list
╔═════════╤═══════════════╤═══════════╗
║Task Name│Task Definition│Task Status║
╚═════════╧═══════════════╧═══════════╝
----
[[spring-cloud-data-flow-composed-task-stopping]]
==== Stopping a Composed Task
In cases where a composed task execution needs to be stopped, you can do so through the:
* RESTful API
* Spring Cloud Data Flow Dashboard
To stop a composed task through the dashboard, select the Jobs tab and click the Stop button next to the job execution that you want to stop.
The composed task run is stopped when the currently running child task completes.
The step associated with the child task that was running at the time that the composed task was stopped is marked as `STOPPED` as well as the composed task job execution.
[[spring-cloud-data-flow-composed-task-restarting]]
==== Restarting a Composed Task
In cases where a composed task fails during execution and the status of the composed task is `FAILED`, the task can be restarted.
You can do so through the:
* RESTful API
* The shell
* Spring Cloud Data Flow Dashboard
To restart a composed task through the shell, launch the task with the same parameters.
To restart a composed task through the dashboard, select the Jobs tab and click the Restart button next to the job execution that you want to restart.
NOTE: Restarting a Composed Task job that has been stopped (through the Spring Cloud Data Flow Dashboard or RESTful API) relaunches the `STOPPED` child task and then launches the remaining (unlaunched) child tasks in the specified order.
== Composed Tasks DSL
Composed tasks can be run in three ways:
* <>
* <>
* <>
[[spring-cloud-data-flow-conditional-execution]]
=== Conditional Execution
Conditional execution is expressed by using a double ampersand symbol (`&&`).
This lets each task in the sequence be launched only if the previous task
successfully completed, as shown in the following example:
`task create my-composed-task --definition ""task1 && task2""`
When the composed task called `my-composed-task` is launched, it launches the task called `task1` and, if it completes successfully, then the task called `task2` is launched.
If `task1` fails, then `task2` does not launch.
You can also use the Spring Cloud Data Flow Dashboard to create your conditional execution, by using the designer to drag and drop applications that are required and connecting them together to create your directed graph, as shown in the following image:
.Conditional Execution
image::{dataflow-asciidoc}/images/dataflow-ctr-conditional-execution.png[Composed Task Conditional Execution, scaledwidth=""50%""]
The preceding diagram is a screen capture of the directed graph as it being created by using the Spring Cloud Data Flow Dashboard.
You can see that are four components in the diagram that comprise a conditional execution:
* Start icon: All directed graphs start from this symbol.
There is only one.
* Task icon: Represents each task in the directed graph.
* End icon: Represents the termination of a directed graph.
* Solid line arrow: Represents the flow conditional execution flow between:
** Two applications.
** The start control node and an application.
** An application and the end control node.
* End icon: All directed graphs end at this symbol.
TIP: You can view a diagram of your directed graph by clicking the Detail button next to the composed task definition on the Definitions tab.
[[spring-cloud-data-flow-transitional-execution]]
=== Transitional Execution
The DSL supports fine-grained control over the transitions taken during the execution of the directed graph.
Transitions are specified by providing a condition for equality based on the exit status of the previous task.
A task transition is represented by the following symbol `->`.
==== Basic Transition
A basic transition would look like the following:
```
task create my-transition-composed-task --definition ""foo 'FAILED' -> bar 'COMPLETED' -> baz""
```
In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch.
If the exit status of `foo` was `COMPLETED`, `baz` would launch.
All other statuses returned by `foo` have no effect, and the task would terminate normally.
Using the Spring Cloud Data Flow Dashboard to create the same "" `basic transition` "" would resemble the following image:
.Basic Transition
image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic.png[Composed Task Basic Transition, scaledwidth=""50%""]
The preceding diagram is a screen capture of the directed graph as it being created in the Spring Cloud Data Flow Dashboard.
Notice that there are two different types of connectors:
* Dashed line: Represents transitions from the application to one of the possible destination applications.
* Solid line: Connects applications in a conditional execution or a connection between the application and a control node (start or end).
To create a transitional connector:
. When creating a transition, link the application to each possible destination by using the connector.
. Once complete, go to each connection and select it by clicking it.
. A bolt icon appears.
. Click that icon.
. Enter the exit status required for that connector.
. The solid line for that connector turns to a dashed line.
==== Transition With a Wildcard
Wildcards are supported for transitions by the DSL, as shown in the following:
```
task create my-transition-composed-task --definition ""foo 'FAILED' -> bar '*' -> baz""
```
In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch.
For any exit status of `foo` other than `FAILED`, `baz` would launch.
Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with wildcard`"" would resemble the following image:
.Basic Transition With Wildcard
image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic-wildcard.png[Composed Task Basic Transition with Wildcard, scaledwidth=""50%""]
==== Transition With a Following Conditional Execution
A transition can be followed by a conditional execution so long as the wildcard
is not used, as shown in the following example:
```
task create my-transition-conditional-execution-task --definition ""foo 'FAILED' -> bar 'UNKNOWN' -> baz && qux && quux""
```
In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch.
If `foo` had an exit status of `UNKNOWN`, `baz` would launch.
For any exit status of `foo` other than `FAILED` or `UNKNOWN`, `qux` would launch and, upon successful completion, `quux` would launch.
Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with conditional execution`"" would resemble the following image:
.Transition With Conditional Execution
image::{dataflow-asciidoc}/images/dataflow-ctr-transition-conditional-execution.png[Composed Task Transition with Conditional Execution, scaledwidth=""50%""]
NOTE: In this diagram we see the dashed line (transition) connecting the `foo` application to the target applications, but a solid line connecting the conditional executions between `foo`, `qux`, and `quux`.
[[spring-cloud-data-flow-split-execution]]
=== Split Execution
Splits allow multiple tasks within a composed task to be run in parallel.
It is denoted by using angle brackets (`<>`) to group tasks and flows that are to be run in parallel.
These tasks and flows are separated by the double pipe `||` symbol, as shown in the following example:
`task create my-split-task --definition """"`
The preceding example above launches tasks `foo`, `bar` and `baz` in parallel.
Using the Spring Cloud Data Flow Dashboard to create the same ""`split execution`"" would resemble the following image:
.Split
image::{dataflow-asciidoc}/images/dataflow-ctr-split.png[Composed Task Split, scaledwidth=""50%""]
With the task DSL, a user may also execute multiple split groups in succession, as shown in the following example:
`task create my-split-task --definition "" && ""'
In the preceding example, tasks `foo`, `bar`, and `baz` are launched in parallel.
Once they all complete, then tasks `qux` and `quux` are launched in parallel.
Once they complete, the composed task ends.
However, if `foo`, `bar`, or `baz` fails, the split containing `qux` and `quux` does not launch.
Using the Spring Cloud Data Flow Dashboard to create the same ""`split with multiple groups`"" would resemble the following image:
.Split as a part of a conditional execution
image::{dataflow-asciidoc}/images/dataflow-ctr-multiple-splits.png[Composed Task Split, scaledwidth=""50%""]
Notice that there is a `SYNC` control node that is inserted by the designer when
connecting two consecutive splits.
NOTE: Tasks that are used in a split should not set the their `ExitMessage`. Setting the `ExitMessage` is only to be used
with <>.
==== Split Containing Conditional Execution
A split can also have a conditional execution within the angle brackets, as shown in the following example:
`task create my-split-task --definition """"`
In the preceding example, we see that `foo` and `baz` are launched in parallel.
However, `bar` does not launch until `foo` completes successfully.
Using the Spring Cloud Data Flow Dashboard to create the same "" `split containing conditional execution` "" resembles the following image:
.Split with conditional execution
image::{dataflow-asciidoc}/images/dataflow-ctr-split-contains-conditional.png[Composed Task Split With Conditional Execution, scaledwidth=""50%""]
==== Establishing the proper thread count for splits
Each child task contained in a split requires a thread in order to execute. To set this properly you want to look at your graph and count the split that has the largest number of child tasks, this will be the number of threads you will need to utilize.
To set the thread count use the split-thread-core-pool-size property (defaults to 1). So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3.
This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run.
Then `DDD` and `EEE` would run in parallel.
[[spring-cloud-dataflow-launch-tasks-from-stream]]
== Launching Tasks from a Stream
You can launch a task from a stream by using the https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc[tasklauncher-dataflow] sink.
The sink connects to a Data Flow server and uses its REST API to launch any defined task.
The sink accepts a https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc#payload[JSON payload] representing a `task launch request` which provides the name of the task to launch, and may include command line arguments and deployment properties.
The https://github.com/spring-cloud-stream-app-starters/core/blob/master/common/app-starters-task-launch-request-common/README.adoc[app-starters-task-launch-request-common] component , in conjunction with Spring Cloud Stream https://docs.spring.io/spring-cloud-stream/docs/current-snapshot/reference/htmlsingle/#_functional_composition[functional composition], can transform the output of any source or processor to a task launch request.
Adding a dependency to `app-starters-task-launch-request-common`, auto-configures a `java.util.function.Function` implementation, registered via https://cloud.spring.io/spring-cloud-function/[Spring Cloud Function] as `taskLaunchRequest`.
For example, you can start with the https://github.com/spring-cloud-stream-app-starters/time/tree/master/spring-cloud-starter-stream-source-time[time] source, add the following dependency, build it, and register it as a custom source. We'll call it `time-tlr` in this example.
[source,xml]
----
org.springframework.cloud.stream.appapp-starters-task-launch-request-common
----
TIP: https://start-scs.cfapps.io/[Spring Cloud Stream Initializr] provides a great starting point for creating stream applications.
Next, <> the `tasklauncher-dataflow` sink, and create a task (we will use the provided timestamp task).
```
stream create --name task-every-minute --definition ""time-tlr --trigger.fixed-delay=60 --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task | tasklauncher-dataflow"" --deploy
```
The preceding stream will produce a task launch request every minute. The request provides the name of the task to launch : `{""name"":""timestamp-task""}`.
The following stream definition illustrates the use of command line arguments. It will produce messages like `{""args"":[""foo=bar"",""time=12/03/18 17:44:12""],""deploymentProps"":{},""name"":""timestamp-task""}` to provide command line arguments to the task:
```
stream create --name task-every-second --definition ""time-tlr --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task --task.launch.request.args=foo=bar --task.launch.request.arg-expressions=time=payload | tasklauncher-dataflow"" --deploy
```
Note the use of SpEL expressions to map each message payload to the `time` command line argument, along with a static argument `foo=bar`.
You can then see the list of task executions by using the shell command `task execution list`, as shown (with its output) in the following example:
[source,bash,options=""nowrap""]
----
dataflow:>task execution list
╔════════════════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗
║ Task Name │ID│ Start Time │ End Time │Exit Code║
╠════════════════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣
║timestamp-task_26176│4 │Tue May 02 12:13:49 EDT 2017│Tue May 02 12:13:49 EDT 2017│0 ║
║timestamp-task_32996│3 │Tue May 02 12:12:49 EDT 2017│Tue May 02 12:12:49 EDT 2017│0 ║
║timestamp-task_58971│2 │Tue May 02 12:11:50 EDT 2017│Tue May 02 12:11:50 EDT 2017│0 ║
║timestamp-task_13467│1 │Tue May 02 12:10:50 EDT 2017│Tue May 02 12:10:50 EDT 2017│0 ║
╚════════════════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝
----
In this example, we have shown how to use the `time` source to launch a task at a fixed rate.
This pattern may be applied to any source to launch a task in response to any event.
=== Launching a Composed Task From a Stream
A composed task can be launched with the `tasklauncher-dataflow` sink, as discussed <>.
Since we use the `ComposedTaskRunner` directly, we need to set up the task definitions for the composed task runner itself, along with the composed tasks, prior to the creation of the composed task launching stream.
Suppose we wanted to create the following composed task definition: `AAA && BBB`.
The first step would be to create the task definitions, as shown in the following example:
[source]
----
task create composed-task-runner --definition ""composed-task-runner""
task create AAA --definition ""timestamp""
task create BBB --definition ""timestamp""
----
NOTE: Releases of `ComposedTaskRunner` can be found
https://github.com/spring-cloud-task-app-starters/composed-task-runner/releases[here].
Now that the task definitions we need for composed task definition are ready, we need to create a stream that launches `ComposedTaskRunner`.
So, in this case, we create a stream with
* The `time` source customized to emit task launch requests, as shown <>.
* The `tasklauncher-dataflow` sink that launches the `ComposedTaskRunner`
The stream should resemble the following:
[source]
----
stream create ctr-stream --definition ""time --fixed-delay=30 --task.launch.request.task-name=composed-task-launcher --task.launch.request.args=--graph=AAA&&BBB,--increment-instance-enabled=true | tasklauncher-dataflow""
----
For now, we focus on the configuration that is required to launch the `ComposedTaskRunner`:
* *graph*: this is the graph that is to be executed by the `ComposedTaskRunner`.
In this case it is `AAA&&BBB`.
* *increment-instance-enabled*: This lets each execution of `ComposedTaskRunner` be unique.
`ComposedTaskRunner` is built by using https://projects.spring.io/spring-batch/[Spring Batch].
Thus, we want a new Job Instance for each launch of the `ComposedTaskRunner`.
To do this, we set `increment-instance-enabled` to be `true`.
[[sharing-spring-cloud-dataflows-datastore-with-tasks]]
== Sharing Spring Cloud Data Flow's Datastore with Tasks
As discussed in the <> documentation Spring
Cloud Data Flow allows a user to view Spring Cloud Task App executions. So in
this section we will discuss what is required by a Task Application and Spring
Cloud Data Flow to share the task execution information.
[[a-common-datastore-dependency]]
=== A Common DataStore Dependency
Spring Cloud Data Flow supports many databases out-of-the-box,
so all the user typically has to do is declare the `spring_datasource_*` environment variables
to establish what data store Spring Cloud Data Flow will need.
So whatever database you decide to use for Spring Cloud Data Flow make sure that the your task also
includes that database dependency in its `pom.xml` or `gradle.build` file. If the database dependency
that is used by Spring Cloud Data Flow is not present in the Task Application, the task will fail
and the task execution will not be recorded.
[[a-common-datastore]]
=== A Common Data Store
Spring Cloud Data Flow and your task application must access the same datastore instance.
This is so that the task executions recorded by the task application can be read by Spring Cloud Data Flow to list them in the Shell and Dashboard views.
Also the task app must have read & write privileges to the task data tables that are used by Spring Cloud Data Flow.
Given the understanding of Datasource dependency between Task apps and Spring Cloud Data Flow, let's review how to apply them in various Task orchestration scenarios.
[[datasource-simple-task-launch]]
==== Simple Task Launch
When launching a task from Spring Cloud Data Flow, Data Flow adds its datasource
properties (`spring.datasource.url`, `spring.datasource.driverClassName`, `spring.datasource.username`, `spring.datasource.password`)
to the app properties of the task being launched. Thus a task application
will record its task execution information to the Spring Cloud Data Flow repository.
==== Composed Task Runner
Spring Cloud Data Flow allows a user to create a directed graph where each node
of the graph is a task application and this is done via the
https://github.com/spring-cloud-task-app-starters/composed-task-runner/blob/master/spring-cloud-starter-task-composedtaskrunner/README.adoc[Composed Task Runner].
In this case the rules that applied to a <>
or Task Launcher Sink apply to the composed task runner as well.
All child apps must also have access to the datastore that is being used by the composed task runner
Also, All child apps must have the same database dependency as the composed task runner enumerated in their `pom.xml` or `gradle.build` file.
==== Launching a task externally from Spring Cloud Data Flow
Users may wish to launch Spring Cloud Task applications via another method (scheduler for example) but still track the task execution via Spring Cloud Data Flow.
This can be done so long as the task applications observe the rules specified <> and <>.
NOTE: If a user wishes to use Spring Cloud Data Flow to view their
https://projects.spring.io/spring-batch/[Spring Batch] jobs, the user must make sure that
their batch application use the `@EnableTask` annotation and follow the rules enumerated <> and <>.
More information is available https://github.com/spring-projects/spring-batch-admin/blob/master/MIGRATION.md[here].
[[spring-cloud-dataflow-schedule-launch-tasks]]
== Scheduling Tasks
Spring Cloud Data Flow lets a user schedule the execution of tasks via a cron expression.
A schedule can be created through the RESTful API or the Spring Cloud Data Flow UI.
=== The Scheduler
Spring Cloud Data Flow will schedule the execution of its tasks via a scheduling agent that is available on the cloud platform.
When using the Cloud Foundry platform Spring Cloud Data Flow will use the https://www.cloudfoundry.org/the-foundry/scheduler/[PCF Scheduler].
When using Kubernetes, a https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/[CronJob] will be used.
NOTE: Scheduled tasks do not implement the continuous deployment feature. Any changes to application version or properties for a task definition via Spring Cloud Data Flow will not affect scheduled tasks.
.Architectural Overview
image::{dataflow-asciidoc}/images/dataflow-scheduling-architecture.png[Scheduler Architecture Overview, scaledwidth=""50%""]
=== Enabling Scheduling
By default the Spring Cloud Data Flow leaves the scheduling feature disabled. To enable the scheduling feature the following feature properties must be set to `true`:
* `spring.cloud.dataflow.features.schedules-enabled`
* `spring.cloud.dataflow.features.tasks-enabled`
=== The Lifecycle of a Schedule
The lifecycle of a schedule has 2 parts:
* <>
* <>
* <>
[[spring-cloud-data-flow-schedule-scheduling]]
==== Scheduling a Task Execution
You can schedule a task execution via the:
* Spring Cloud Data Flow Shell
* Spring Cloud Data Flow Dashboard
* Spring Cloud Data Flow RESTful API
==== Scheduling a Task
To schedule a task using the shell, use the `task schedule create` command to create the schedule as shown in the following example:
```
dataflow:>task schedule create --definitionName mytask --name mytaskschedule --expression '*/1 * * * *'
Created schedule 'mytaskschedule'
```
In the example above we created a schedule `mytaskschedule` for the task definition `mytask`. This schedule will launch `mytask` once a minute.
NOTE: If using Cloud Foundry the cron expression above would be: `*/1 * ? * *`. This is because Cloud Foundry uses the Quartz cron expression format.
[[spring-cloud-data-flow-schedule-unscheduling]]
==== Deleting a Schedule
You can delete a schedule via the:
* Spring Cloud Data Flow Shell
* Spring Cloud Data Flow Dashboard
* Spring Cloud Data Flow RESTful API
To delete a task schedule using the shell, use the `task schedule destroy` command as shown in the following example:
```
dataflow:>task schedule destroy --name mytaskschedule
Deleted task schedule 'mytaskschedule'
```
[[spring-cloud-data-flow-schedule-list]]
==== Listing Schedules
You can view the available schedules via the:
* Spring Cloud Data Flow Shell
* Spring Cloud Data Flow Dashboard
* Spring Cloud Data Flow RESTful API
To view your schedules via the shell use the `task schedule list` command as shown in the following example:
[source,bas,options=""nowrap""h]
----
dataflow:>task schedule list
╔══════════════════════════╤════════════════════╤════════════════════════════════════════════════════╗
║ Schedule Name │Task Definition Name│ Properties ║
╠══════════════════════════╪════════════════════╪════════════════════════════════════════════════════╣
║mytaskschedule │mytask │spring.cloud.scheduler.cron.expression = */1 * * * *║
╚══════════════════════════╧════════════════════╧════════════════════════════════════════════════════╝
----
NOTE: Instructions to create, delete and list schedules via the Spring Cloud Data Flow UI can be found https://dataflow.spring.io/docs/feature-guides/batch/scheduling/[here].
[[spring-cloud-dataflow-task-cd]]
== Continuous Deployment
As task applications evolve, you want to get your updates to production. This section walks through the capabilities that Spring Cloud Data Flow provides around being able to update task applications.
When a task application is registered (<>), a version is associated with it. A task application can have multiple versions associated with it, with one selected as the default. The following image illustrates an application with multiple versions associated with it (see the timestamp entry).
image::{dataflow-asciidoc}/images/dataflow-task-application-versions.png[Task Application Versions, scaledwidth=""50%""]
Versions of an application are managed by registering multiple applications with the same name and coordinates, _except_ the version. For example, if you were to register an application with the following values, you would get one application registered with two versions (2.0.0.RELEASE and 2.1.0.RELEASE):
* Application 1
** Name: `timestamp`
** Type: `task`
** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.0.0.RELEASE`
* Application 2
** Name: `timestamp`
** Type: `task`
** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.1.0.RELEASE`
Besides having multiple versions, Spring Cloud Data Flow needs to know which version to run on the next launch. This is indicated by setting a version to be the default version. Whatever version of a task application is configured as the default version is the one to be run on the next launch request. You can see which version is the default in the UI as this image shows:
image::{dataflow-asciidoc}/images/dataflow-task-default-version.png[Task Application Default Version, scaledwidth=""50%""]
=== Task Launch Lifecycle
In previous versions of Spring Cloud Data Flow, when the request to launch a task was received, Spring Cloud Data Flow would deploy the application (if needed) and run it. If the application was being run on a platform that did not need to have the application deployed every time (CloudFoundry for example), the previously deployed application was used. This flow has changed in 2.3. The following image shows what happens when a task launch request comes in now:
image::{dataflow-asciidoc}/images/dataflow-task-launch-flow.png[Flow For Launching A Task, scaledwidth=""50%""]
There are three main flows to consider in the preceding diagram. Launching the first time or launching with no changes is one. The other is launching when there are changes. We look at the flow with no changes first.
==== Launch a Task With No Changes
1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is not required, since nothing has changed (no properties, deployment properites, or versions have changed since the last execution).
[start=5]
5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed.
6. If the application needs to be deployed, Data Flow does the deployment of the task application.
7. Data Flow launches the application.
That flow is the default behavior and occurs every time a request comes in if nothing has changed. It is important to note that this is the same flow that Data Flow has always executed for launching of tasks.
==== Launch a Task With Changes That Is Not Currently Running
The second flow to consider when launching a task is whether there was a change in any of the task application version, application properties, or deployment properties. In this case, the following flow is executed:
1. A launch request comes into Data Flow. Data Flow determines that an upgrade is required since there was a change in either task application version, application properties, or deployment properties.
2. Data Flow checks to see whether another instance of the task definition is currently running.
[start=4]
4. If there is not another instance of the task definition currently running, the old deployment is deleted.
5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed (this check will evaluate to `false` in this flow since the old deployment was deleted).
6. Data Flow does the deployment of the task application with the updated values (new application version, new merged properties, and new merged deployment properties).
7. Data Flow launches the application.
This flow is what fundamentally enables continuous deployment for Spring Cloud Data Flow.
==== Launch a Task With Changes While Another Instance Is Running
The last main flow is when a launch request comes to Spring Cloud Data Flow to do an upgrade but the task definition is currently running. In this case, the launch is blocked due to the requirement to delete the current application. On some platforms (CloudFoundry at the writing of this document), deleting the application causes all currently running applications to be shut down. This feature prevents that from happening. The following process describes what happens when a task changes while another instance is running:
1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is required, since there was a change in either task application version, application properties, or deployment properties.
2. Data Flow checks to see whether another instance of the task definition is currently running.
3. Data Flow prevents the launch from happening because other instances of the task definition are running.
NOTE: Any launch that requires an upgrade of a task definition that is running at the time of the request is blocked from executing due to the need to delete any currently running tasks.
",16186,True,2884.533416366119,median
"
////
/**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* ""License""); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
////
:doctype: book
:numbered:
:toc: left
:icons: font
:experimental:
[[hbase_default_configurations]]
=== HBase Default Configuration
The documentation below is generated using the default hbase configuration file, _hbase-default.xml_, as source.
[[hbase.tmp.dir]]
*`hbase.tmp.dir`*::
+
.Description
Temporary directory on the local filesystem.
Change this setting to point to a location more permanent
than '/tmp', the usual resolve for java.io.tmpdir, as the
'/tmp' directory is cleared on machine restart.
+
.Default
`${java.io.tmpdir}/hbase-${user.name}`
[[hbase.rootdir]]
*`hbase.rootdir`*::
+
.Description
The directory shared by region servers and into
which HBase persists. The URL should be 'fully-qualified'
to include the filesystem scheme. For example, to specify the
HDFS directory '/hbase' where the HDFS instance's namenode is
running at namenode.example.org on port 9000, set this value to:
hdfs://namenode.example.org:9000/hbase. By default, we write
to whatever ${hbase.tmp.dir} is set to -- usually /tmp --
so change this configuration or else all data will be lost on
machine restart.
+
.Default
`${hbase.tmp.dir}/hbase`
[[hbase.cluster.distributed]]
*`hbase.cluster.distributed`*::
+
.Description
The mode the cluster will be in. Possible values are
false for standalone mode and true for distributed mode. If
false, startup will run all HBase and ZooKeeper daemons together
in one JVM.
+
.Default
`false`
[[hbase.zookeeper.quorum]]
*`hbase.zookeeper.quorum`*::
+
.Description
Comma separated list of servers in the ZooKeeper ensemble
(This config. should have been named hbase.zookeeper.ensemble).
For example, ""host1.mydomain.com,host2.mydomain.com,host3.mydomain.com"".
By default this is set to localhost for local and pseudo-distributed modes
of operation. For a fully-distributed setup, this should be set to a full
list of ZooKeeper ensemble servers. If HBASE_MANAGES_ZK is set in hbase-env.sh,
this is the list of servers which hbase will start/stop ZooKeeper on as
part of cluster start/stop. Client-side, we will take this list of
ensemble members and put it together with the hbase.zookeeper.clientPort
config and pass it into zookeeper constructor as the connectString
parameter.
+
.Default
`localhost`
[[hbase.local.dir]]
*`hbase.local.dir`*::
+
.Description
Directory on the local filesystem to be used
as a local storage.
+
.Default
`${hbase.tmp.dir}/local/`
[[hbase.master.info.port]]
*`hbase.master.info.port`*::
+
.Description
The port for the HBase Master web UI.
Set to -1 if you do not want a UI instance run.
+
.Default
`16010`
[[hbase.master.info.bindAddress]]
*`hbase.master.info.bindAddress`*::
+
.Description
The bind address for the HBase Master web UI
+
.Default
`0.0.0.0`
[[hbase.master.logcleaner.plugins]]
*`hbase.master.logcleaner.plugins`*::
+
.Description
A comma-separated list of BaseLogCleanerDelegate invoked by
the LogsCleaner service. These WAL cleaners are called in order,
so put the cleaner that prunes the most files in front. To
implement your own BaseLogCleanerDelegate, just put it in HBase's classpath
and add the fully qualified class name here. Always add the above
default log cleaners in the list.
+
.Default
`org.apache.hadoop.hbase.master.cleaner.TimeToLiveLogCleaner`
[[hbase.master.logcleaner.ttl]]
*`hbase.master.logcleaner.ttl`*::
+
.Description
Maximum time a WAL can stay in the oldWALs directory,
after which it will be cleaned by a Master thread.
+
.Default
`600000`
[[hbase.master.hfilecleaner.plugins]]
*`hbase.master.hfilecleaner.plugins`*::
+
.Description
A comma-separated list of BaseHFileCleanerDelegate invoked by
the HFileCleaner service. These HFiles cleaners are called in order,
so put the cleaner that prunes the most files in front. To
implement your own BaseHFileCleanerDelegate, just put it in HBase's classpath
and add the fully qualified class name here. Always add the above
default log cleaners in the list as they will be overwritten in
hbase-site.xml.
+
.Default
`org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner`
[[hbase.master.infoserver.redirect]]
*`hbase.master.infoserver.redirect`*::
+
.Description
Whether or not the Master listens to the Master web
UI port (hbase.master.info.port) and redirects requests to the web
UI server shared by the Master and RegionServer.
+
.Default
`true`
[[hbase.regionserver.port]]
*`hbase.regionserver.port`*::
+
.Description
The port the HBase RegionServer binds to.
+
.Default
`16020`
[[hbase.regionserver.info.port]]
*`hbase.regionserver.info.port`*::
+
.Description
The port for the HBase RegionServer web UI
Set to -1 if you do not want the RegionServer UI to run.
+
.Default
`16030`
[[hbase.regionserver.info.bindAddress]]
*`hbase.regionserver.info.bindAddress`*::
+
.Description
The address for the HBase RegionServer web UI
+
.Default
`0.0.0.0`
[[hbase.regionserver.info.port.auto]]
*`hbase.regionserver.info.port.auto`*::
+
.Description
Whether or not the Master or RegionServer
UI should search for a port to bind to. Enables automatic port
search if hbase.regionserver.info.port is already in use.
Useful for testing, turned off by default.
+
.Default
`false`
[[hbase.regionserver.handler.count]]
*`hbase.regionserver.handler.count`*::
+
.Description
Count of RPC Listener instances spun up on RegionServers.
Same property is used by the Master for count of master handlers.
+
.Default
`30`
[[hbase.ipc.server.callqueue.handler.factor]]
*`hbase.ipc.server.callqueue.handler.factor`*::
+
.Description
Factor to determine the number of call queues.
A value of 0 means a single queue shared between all the handlers.
A value of 1 means that each handler has its own queue.
+
.Default
`0.1`
[[hbase.ipc.server.callqueue.read.ratio]]
*`hbase.ipc.server.callqueue.read.ratio`*::
+
.Description
Split the call queues into read and write queues.
The specified interval (which should be between 0.0 and 1.0)
will be multiplied by the number of call queues.
A value of 0 indicates to not split the call queues, meaning that both read and write
requests will be pushed to the same set of queues.
A value lower than 0.5 means that there will be less read queues than write queues.
A value of 0.5 means there will be the same number of read and write queues.
A value greater than 0.5 means that there will be more read queues than write queues.
A value of 1.0 means that all the queues except one are used to dispatch read requests.
Example: Given the total number of call queues being 10
a read.ratio of 0 means that: the 10 queues will contain both read/write requests.
a read.ratio of 0.3 means that: 3 queues will contain only read requests
and 7 queues will contain only write requests.
a read.ratio of 0.5 means that: 5 queues will contain only read requests
and 5 queues will contain only write requests.
a read.ratio of 0.8 means that: 8 queues will contain only read requests
and 2 queues will contain only write requests.
a read.ratio of 1 means that: 9 queues will contain only read requests
and 1 queues will contain only write requests.
+
.Default
`0`
[[hbase.ipc.server.callqueue.scan.ratio]]
*`hbase.ipc.server.callqueue.scan.ratio`*::
+
.Description
Given the number of read call queues, calculated from the total number
of call queues multiplied by the callqueue.read.ratio, the scan.ratio property
will split the read call queues into small-read and long-read queues.
A value lower than 0.5 means that there will be less long-read queues than short-read queues.
A value of 0.5 means that there will be the same number of short-read and long-read queues.
A value greater than 0.5 means that there will be more long-read queues than short-read queues
A value of 0 or 1 indicates to use the same set of queues for gets and scans.
Example: Given the total number of read call queues being 8
a scan.ratio of 0 or 1 means that: 8 queues will contain both long and short read requests.
a scan.ratio of 0.3 means that: 2 queues will contain only long-read requests
and 6 queues will contain only short-read requests.
a scan.ratio of 0.5 means that: 4 queues will contain only long-read requests
and 4 queues will contain only short-read requests.
a scan.ratio of 0.8 means that: 6 queues will contain only long-read requests
and 2 queues will contain only short-read requests.
+
.Default
`0`
[[hbase.regionserver.msginterval]]
*`hbase.regionserver.msginterval`*::
+
.Description
Interval between messages from the RegionServer to Master
in milliseconds.
+
.Default
`3000`
[[hbase.regionserver.regionSplitLimit]]
*`hbase.regionserver.regionSplitLimit`*::
+
.Description
Limit for the number of regions after which no more region
splitting should take place. This is not a hard limit for the number of
regions but acts as a guideline for the regionserver to stop splitting after
a certain limit. Default is MAX_INT; i.e. do not block splitting.
+
.Default
`2147483647`
[[hbase.regionserver.logroll.period]]
*`hbase.regionserver.logroll.period`*::
+
.Description
Period at which we will roll the commit log regardless
of how many edits it has.
+
.Default
`3600000`
[[hbase.regionserver.logroll.errors.tolerated]]
*`hbase.regionserver.logroll.errors.tolerated`*::
+
.Description
The number of consecutive WAL close errors we will allow
before triggering a server abort. A setting of 0 will cause the
region server to abort if closing the current WAL writer fails during
log rolling. Even a small value (2 or 3) will allow a region server
to ride over transient HDFS errors.
+
.Default
`2`
[[hbase.regionserver.hlog.reader.impl]]
*`hbase.regionserver.hlog.reader.impl`*::
+
.Description
The WAL file reader implementation.
+
.Default
`org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader`
[[hbase.regionserver.hlog.writer.impl]]
*`hbase.regionserver.hlog.writer.impl`*::
+
.Description
The WAL file writer implementation.
+
.Default
`org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter`
[[hbase.regionserver.global.memstore.size]]
*`hbase.regionserver.global.memstore.size`*::
+
.Description
Maximum size of all memstores in a region server before new
updates are blocked and flushes are forced. Defaults to 40% of heap.
Updates are blocked and flushes are forced until size of all memstores
in a region server hits hbase.regionserver.global.memstore.size.lower.limit.
+
.Default
`0.4`
[[hbase.regionserver.global.memstore.size.lower.limit]]
*`hbase.regionserver.global.memstore.size.lower.limit`*::
+
.Description
Maximum size of all memstores in a region server before flushes are forced.
Defaults to 95% of hbase.regionserver.global.memstore.size.
A 100% value for this property causes the minimum possible flushing to occur when updates are
blocked due to memstore limiting.
+
.Default
`0.95`
[[hbase.regionserver.optionalcacheflushinterval]]
*`hbase.regionserver.optionalcacheflushinterval`*::
+
.Description
Maximum amount of time an edit lives in memory before being automatically flushed.
Default 1 hour. Set it to 0 to disable automatic flushing.
+
.Default
`3600000`
[[hbase.regionserver.dns.interface]]
*`hbase.regionserver.dns.interface`*::
+
.Description
The name of the Network Interface from which a region server
should report its IP address.
+
.Default
`default`
[[hbase.regionserver.dns.nameserver]]
*`hbase.regionserver.dns.nameserver`*::
+
.Description
The host name or IP address of the name server (DNS)
which a region server should use to determine the host name used by the
master for communication and display purposes.
+
.Default
`default`
[[hbase.regionserver.region.split.policy]]
*`hbase.regionserver.region.split.policy`*::
+
.Description
A split policy determines when a region should be split. The various other split policies that
are available currently are ConstantSizeRegionSplitPolicy, DisabledRegionSplitPolicy,
DelimitedKeyPrefixRegionSplitPolicy, KeyPrefixRegionSplitPolicy,
BusyRegionSplitPolicy, SteppingSplitPolicy etc.
+
.Default
`org.apache.hadoop.hbase.regionserver.SteppingSplitPolicy`
[[zookeeper.session.timeout]]
*`zookeeper.session.timeout`*::
+
.Description
ZooKeeper session timeout in milliseconds. It is used in two different ways.
First, this value is used in the ZK client that HBase uses to connect to the ensemble.
It is also used by HBase when it starts a ZK server and it is passed as the 'maxSessionTimeout'. See
https://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkSessions.
For example, if an HBase region server connects to a ZK ensemble that's also managed
by HBase, then the
session timeout will be the one specified by this configuration. But, a region server that connects
to an ensemble managed with a different configuration will be subjected that ensemble's maxSessionTimeout. So,
even though HBase might propose using 90 seconds, the ensemble can have a max timeout lower than this and
it will take precedence. The current default maxSessionTimeout that ZK ships with is 40 seconds, which is lower than HBase's.
+
.Default
`90000`
[[zookeeper.znode.parent]]
*`zookeeper.znode.parent`*::
+
.Description
Root ZNode for HBase in ZooKeeper. All of HBase's ZooKeeper
files that are configured with a relative path will go under this node.
By default, all of HBase's ZooKeeper file path are configured with a
relative path, so they will all go under this directory unless changed.
+
.Default
`/hbase`
[[zookeeper.znode.acl.parent]]
*`zookeeper.znode.acl.parent`*::
+
.Description
Root ZNode for access control lists.
+
.Default
`acl`
[[hbase.zookeeper.dns.interface]]
*`hbase.zookeeper.dns.interface`*::
+
.Description
The name of the Network Interface from which a ZooKeeper server
should report its IP address.
+
.Default
`default`
[[hbase.zookeeper.dns.nameserver]]
*`hbase.zookeeper.dns.nameserver`*::
+
.Description
The host name or IP address of the name server (DNS)
which a ZooKeeper server should use to determine the host name used by the
master for communication and display purposes.
+
.Default
`default`
[[hbase.zookeeper.peerport]]
*`hbase.zookeeper.peerport`*::
+
.Description
Port used by ZooKeeper peers to talk to each other.
See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper
for more information.
+
.Default
`2888`
[[hbase.zookeeper.leaderport]]
*`hbase.zookeeper.leaderport`*::
+
.Description
Port used by ZooKeeper for leader election.
See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper
for more information.
+
.Default
`3888`
[[hbase.zookeeper.useMulti]]
*`hbase.zookeeper.useMulti`*::
+
.Description
Instructs HBase to make use of ZooKeeper's multi-update functionality.
This allows certain ZooKeeper operations to complete more quickly and prevents some issues
with rare Replication failure scenarios (see the release note of HBASE-2611 for an example).
IMPORTANT: only set this to true if all ZooKeeper servers in the cluster are on version 3.4+
and will not be downgraded. ZooKeeper versions before 3.4 do not support multi-update and
will not fail gracefully if multi-update is invoked (see ZOOKEEPER-1495).
+
.Default
`true`
[[hbase.zookeeper.property.initLimit]]
*`hbase.zookeeper.property.initLimit`*::
+
.Description
Property from ZooKeeper's config zoo.cfg.
The number of ticks that the initial synchronization phase can take.
+
.Default
`10`
[[hbase.zookeeper.property.syncLimit]]
*`hbase.zookeeper.property.syncLimit`*::
+
.Description
Property from ZooKeeper's config zoo.cfg.
The number of ticks that can pass between sending a request and getting an
acknowledgment.
+
.Default
`5`
[[hbase.zookeeper.property.dataDir]]
*`hbase.zookeeper.property.dataDir`*::
+
.Description
Property from ZooKeeper's config zoo.cfg.
The directory where the snapshot is stored.
+
.Default
`${hbase.tmp.dir}/zookeeper`
[[hbase.zookeeper.property.clientPort]]
*`hbase.zookeeper.property.clientPort`*::
+
.Description
Property from ZooKeeper's config zoo.cfg.
The port at which the clients will connect.
+
.Default
`2181`
[[hbase.zookeeper.property.maxClientCnxns]]
*`hbase.zookeeper.property.maxClientCnxns`*::
+
.Description
Property from ZooKeeper's config zoo.cfg.
Limit on number of concurrent connections (at the socket level) that a
single client, identified by IP address, may make to a single member of
the ZooKeeper ensemble. Set high to avoid zk connection issues running
standalone and pseudo-distributed.
+
.Default
`300`
[[hbase.client.write.buffer]]
*`hbase.client.write.buffer`*::
+
.Description
Default size of the BufferedMutator write buffer in bytes.
A bigger buffer takes more memory -- on both the client and server
side since server instantiates the passed write buffer to process
it -- but a larger buffer size reduces the number of RPCs made.
For an estimate of server-side memory-used, evaluate
hbase.client.write.buffer * hbase.regionserver.handler.count
+
.Default
`2097152`
[[hbase.client.pause]]
*`hbase.client.pause`*::
+
.Description
General client pause value. Used mostly as value to wait
before running a retry of a failed get, region lookup, etc.
See hbase.client.retries.number for description of how we backoff from
this initial pause amount and how this pause works w/ retries.
+
.Default
`100`
[[hbase.client.retries.number]]
*`hbase.client.retries.number`*::
+
.Description
Maximum retries. Used as maximum for all retryable
operations such as the getting of a cell's value, starting a row update,
etc. Retry interval is a rough function based on hbase.client.pause. At
first we retry at this interval but then with backoff, we pretty quickly reach
retrying every ten seconds. See HConstants#RETRY_BACKOFF for how the backup
ramps up. Change this setting and hbase.client.pause to suit your workload.
+
.Default
`35`
[[hbase.client.max.total.tasks]]
*`hbase.client.max.total.tasks`*::
+
.Description
The maximum number of concurrent tasks a single HTable instance will
send to the cluster.
+
.Default
`100`
[[hbase.client.max.perserver.tasks]]
*`hbase.client.max.perserver.tasks`*::
+
.Description
The maximum number of concurrent tasks a single HTable instance will
send to a single region server.
+
.Default
`2`
[[hbase.client.max.perregion.tasks]]
*`hbase.client.max.perregion.tasks`*::
+
.Description
The maximum number of concurrent connections the client will
maintain to a single Region. That is, if there is already
hbase.client.max.perregion.tasks writes in progress for this region, new puts
won't be sent to this region until some writes finish.
+
.Default
`1`
[[hbase.client.scanner.caching]]
*`hbase.client.scanner.caching`*::
+
.Description
Number of rows that will be fetched when calling next
on a scanner if it is not served from (local, client) memory. Higher
caching values will enable faster scanners but will eat up more memory
and some calls of next may take longer and longer times when the cache is empty.
Do not set this value such that the time between invocations is greater
than the scanner timeout; i.e. hbase.client.scanner.timeout.period
+
.Default
`100`
[[hbase.client.keyvalue.maxsize]]
*`hbase.client.keyvalue.maxsize`*::
+
.Description
Specifies the combined maximum allowed size of a KeyValue
instance. This is to set an upper boundary for a single entry saved in a
storage file. Since they cannot be split it helps avoiding that a region
cannot be split any further because the data is too large. It seems wise
to set this to a fraction of the maximum region size. Setting it to zero
or less disables the check.
+
.Default
`10485760`
[[hbase.client.scanner.timeout.period]]
*`hbase.client.scanner.timeout.period`*::
+
.Description
Client scanner lease period in milliseconds.
+
.Default
`60000`
[[hbase.client.localityCheck.threadPoolSize]]
*`hbase.client.localityCheck.threadPoolSize`*::
+
.Description
+
.Default
`2`
[[hbase.bulkload.retries.number]]
*`hbase.bulkload.retries.number`*::
+
.Description
Maximum retries. This is a maximum number of iterations
atomic bulk loads are attempted in the face of splitting operations,
0 means never give up.
+
.Default
`10`
[[hbase.compaction.after.bulkload.enable]]
*`hbase.compaction.after.bulkload.enable`*::
+
.Description
Request Compaction after bulkload immediately.
If bulkload is continuous, the triggered compactions may increase load,
bring about performance side effect.
(For HBase-2.x, the default value for ""hbase.compaction.after.bulkload.enable"" is true)
+
.Default
`false`
[[hbase.balancer.period
]]
*`hbase.balancer.period
`*::
+
.Description
Period at which the region balancer runs in the Master.
+
.Default
`300000`
[[hbase.regions.slop]]
*`hbase.regions.slop`*::
+
.Description
Rebalance if any regionserver has average + (average * slop) regions.
+
.Default
`0.2`
[[hbase.server.thread.wakefrequency]]
*`hbase.server.thread.wakefrequency`*::
+
.Description
Time to sleep in between searches for work (in milliseconds).
Used as sleep interval by service threads such as log roller.
+
.Default
`10000`
[[hbase.server.versionfile.writeattempts]]
*`hbase.server.versionfile.writeattempts`*::
+
.Description
How many time to retry attempting to write a version file
before just aborting. Each attempt is separated by the
hbase.server.thread.wakefrequency milliseconds.
+
.Default
`3`
[[hbase.hregion.memstore.flush.size]]
*`hbase.hregion.memstore.flush.size`*::
+
.Description
Memstore will be flushed to disk if size of the memstore
exceeds this number of bytes. Value is checked by a thread that runs
every hbase.server.thread.wakefrequency.
+
.Default
`134217728`
[[hbase.hregion.percolumnfamilyflush.size.lower.bound]]
*`hbase.hregion.percolumnfamilyflush.size.lower.bound`*::
+
.Description
If FlushLargeStoresPolicy is used, then every time that we hit the
total memstore limit, we find out all the column families whose memstores
exceed this value, and only flush them, while retaining the others whose
memstores are lower than this limit. If none of the families have their
memstore size more than this, all the memstores will be flushed
(just as usual). This value should be less than half of the total memstore
threshold (hbase.hregion.memstore.flush.size).
+
.Default
`16777216`
[[hbase.hregion.preclose.flush.size]]
*`hbase.hregion.preclose.flush.size`*::
+
.Description
If the memstores in a region are this size or larger when we go
to close, run a ""pre-flush"" to clear out memstores before we put up
the region closed flag and take the region offline. On close,
a flush is run under the close flag to empty memory. During
this time the region is offline and we are not taking on any writes.
If the memstore content is large, this flush could take a long time to
complete. The preflush is meant to clean out the bulk of the memstore
before putting up the close flag and taking the region offline so the
flush that runs under the close flag has little to do.
+
.Default
`5242880`
[[hbase.hregion.memstore.block.multiplier]]
*`hbase.hregion.memstore.block.multiplier`*::
+
.Description
Block updates if memstore has hbase.hregion.memstore.block.multiplier
times hbase.hregion.memstore.flush.size bytes. Useful preventing
runaway memstore during spikes in update traffic. Without an
upper-bound, memstore fills such that when it flushes the
resultant flush files take a long time to compact or split, or
worse, we OOME.
+
.Default
`4`
[[hbase.hregion.memstore.mslab.enabled]]
*`hbase.hregion.memstore.mslab.enabled`*::
+
.Description
Enables the MemStore-Local Allocation Buffer,
a feature which works to prevent heap fragmentation under
heavy write loads. This can reduce the frequency of stop-the-world
GC pauses on large heaps.
+
.Default
`true`
[[hbase.hregion.max.filesize]]
*`hbase.hregion.max.filesize`*::
+
.Description
Maximum file size. If the sum of the sizes of a region's HFiles has
grown to exceed this value, the region is split in two. There are two choices of
how this option works, the first is when any store's size exceed the threshold
then split, and the other is overall region's size exceed the threshold then split,
it can be configed by hbase.hregion.split.overallfiles.
+
.Default
`10737418240`
[[hbase.hregion.split.overallfiles]]
*`hbase.hregion.split.overallfiles`*::
+
.Description
If we should sum overall region files size when check to split.
+
.Default
`true`
[[hbase.hregion.majorcompaction]]
*`hbase.hregion.majorcompaction`*::
+
.Description
Time between major compactions, expressed in milliseconds. Set to 0 to disable
time-based automatic major compactions. User-requested and size-based major compactions will
still run. This value is multiplied by hbase.hregion.majorcompaction.jitter to cause
compaction to start at a somewhat-random time during a given window of time. The default value
is 7 days, expressed in milliseconds. If major compactions are causing disruption in your
environment, you can configure them to run at off-peak times for your deployment, or disable
time-based major compactions by setting this parameter to 0, and run major compactions in a
cron job or by another external mechanism.
+
.Default
`604800000`
[[hbase.hregion.majorcompaction.jitter]]
*`hbase.hregion.majorcompaction.jitter`*::
+
.Description
A multiplier applied to hbase.hregion.majorcompaction to cause compaction to occur
a given amount of time either side of hbase.hregion.majorcompaction. The smaller the number,
the closer the compactions will happen to the hbase.hregion.majorcompaction
interval.
+
.Default
`0.50`
[[hbase.hstore.compactionThreshold]]
*`hbase.hstore.compactionThreshold`*::
+
.Description
If more than this number of StoreFiles exist in any one Store
(one StoreFile is written per flush of MemStore), a compaction is run to rewrite all
StoreFiles into a single StoreFile. Larger values delay compaction, but when compaction does
occur, it takes longer to complete.
+
.Default
`3`
[[hbase.hstore.flusher.count]]
*`hbase.hstore.flusher.count`*::
+
.Description
The number of flush threads. With fewer threads, the MemStore flushes will be
queued. With more threads, the flushes will be executed in parallel, increasing the load on
HDFS, and potentially causing more compactions.
+
.Default
`2`
[[hbase.hstore.blockingStoreFiles]]
*`hbase.hstore.blockingStoreFiles`*::
+
.Description
If more than this number of StoreFiles exist in any one Store (one StoreFile
is written per flush of MemStore), updates are blocked for this region until a compaction is
completed, or until hbase.hstore.blockingWaitTime has been exceeded.
+
.Default
`10`
[[hbase.hstore.blockingWaitTime]]
*`hbase.hstore.blockingWaitTime`*::
+
.Description
The time for which a region will block updates after reaching the StoreFile limit
defined by hbase.hstore.blockingStoreFiles. After this time has elapsed, the region will stop
blocking updates even if a compaction has not been completed.
+
.Default
`90000`
[[hbase.hstore.compaction.min]]
*`hbase.hstore.compaction.min`*::
+
.Description
The minimum number of StoreFiles which must be eligible for compaction before
compaction can run. The goal of tuning hbase.hstore.compaction.min is to avoid ending up with
too many tiny StoreFiles to compact. Setting this value to 2 would cause a minor compaction
each time you have two StoreFiles in a Store, and this is probably not appropriate. If you
set this value too high, all the other values will need to be adjusted accordingly. For most
cases, the default value is appropriate. In previous versions of HBase, the parameter
hbase.hstore.compaction.min was named hbase.hstore.compactionThreshold.
+
.Default
`3`
[[hbase.hstore.compaction.max]]
*`hbase.hstore.compaction.max`*::
+
.Description
The maximum number of StoreFiles which will be selected for a single minor
compaction, regardless of the number of eligible StoreFiles. Effectively, the value of
hbase.hstore.compaction.max controls the length of time it takes a single compaction to
complete. Setting it larger means that more StoreFiles are included in a compaction. For most
cases, the default value is appropriate.
+
.Default
`10`
[[hbase.hstore.compaction.min.size]]
*`hbase.hstore.compaction.min.size`*::
+
.Description
A StoreFile smaller than this size will always be eligible for minor compaction.
HFiles this size or larger are evaluated by hbase.hstore.compaction.ratio to determine if
they are eligible. Because this limit represents the ""automatic include""limit for all
StoreFiles smaller than this value, this value may need to be reduced in write-heavy
environments where many StoreFiles in the 1-2 MB range are being flushed, because every
StoreFile will be targeted for compaction and the resulting StoreFiles may still be under the
minimum size and require further compaction. If this parameter is lowered, the ratio check is
triggered more quickly. This addressed some issues seen in earlier versions of HBase but
changing this parameter is no longer necessary in most situations. Default: 128 MB expressed
in bytes.
+
.Default
`134217728`
[[hbase.hstore.compaction.max.size]]
*`hbase.hstore.compaction.max.size`*::
+
.Description
A StoreFile larger than this size will be excluded from compaction. The effect of
raising hbase.hstore.compaction.max.size is fewer, larger StoreFiles that do not get
compacted often. If you feel that compaction is happening too often without much benefit, you
can try raising this value. Default: the value of LONG.MAX_VALUE, expressed in bytes.
+
.Default
`9223372036854775807`
[[hbase.hstore.compaction.ratio]]
*`hbase.hstore.compaction.ratio`*::
+
.Description
For minor compaction, this ratio is used to determine whether a given StoreFile
which is larger than hbase.hstore.compaction.min.size is eligible for compaction. Its
effect is to limit compaction of large StoreFiles. The value of hbase.hstore.compaction.ratio
is expressed as a floating-point decimal. A large ratio, such as 10, will produce a single
giant StoreFile. Conversely, a low value, such as .25, will produce behavior similar to the
BigTable compaction algorithm, producing four StoreFiles. A moderate value of between 1.0 and
1.4 is recommended. When tuning this value, you are balancing write costs with read costs.
Raising the value (to something like 1.4) will have more write costs, because you will
compact larger StoreFiles. However, during reads, HBase will need to seek through fewer
StoreFiles to accomplish the read. Consider this approach if you cannot take advantage of
Bloom filters. Otherwise, you can lower this value to something like 1.0 to reduce the
background cost of writes, and use Bloom filters to control the number of StoreFiles touched
during reads. For most cases, the default value is appropriate.
+
.Default
`1.2F`
[[hbase.hstore.compaction.ratio.offpeak]]
*`hbase.hstore.compaction.ratio.offpeak`*::
+
.Description
Allows you to set a different (by default, more aggressive) ratio for determining
whether larger StoreFiles are included in compactions during off-peak hours. Works in the
same way as hbase.hstore.compaction.ratio. Only applies if hbase.offpeak.start.hour and
hbase.offpeak.end.hour are also enabled.
+
.Default
`5.0F`
[[hbase.hstore.time.to.purge.deletes]]
*`hbase.hstore.time.to.purge.deletes`*::
+
.Description
The amount of time to delay purging of delete markers with future timestamps. If
unset, or set to 0, all delete markers, including those with future timestamps, are purged
during the next major compaction. Otherwise, a delete marker is kept until the major compaction
which occurs after the marker's timestamp plus the value of this setting, in milliseconds.
+
.Default
`0`
[[hbase.offpeak.start.hour]]
*`hbase.offpeak.start.hour`*::
+
.Description
The start of off-peak hours, expressed as an integer between 0 and 23, inclusive.
Set to -1 to disable off-peak.
+
.Default
`-1`
[[hbase.offpeak.end.hour]]
*`hbase.offpeak.end.hour`*::
+
.Description
The end of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set
to -1 to disable off-peak.
+
.Default
`-1`
[[hbase.regionserver.thread.compaction.throttle]]
*`hbase.regionserver.thread.compaction.throttle`*::
+
.Description
There are two different thread pools for compactions, one for large compactions and
the other for small compactions. This helps to keep compaction of lean tables (such as
hbase:meta) fast. If a compaction is larger than this threshold, it
goes into the large compaction pool. In most cases, the default value is appropriate. Default:
2 x hbase.hstore.compaction.max x hbase.hregion.memstore.flush.size (which defaults to 128MB).
The value field assumes that the value of hbase.hregion.memstore.flush.size is unchanged from
the default.
+
.Default
`2684354560`
[[hbase.hstore.compaction.kv.max]]
*`hbase.hstore.compaction.kv.max`*::
+
.Description
The maximum number of KeyValues to read and then write in a batch when flushing or
compacting. Set this lower if you have big KeyValues and problems with Out Of Memory
Exceptions Set this higher if you have wide, small rows.
+
.Default
`10`
[[hbase.storescanner.parallel.seek.enable]]
*`hbase.storescanner.parallel.seek.enable`*::
+
.Description
Enables StoreFileScanner parallel-seeking in StoreScanner,
a feature which can reduce response latency under special conditions.
+
.Default
`false`
[[hbase.storescanner.parallel.seek.threads]]
*`hbase.storescanner.parallel.seek.threads`*::
+
.Description
The default thread pool size if parallel-seeking feature enabled.
+
.Default
`10`
[[hfile.block.cache.size]]
*`hfile.block.cache.size`*::
+
.Description
Percentage of maximum heap (-Xmx setting) to allocate to block cache
used by a StoreFile. Default of 0.4 means allocate 40%.
Set to 0 to disable but it's not recommended; you need at least
enough cache to hold the storefile indices.
+
.Default
`0.4`
[[hfile.block.index.cacheonwrite]]
*`hfile.block.index.cacheonwrite`*::
+
.Description
This allows to put non-root multi-level index blocks into the block
cache at the time the index is being written.
+
.Default
`false`
[[hfile.index.block.max.size]]
*`hfile.index.block.max.size`*::
+
.Description
When the size of a leaf-level, intermediate-level, or root-level
index block in a multi-level block index grows to this size, the
block is written out and a new block is started.
+
.Default
`131072`
[[hbase.bucketcache.ioengine]]
*`hbase.bucketcache.ioengine`*::
+
.Description
Where to store the contents of the bucketcache. One of: offheap,
file, files, mmap or pmem. If a file or files, set it to file(s):PATH_TO_FILE.
mmap means the content will be in an mmaped file. Use mmap:PATH_TO_FILE.
'pmem' is bucket cache over a file on the persistent memory device.
Use pmem:PATH_TO_FILE.
See https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html
for more information.
+
.Default
``
[[hbase.bucketcache.combinedcache.enabled]]
*`hbase.bucketcache.combinedcache.enabled`*::
+
.Description
Whether or not the bucketcache is used in league with the LRU
on-heap block cache. In this mode, indices and blooms are kept in the LRU
blockcache and the data blocks are kept in the bucketcache.
+
.Default
`true`
[[hbase.bucketcache.size]]
*`hbase.bucketcache.size`*::
+
.Description
Used along with bucket cache, this is a float that EITHER represents a percentage of total heap
memory size to give to the cache (if < 1.0) OR, it is the capacity in megabytes of the cache.
(After HBase-2.0, ""hbase.bucketcache.size"" cannot be between 0-1)
+
.Default
`0` when specified as a float
[[hbase.bucketcache.bucket.sizes]]
*`hbase.bucketcache.bucket.sizes`*::
+
.Description
A comma-separated list of sizes for buckets for the bucketcache
if you use multiple sizes. Should be a list of block sizes in order from smallest
to largest. The sizes you use will depend on your data access patterns.
+
.Default
``
[[hfile.format.version]]
*`hfile.format.version`*::
+
.Description
The HFile format version to use for new files.
Version 3 adds support for tags in hfiles (See https://hbase.apache.org/book.html#hbase.tags).
Also see the configuration 'hbase.replication.rpc.codec'.
+
.Default
`3`
[[hfile.block.bloom.cacheonwrite]]
*`hfile.block.bloom.cacheonwrite`*::
+
.Description
Enables cache-on-write for inline blocks of a compound Bloom filter.
+
.Default
`false`
[[io.storefile.bloom.block.size]]
*`io.storefile.bloom.block.size`*::
+
.Description
The size in bytes of a single block (""chunk"") of a compound Bloom
filter. This size is approximate, because Bloom blocks can only be
inserted at data block boundaries, and the number of keys per data
block varies.
+
.Default
`131072`
[[hbase.rs.cacheblocksonwrite]]
*`hbase.rs.cacheblocksonwrite`*::
+
.Description
Whether an HFile block should be added to the block cache when the
block is finished.
+
.Default
`false`
[[hbase.rpc.timeout]]
*`hbase.rpc.timeout`*::
+
.Description
This is for the RPC layer to define how long HBase client applications
take for a remote call to time out. It uses pings to check connections
but will eventually throw a TimeoutException.
+
.Default
`60000`
[[hbase.rpc.shortoperation.timeout]]
*`hbase.rpc.shortoperation.timeout`*::
+
.Description
This is another version of ""hbase.rpc.timeout"". For those RPC operations
within cluster, we rely on this configuration to set a short timeout limitation
for short operations. For example, short rpc timeout for region server trying
to report to active master can benefit from quicker master failover process.
+
.Default
`10000`
[[hbase.ipc.client.tcpnodelay]]
*`hbase.ipc.client.tcpnodelay`*::
+
.Description
Set no delay on rpc socket connections. See
http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getTcpNoDelay--
+
.Default
`true`
[[hbase.master.keytab.file]]
*`hbase.master.keytab.file`*::
+
.Description
Full path to the kerberos keytab file to use for logging in
the configured HMaster server principal.
+
.Default
``
[[hbase.master.kerberos.principal]]
*`hbase.master.kerberos.principal`*::
+
.Description
Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name
that should be used to run the HMaster process. The principal name should
be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname
portion, it will be replaced with the actual hostname of the running
instance.
+
.Default
``
[[hbase.regionserver.keytab.file]]
*`hbase.regionserver.keytab.file`*::
+
.Description
Full path to the kerberos keytab file to use for logging in
the configured HRegionServer server principal.
+
.Default
``
[[hbase.regionserver.kerberos.principal]]
*`hbase.regionserver.kerberos.principal`*::
+
.Description
Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name
that should be used to run the HRegionServer process. The principal name
should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the
hostname portion, it will be replaced with the actual hostname of the
running instance. An entry for this principal must exist in the file
specified in hbase.regionserver.keytab.file
+
.Default
``
[[hadoop.policy.file]]
*`hadoop.policy.file`*::
+
.Description
The policy configuration file used by RPC servers to make
authorization decisions on client requests. Only used when HBase
security is enabled.
+
.Default
`hbase-policy.xml`
[[hbase.superuser]]
*`hbase.superuser`*::
+
.Description
List of users or groups (comma-separated), who are allowed
full privileges, regardless of stored ACLs, across the cluster.
Only used when HBase security is enabled.
+
.Default
``
[[hbase.auth.key.update.interval]]
*`hbase.auth.key.update.interval`*::
+
.Description
The update interval for master key for authentication tokens
in servers in milliseconds. Only used when HBase security is enabled.
+
.Default
`86400000`
[[hbase.auth.token.max.lifetime]]
*`hbase.auth.token.max.lifetime`*::
+
.Description
The maximum lifetime in milliseconds after which an
authentication token expires. Only used when HBase security is enabled.
+
.Default
`604800000`
[[hbase.ipc.client.fallback-to-simple-auth-allowed]]
*`hbase.ipc.client.fallback-to-simple-auth-allowed`*::
+
.Description
When a client is configured to attempt a secure connection, but attempts to
connect to an insecure server, that server may instruct the client to
switch to SASL SIMPLE (unsecure) authentication. This setting controls
whether or not the client will accept this instruction from the server.
When false (the default), the client will not allow the fallback to SIMPLE
authentication, and will abort the connection.
+
.Default
`false`
[[hbase.display.keys]]
*`hbase.display.keys`*::
+
.Description
When this is set to true the webUI and such will display all start/end keys
as part of the table details, region names, etc. When this is set to false,
the keys are hidden.
+
.Default
`true`
[[hbase.coprocessor.region.classes]]
*`hbase.coprocessor.region.classes`*::
+
.Description
A comma-separated list of Coprocessors that are loaded by
default on all tables. For any override coprocessor method, these classes
will be called in order. After implementing your own Coprocessor, just put
it in HBase's classpath and add the fully qualified class name here.
A coprocessor can also be loaded on demand by setting HTableDescriptor.
+
.Default
``
[[hbase.rest.port]]
*`hbase.rest.port`*::
+
.Description
The port for the HBase REST server.
+
.Default
`8080`
[[hbase.rest.readonly]]
*`hbase.rest.readonly`*::
+
.Description
Defines the mode the REST server will be started in. Possible values are:
false: All HTTP methods are permitted - GET/PUT/POST/DELETE.
true: Only the GET method is permitted.
+
.Default
`false`
[[hbase.rest.threads.max]]
*`hbase.rest.threads.max`*::
+
.Description
The maximum number of threads of the REST server thread pool.
Threads in the pool are reused to process REST requests. This
controls the maximum number of requests processed concurrently.
It may help to control the memory used by the REST server to
avoid OOM issues. If the thread pool is full, incoming requests
will be queued up and wait for some free threads.
+
.Default
`100`
[[hbase.rest.threads.min]]
*`hbase.rest.threads.min`*::
+
.Description
The minimum number of threads of the REST server thread pool.
The thread pool always has at least these number of threads so
the REST server is ready to serve incoming requests.
+
.Default
`2`
[[hbase.rest.support.proxyuser]]
*`hbase.rest.support.proxyuser`*::
+
.Description
Enables running the REST server to support proxy-user mode.
+
.Default
`false`
[[hbase.defaults.for.version.skip]]
*`hbase.defaults.for.version.skip`*::
+
.Description
Set to true to skip the 'hbase.defaults.for.version' check.
Setting this to true can be useful in contexts other than
the other side of a maven generation; i.e. running in an
ide. You'll want to set this boolean to true to avoid
seeing the RuntimeException complaint: ""hbase-default.xml file
seems to be for and old version of HBase (\\${hbase.version}), this
version is X.X.X-SNAPSHOT""
+
.Default
`false`
[[hbase.coprocessor.master.classes]]
*`hbase.coprocessor.master.classes`*::
+
.Description
A comma-separated list of
org.apache.hadoop.hbase.coprocessor.MasterObserver coprocessors that are
loaded by default on the active HMaster process. For any implemented
coprocessor methods, the listed classes will be called in order. After
implementing your own MasterObserver, just put it in HBase's classpath
and add the fully qualified class name here.
+
.Default
``
[[hbase.coprocessor.abortonerror]]
*`hbase.coprocessor.abortonerror`*::
+
.Description
Set to true to cause the hosting server (master or regionserver)
to abort if a coprocessor fails to load, fails to initialize, or throws an
unexpected Throwable object. Setting this to false will allow the server to
continue execution but the system wide state of the coprocessor in question
will become inconsistent as it will be properly executing in only a subset
of servers, so this is most useful for debugging only.
+
.Default
`true`
[[hbase.table.lock.enable]]
*`hbase.table.lock.enable`*::
+
.Description
Set to true to enable locking the table in zookeeper for schema change operations.
Table locking from master prevents concurrent schema modifications to corrupt table
state.
+
.Default
`true`
[[hbase.table.max.rowsize]]
*`hbase.table.max.rowsize`*::
+
.Description
Maximum size of single row in bytes (default is 1 Gb) for Get'ting
or Scan'ning without in-row scan flag set. If row size exceeds this limit
RowTooBigException is thrown to client.
+
.Default
`1073741824`
[[hbase.thrift.minWorkerThreads]]
*`hbase.thrift.minWorkerThreads`*::
+
.Description
The ""core size"" of the thread pool. New threads are created on every
connection until this many threads are created.
+
.Default
`16`
[[hbase.thrift.maxWorkerThreads]]
*`hbase.thrift.maxWorkerThreads`*::
+
.Description
The maximum size of the thread pool. When the pending request queue
overflows, new threads are created until their number reaches this number.
After that, the server starts dropping connections.
+
.Default
`1000`
[[hbase.thrift.maxQueuedRequests]]
*`hbase.thrift.maxQueuedRequests`*::
+
.Description
The maximum number of pending Thrift connections waiting in the queue. If
there are no idle threads in the pool, the server queues requests. Only
when the queue overflows, new threads are added, up to
hbase.thrift.maxQueuedRequests threads.
+
.Default
`1000`
[[hbase.regionserver.thrift.framed]]
*`hbase.regionserver.thrift.framed`*::
+
.Description
Use Thrift TFramedTransport on the server side.
This is the recommended transport for thrift servers and requires a similar setting
on the client side. Changing this to false will select the default transport,
vulnerable to DoS when malformed requests are issued due to THRIFT-601.
+
.Default
`false`
[[hbase.regionserver.thrift.framed.max_frame_size_in_mb]]
*`hbase.regionserver.thrift.framed.max_frame_size_in_mb`*::
+
.Description
Default frame size when using framed transport
+
.Default
`2`
[[hbase.regionserver.thrift.compact]]
*`hbase.regionserver.thrift.compact`*::
+
.Description
Use Thrift TCompactProtocol binary serialization protocol.
+
.Default
`false`
[[hbase.data.umask.enable]]
*`hbase.data.umask.enable`*::
+
.Description
Enable, if true, that file permissions should be assigned
to the files written by the regionserver
+
.Default
`false`
[[hbase.data.umask]]
*`hbase.data.umask`*::
+
.Description
File permissions that should be used to write data
files when hbase.data.umask.enable is true
+
.Default
`000`
[[hbase.snapshot.enabled]]
*`hbase.snapshot.enabled`*::
+
.Description
Set to true to allow snapshots to be taken / restored / cloned.
+
.Default
`true`
[[hbase.snapshot.restore.take.failsafe.snapshot]]
*`hbase.snapshot.restore.take.failsafe.snapshot`*::
+
.Description
Set to true to take a snapshot before the restore operation.
The snapshot taken will be used in case of failure, to restore the previous state.
At the end of the restore operation this snapshot will be deleted
+
.Default
`true`
[[hbase.snapshot.restore.failsafe.name]]
*`hbase.snapshot.restore.failsafe.name`*::
+
.Description
Name of the failsafe snapshot taken by the restore operation.
You can use the {snapshot.name}, {table.name} and {restore.timestamp} variables
to create a name based on what you are restoring.
+
.Default
`hbase-failsafe-{snapshot.name}-{restore.timestamp}`
[[hbase.server.compactchecker.interval.multiplier]]
*`hbase.server.compactchecker.interval.multiplier`*::
+
.Description
The number that determines how often we scan to see if compaction is necessary.
Normally, compactions are done after some events (such as memstore flush), but if
region didn't receive a lot of writes for some time, or due to different compaction
policies, it may be necessary to check it periodically. The interval between checks is
hbase.server.compactchecker.interval.multiplier multiplied by
hbase.server.thread.wakefrequency.
+
.Default
`1000`
[[hbase.lease.recovery.timeout]]
*`hbase.lease.recovery.timeout`*::
+
.Description
How long we wait on dfs lease recovery in total before giving up.
+
.Default
`900000`
[[hbase.lease.recovery.dfs.timeout]]
*`hbase.lease.recovery.dfs.timeout`*::
+
.Description
How long between dfs recovery lease invocations. Should be larger than the sum of
the time it takes for the namenode to issue a block recovery command as part of
datanode dfs.heartbeat.interval and the time it takes for the primary
datanode performing block recovery to timeout on a dead datanode, usually
dfs.client.socket-timeout. See the end of HBASE-8389 for more.
+
.Default
`64000`
[[hbase.column.max.version]]
*`hbase.column.max.version`*::
+
.Description
New column family descriptors will use this value as the default number of versions
to keep.
+
.Default
`1`
[[hbase.dfs.client.read.shortcircuit.buffer.size]]
*`hbase.dfs.client.read.shortcircuit.buffer.size`*::
+
.Description
If the DFSClient configuration
dfs.client.read.shortcircuit.buffer.size is unset, we will
use what is configured here as the short circuit read default
direct byte buffer size. DFSClient native default is 1MB; HBase
keeps its HDFS files open so number of file blocks * 1MB soon
starts to add up and threaten OOME because of a shortage of
direct memory. So, we set it down from the default. Make
it > the default hbase block size set in the HColumnDescriptor
which is usually 64k.
+
.Default
`131072`
[[hbase.regionserver.checksum.verify]]
*`hbase.regionserver.checksum.verify`*::
+
.Description
If set to true (the default), HBase verifies the checksums for hfile
blocks. HBase writes checksums inline with the data when it writes out
hfiles. HDFS (as of this writing) writes checksums to a separate file
than the data file necessitating extra seeks. Setting this flag saves
some on i/o. Checksum verification by HDFS will be internally disabled
on hfile streams when this flag is set. If the hbase-checksum verification
fails, we will switch back to using HDFS checksums (so do not disable HDFS
checksums! And besides this feature applies to hfiles only, not to WALs).
If this parameter is set to false, then hbase will not verify any checksums,
instead it will depend on checksum verification being done in the HDFS client.
+
.Default
`true`
[[hbase.hstore.bytes.per.checksum]]
*`hbase.hstore.bytes.per.checksum`*::
+
.Description
Number of bytes in a newly created checksum chunk for HBase-level
checksums in hfile blocks.
+
.Default
`16384`
[[hbase.hstore.checksum.algorithm]]
*`hbase.hstore.checksum.algorithm`*::
+
.Description
Name of an algorithm that is used to compute checksums. Possible values
are NULL, CRC32, CRC32C.
+
.Default
`CRC32`
[[hbase.status.published]]
*`hbase.status.published`*::
+
.Description
This setting activates the publication by the master of the status of the region server.
When a region server dies and its recovery starts, the master will push this information
to the client application, to let them cut the connection immediately instead of waiting
for a timeout.
+
.Default
`false`
[[hbase.status.publisher.class]]
*`hbase.status.publisher.class`*::
+
.Description
Implementation of the status publication with a multicast message.
+
.Default
`org.apache.hadoop.hbase.master.ClusterStatusPublisher$MulticastPublisher`
[[hbase.status.listener.class]]
*`hbase.status.listener.class`*::
+
.Description
Implementation of the status listener with a multicast message.
+
.Default
`org.apache.hadoop.hbase.client.ClusterStatusListener$MulticastListener`
[[hbase.status.multicast.address.ip]]
*`hbase.status.multicast.address.ip`*::
+
.Description
Multicast address to use for the status publication by multicast.
+
.Default
`226.1.1.3`
[[hbase.status.multicast.address.port]]
*`hbase.status.multicast.address.port`*::
+
.Description
Multicast port to use for the status publication by multicast.
+
.Default
`16100`
[[hbase.dynamic.jars.dir]]
*`hbase.dynamic.jars.dir`*::
+
.Description
The directory from which the custom filter/co-processor jars can be loaded
dynamically by the region server without the need to restart. However,
an already loaded filter/co-processor class would not be un-loaded. See
HBASE-1936 for more details.
+
.Default
`${hbase.rootdir}/lib`
[[hbase.security.authentication]]
*`hbase.security.authentication`*::
+
.Description
Controls whether or not secure authentication is enabled for HBase.
Possible values are 'simple' (no authentication), and 'kerberos'.
+
.Default
`simple`
[[hbase.rest.filter.classes]]
*`hbase.rest.filter.classes`*::
+
.Description
Servlet filters for REST service.
+
.Default
`org.apache.hadoop.hbase.rest.filter.GzipFilter`
[[hbase.master.loadbalancer.class]]
*`hbase.master.loadbalancer.class`*::
+
.Description
Class used to execute the regions balancing when the period occurs.
See the class comment for more on how it works
https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/master/balancer/StochasticLoadBalancer.html
It replaces the DefaultLoadBalancer as the default (since renamed
as the SimpleLoadBalancer).
+
.Default
`org.apache.hadoop.hbase.master.balancer.StochasticLoadBalancer`
[[hbase.security.exec.permission.checks]]
*`hbase.security.exec.permission.checks`*::
+
.Description
If this setting is enabled and ACL based access control is active (the
AccessController coprocessor is installed either as a system coprocessor
or on a table as a table coprocessor) then you must grant all relevant
users EXEC privilege if they require the ability to execute coprocessor
endpoint calls. EXEC privilege, like any other permission, can be
granted globally to a user, or to a user on a per table or per namespace
basis. For more information on coprocessor endpoints, see the coprocessor
section of the HBase online manual. For more information on granting or
revoking permissions using the AccessController, see the security
section of the HBase online manual.
+
.Default
`false`
[[hbase.procedure.regionserver.classes]]
*`hbase.procedure.regionserver.classes`*::
+
.Description
A comma-separated list of
org.apache.hadoop.hbase.procedure.RegionServerProcedureManager procedure managers that are
loaded by default on the active HRegionServer process. The lifecycle methods (init/start/stop)
will be called by the active HRegionServer process to perform the specific globally barriered
procedure. After implementing your own RegionServerProcedureManager, just put it in
HBase's classpath and add the fully qualified class name here.
+
.Default
``
[[hbase.procedure.master.classes]]
*`hbase.procedure.master.classes`*::
+
.Description
A comma-separated list of
org.apache.hadoop.hbase.procedure.MasterProcedureManager procedure managers that are
loaded by default on the active HMaster process. A procedure is identified by its signature and
users can use the signature and an instant name to trigger an execution of a globally barriered
procedure. After implementing your own MasterProcedureManager, just put it in HBase's classpath
and add the fully qualified class name here.
+
.Default
``
[[hbase.regionserver.storefile.refresh.period]]
*`hbase.regionserver.storefile.refresh.period`*::
+
.Description
The period (in milliseconds) for refreshing the store files for the secondary regions. 0
means this feature is disabled. Secondary regions sees new files (from flushes and
compactions) from primary once the secondary region refreshes the list of files in the
region (there is no notification mechanism). But too frequent refreshes might cause
extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL
(hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger
value is also recommended with this setting.
+
.Default
`0`
[[hbase.region.replica.replication.enabled]]
*`hbase.region.replica.replication.enabled`*::
+
.Description
Whether asynchronous WAL replication to the secondary region replicas is enabled or not.
If this is enabled, a replication peer named ""region_replica_replication"" will be created
which will tail the logs and replicate the mutations to region replicas for tables that
have region replication > 1. If this is enabled once, disabling this replication also
requires disabling the replication peer using shell or Admin java class.
Replication to secondary region replicas works over standard inter-cluster replication.
+
.Default
`false`
[[hbase.http.filter.initializers]]
*`hbase.http.filter.initializers`*::
+
.Description
A comma separated list of class names. Each class in the list must extend
org.apache.hadoop.hbase.http.FilterInitializer. The corresponding Filter will
be initialized. Then, the Filter will be applied to all user facing jsp
and servlet web pages.
The ordering of the list defines the ordering of the filters.
The default StaticUserWebFilter adds a user principal as defined by the
hbase.http.staticuser.user property.
+
.Default
`org.apache.hadoop.hbase.http.lib.StaticUserWebFilter`
[[hbase.security.visibility.mutations.checkauths]]
*`hbase.security.visibility.mutations.checkauths`*::
+
.Description
This property if enabled, will check whether the labels in the visibility expression are associated
with the user issuing the mutation
+
.Default
`false`
[[hbase.http.max.threads]]
*`hbase.http.max.threads`*::
+
.Description
The maximum number of threads that the HTTP Server will create in its
ThreadPool.
+
.Default
`16`
[[hbase.replication.rpc.codec]]
*`hbase.replication.rpc.codec`*::
+
.Description
The codec that is to be used when replication is enabled so that
the tags are also replicated. This is used along with HFileV3 which
supports tags in them. If tags are not used or if the hfile version used
is HFileV2 then KeyValueCodec can be used as the replication codec. Note that
using KeyValueCodecWithTags for replication when there are no tags causes no harm.
+
.Default
`org.apache.hadoop.hbase.codec.KeyValueCodecWithTags`
[[hbase.http.staticuser.user]]
*`hbase.http.staticuser.user`*::
+
.Description
The user name to filter as on static web filters
while rendering content. For example, the HDFS
web UI (user to be used for browsing files).
+
.Default
`dr.stack`
[[hbase.regionserver.handler.abort.on.error.percent]]
*`hbase.regionserver.handler.abort.on.error.percent`*::
+
.Description
The percent of region server RPC threads failed to abort RS.
-1 Disable aborting; 0 Abort if even a single handler has died;
0.x Abort only when this percent of handlers have died;
1 Abort only all of the handlers have died.
+
.Default
`0.5`
[[hbase.master.cleaner.snapshot.interval]]
*`hbase.master.cleaner.snapshot.interval`*::
+
.Description
Snapshot Cleanup chore interval in milliseconds.
The cleanup thread keeps running at this interval
to find all snapshots that are expired based on TTL
and delete them.
+
.Default
`1800000`
[[hbase.master.snapshot.ttl]]
*`hbase.master.snapshot.ttl`*::
+
.Description
Default Snapshot TTL to be considered when the user
does not specify TTL while creating snapshot.
Default value 0 indicates FOREVERE - snapshot should not be
automatically deleted until it is manually deleted
+
.Default
`0`
[[hbase.master.regions.recovery.check.interval]]
*`hbase.master.regions.recovery.check.interval`*::
+
.Description
Regions Recovery Chore interval in milliseconds.
This chore keeps running at this interval to
find all regions with configurable max store file ref count
and reopens them.
+
.Default
`1200000`
[[hbase.regions.recovery.store.file.ref.count]]
*`hbase.regions.recovery.store.file.ref.count`*::
+
.Description
Very large number of ref count on a compacted
store file indicates that it is a ref leak
on that object(compacted store file).
Such files can not be removed after
it is invalidated via compaction.
Only way to recover in such scenario is to
reopen the region which can release
all resources, like the refcount,
leases, etc. This config represents Store files Ref
Count threshold value considered for reopening
regions. Any region with compacted store files
ref count > this value would be eligible for
reopening by master. Here, we get the max
refCount among all refCounts on all
compacted away store files that belong to a
particular region. Default value -1 indicates
this feature is turned off. Only positive
integer value should be provided to
enable this feature.
+
.Default
`-1`
[[hbase.regionserver.slowlog.ringbuffer.size]]
*`hbase.regionserver.slowlog.ringbuffer.size`*::
+
.Description
Default size of ringbuffer to be maintained by each RegionServer in order
to store online slowlog responses. This is an in-memory ring buffer of
requests that were judged to be too slow in addition to the responseTooSlow
logging. The in-memory representation would be complete.
For more details, please look into Doc Section:
<>
+
.Default
`256`
[[hbase.regionserver.slowlog.buffer.enabled]]
*`hbase.regionserver.slowlog.buffer.enabled`*::
+
.Description
Indicates whether RegionServers have ring buffer running for storing
Online Slow logs in FIFO manner with limited entries. The size of
the ring buffer is indicated by config: hbase.regionserver.slowlog.ringbuffer.size
The default value is false, turn this on and get latest slowlog
responses with complete data.
For more details, please look into Doc Section:
<>
+
.Default
`false`
[[hbase.regionserver.slowlog.systable.enabled]]
*`hbase.regionserver.slowlog.systable.enabled`*::
+
.Description
Should be enabled only if hbase.regionserver.slowlog.buffer.enabled is enabled.
If enabled (true), all slow/large RPC logs would be persisted to system table
hbase:slowlog (in addition to in-memory ring buffer at each RegionServer).
The records are stored in increasing order of time.
Operators can scan the table with various combination of ColumnValueFilter and
time range.
More details are provided in the doc section:
""Get Slow/Large Response Logs from System table hbase:slowlog""
+
.Default
`false`
[[hbase.master.metafixer.max.merge.count]]
*`hbase.master.metafixer.max.merge.count`*::
+
.Description
Maximum regions to merge at a time when we fix overlaps noted in
CJ consistency report, but avoid merging 100 regions in one go!
+
.Default
`64`
[[hbase.rpc.rows.size.threshold.reject]]
*`hbase.rpc.rows.size.threshold.reject`*::
+
.Description
If value is true, RegionServer will abort batch requests of
Put/Delete with number of rows in a batch operation exceeding
threshold defined by value of config:
hbase.rpc.rows.warning.threshold.
The default value is false and hence, by default, only
warning will be logged. This config should be turned on to
prevent RegionServer from serving
very large batch size of rows and this way we can improve
CPU usages by discarding too large batch request.
+
.Default
`false`
[[hbase.master.balancer.decision.buffer.enabled]]
*`hbase.master.balancer.decision.buffer.enabled`*::
+
.Description
Indicates whether active HMaster has ring buffer running for storing
balancer decisions in FIFO manner with limited entries. The size of
the ring buffer is indicated by config:
hbase.master.balancer.decision.queue.size
+
.Default
`false`
[[hbase.master.balancer.rejection.buffer.enabled]]
*`hbase.master.balancer.rejection.buffer.enabled`*::
+
.Description
Indicates whether active HMaster has ring buffer running for storing
balancer rejection in FIFO manner with limited entries. The size of
the ring buffer is indicated by config:
hbase.master.balancer.rejection.queue.size
+
.Default
`false`
",16330,True,3054.8299308031183,median
"/**
* BigInteger
*
* An ActionScript 3 implementation of BigInteger (light version)
* Copyright (c) 2007 Henri Torgemane
*
* Derived from:
* The jsbn library, Copyright (c) 2003-2005 Tom Wu
*
* See LICENSE.txt for full license information.
*/
package com.hurlant.math
{
import com.hurlant.crypto.prng.Random;
import com.hurlant.util.Hex;
import com.hurlant.util.Memory;
import flash.utils.ByteArray;
use namespace bi_internal;
public class BigInteger
{
public static const DB:int = 30; // number of significant bits per chunk
public static const DV:int = (1< 0) {
if (p>p)>0) {
m = true;
r = d.toString(36);
}
while (i >= 0) {
if (p>(p+=DB-k);
} else {
d = (a[i]>>(p-=k))&km;
if (p<=0) {
p += DB;
--i;
}
}
if (d>0) {
m = true;
}
if (m) {
r += d.toString(36);
}
}
}
return m?r:""0"";
}
public function toArray(array:ByteArray):uint {
const k:int = 8;
const km:int = (1<<8)-1;
var d:int = 0;
var i:int = t;
var p:int = DB-(i*DB)%k;
var m:Boolean = false;
var c:int = 0;
if (i-- > 0) {
if (p>p)>0) {
m = true;
array.writeByte(d);
c++;
}
while (i >= 0) {
if (p>(p+=DB-k);
} else {
d = (a[i]>>(p-=k))&km;
if (p<=0) {
p += DB;
--i;
}
}
if (d>0) {
m = true;
}
if (m) {
array.writeByte(d);
c++;
}
}
}
return c;
}
/**
* best-effort attempt to fit into a Number.
* precision can be lost if it just can't fit.
*/
public function valueOf():Number {
if (s==-1) {
return -negate().valueOf();
}
var coef:Number = 1;
var value:Number = 0;
for (var i:uint=0;i v, - if this < v, 0 if equal
*/
public function compareTo(v:BigInteger):int {
var r:int = s - v.s;
if (r!=0) {
return r;
}
var i:int = t;
r = i-v.t;
if (r!=0) {
return r;
}
while (--i >=0) {
r=a[i]-v.a[i];
if (r != 0) return r;
}
return 0;
}
/**
* returns bit length of the integer x
*/
bi_internal function nbits(x:int):int {
var r:int = 1;
var t:int;
if ((t=x>>>16) != 0) { x = t; r += 16; }
if ((t=x>>8) != 0) { x = t; r += 8; }
if ((t=x>>4) != 0) { x = t; r += 4; }
if ((t=x>>2) != 0) { x = t; r += 2; }
if ((t=x>>1) != 0) { x = t; r += 1; }
return r;
}
/**
* returns the number of bits in this
*/
public function bitLength():int {
if (t<=0) return 0;
return DB*(t-1)+nbits(a[t-1]^(s&DM));
}
/**
*
* @param v
* @return this % v
*
*/
public function mod(v:BigInteger):BigInteger {
var r:BigInteger = nbi();
abs().divRemTo(v,null,r);
if (s<0 && r.compareTo(ZERO)>0) {
v.subTo(r,r);
}
return r;
}
/**
* this^e % m, 0 <= e < 2^32
*/
public function modPowInt(e:int, m:BigInteger):BigInteger {
var z:IReduction;
if (e<256 || m.isEven()) {
z = new ClassicReduction(m);
} else {
z = new MontgomeryReduction(m);
}
return exp(e, z);
}
/**
* copy this to r
*/
bi_internal function copyTo(r:BigInteger):void {
for (var i:int = t-1; i>=0; --i) {
r.a[i] = a[i];
}
r.t = t;
r.s = s;
}
/**
* set from integer value ""value"", -DV <= value < DV
*/
bi_internal function fromInt(value:int):void {
t = 1;
s = (value<0)?-1:0;
if (value>0) {
a[0] = value;
} else if (value<-1) {
a[0] = value+DV;
} else {
t = 0;
}
}
/**
* set from ByteArray and length,
* starting a current position
* If length goes beyond the array, pad with zeroes.
*/
bi_internal function fromArray(value:ByteArray, length:int, unsigned:Boolean = false):void {
var p:int = value.position;
var i:int = p+length;
var sh:int = 0;
const k:int = 8;
t = 0;
s = 0;
while (--i >= p) {
var x:int = i DB) {
a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh);
} else {
a[t-1] |= x<= DB) sh -= DB;
}
if (!unsigned && (value[0]&0x80)==0x80) {
s = -1;
if (sh > 0) {
a[t-1] |= ((1<<(DB-sh))-1)<0 && a[t-1]==c) {
--t;
}
}
/**
* r = this << n*DB
*/
bi_internal function dlShiftTo(n:int, r:BigInteger):void {
var i:int;
for (i=t-1; i>=0; --i) {
r.a[i+n] = a[i];
}
for (i=n-1; i>=0; --i) {
r.a[i] = 0;
}
r.t = t+n;
r.s = s;
}
/**
* r = this >> n*DB
*/
bi_internal function drShiftTo(n:int, r:BigInteger):void {
var i:int;
for (i=n; i=0; --i) {
r.a[i+ds+1] = (a[i]>>cbs)|c;
c = (a[i]&bm)<=0; --i) {
r.a[i] = 0;
}
r.a[ds] = c;
r.t = t+ds+1;
r.s = s;
r.clamp();
}
/**
* r = this >> n
*/
bi_internal function rShiftTo(n:int, r:BigInteger):void {
r.s = s;
var ds:int = n/DB;
if (ds >= t) {
r.t = 0;
return;
}
var bs:int = n%DB;
var cbs:int = DB-bs;
var bm:int = (1<>bs;
var i:int;
for (i=ds+1; i>bs;
}
if (bs>0) {
r.a[t-ds-1] |= (s&bm)<>= DB;
}
if (v.t < t) {
c -= v.s;
while (i< t) {
c+= a[i];
r.a[i++] = c&DM;
c >>= DB;
}
c += s;
} else {
c += s;
while (i < v.t) {
c -= v.a[i];
r.a[i++] = c&DM;
c >>= DB;
}
c -= v.s;
}
r.s = (c<0)?-1:0;
if (c<-1) {
r.a[i++] = DV+c;
} else if (c>0) {
r.a[i++] = c;
}
r.t = i;
r.clamp();
}
/**
* am: Compute w_j += (x*this_i), propagates carries,
* c is initial carry, returns final carry.
* c < 3*dvalue, x < 2*dvalue, this_i < dvalue
*/
bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int {
var xl:int = x&0x7fff;
var xh:int = x>>15;
while(--n >= 0) {
var l:int = a[i]&0x7fff;
var h:int = a[i++]>>15;
var m:int = xh*l + h*xl;
l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff);
c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
w.a[j++] = l&0x3fffffff;
}
return c;
}
/**
* r = this * v, r != this,a (HAC 14.12)
* ""this"" should be the larger one if appropriate
*/
bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void {
var x:BigInteger = abs();
var y:BigInteger = v.abs();
var i:int = x.t;
r.t = i+y.t;
while (--i >= 0) {
r.a[i] = 0;
}
for (i=0; i