code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package org.anderes.edu.gui.pm.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* View für das Presentation-Model-Pattern
*
* @author René Anderes
*/
public class View {
private final JFrame f;
private final JTextField textField;
private final JTextArea textArea;
private final PresentationModel presentationModel;
/**
* Konstruktor
*/
public View(final PresentationModel presentationModel) {
this.presentationModel = presentationModel;
f = new JFrame( "Taschenrechner" );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setSize(300, 200);
JPanel panel = new JPanel(new GridBagLayout());
textField = new JTextField(20);
textField.setBackground(Color.WHITE);
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textField.setText("");
if (text.matches("\\d+")) {
presentationModel.input(text);
updateStack();
} else if (presentationModel.isCommandEnabled()) {
presentationModel.command(text);
updateStack();
} else {
textField.setText("Ung�ltige Funktion");
textField.selectAll();
}
}
});
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
panel.add(textArea, c);
f.add(panel);
f.setVisible(true);
}
/**
* Die Anzeige des Stacks wird aktualisiert.
*/
private void updateStack() {
textArea.setText("");
for (Double d : presentationModel.getStack()) {
textArea.append(String.format("%1$f", d));
textArea.append("\n");
}
}
}
|
rene-anderes/edu
|
oo.basics/src/main/java/org/anderes/edu/gui/pm/gui/View.java
|
Java
|
apache-2.0
| 2,276 |
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package serviceaccount_test
import (
"crypto/rsa"
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/dgrijalva/jwt-go"
"k8s.io/kubernetes/pkg/api"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_1"
"k8s.io/kubernetes/pkg/client/testing/fake"
serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount"
"k8s.io/kubernetes/pkg/serviceaccount"
)
const otherPublicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArXz0QkIG1B5Bj2/W69GH
rsm5e+RC3kE+VTgocge0atqlLBek35tRqLgUi3AcIrBZ/0YctMSWDVcRt5fkhWwe
Lqjj6qvAyNyOkrkBi1NFDpJBjYJtuKHgRhNxXbOzTSNpdSKXTfOkzqv56MwHOP25
yP/NNAODUtr92D5ySI5QX8RbXW+uDn+ixul286PBW/BCrE4tuS88dA0tYJPf8LCu
sqQOwlXYH/rNUg4Pyl9xxhR5DIJR0OzNNfChjw60zieRIt2LfM83fXhwk8IxRGkc
gPZm7ZsipmfbZK2Tkhnpsa4QxDg7zHJPMsB5kxRXW0cQipXcC3baDyN9KBApNXa0
PwIDAQAB
-----END PUBLIC KEY-----`
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA249XwEo9k4tM8fMxV7zx
OhcrP+WvXn917koM5Qr2ZXs4vo26e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecI
zshKuv1gKIxbbLQMOuK1eA/4HALyEkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG
51RoiMgbQxaCyYxGfNLpLAZK9L0Tctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJU
j7OTh/AjjCnMnkgvKT2tpKxYQ59PgDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEi
B4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRM
WwIDAQAB
-----END PUBLIC KEY-----
`
const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA249XwEo9k4tM8fMxV7zxOhcrP+WvXn917koM5Qr2ZXs4vo26
e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecIzshKuv1gKIxbbLQMOuK1eA/4HALy
EkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG51RoiMgbQxaCyYxGfNLpLAZK9L0T
ctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJUj7OTh/AjjCnMnkgvKT2tpKxYQ59P
gDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEiB4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp
1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRMWwIDAQABAoIBAHJx8GqyCBDNbqk7
e7/hI9iE1S10Wwol5GH2RWxqX28cYMKq+8aE2LI1vPiXO89xOgelk4DN6urX6xjK
ZBF8RRIMQy/e/O2F4+3wl+Nl4vOXV1u6iVXMsD6JRg137mqJf1Fr9elg1bsaRofL
Q7CxPoB8dhS+Qb+hj0DhlqhgA9zG345CQCAds0ZYAZe8fP7bkwrLqZpMn7Dz9WVm
++YgYYKjuE95kPuup/LtWfA9rJyE/Fws8/jGvRSpVn1XglMLSMKhLd27sE8ZUSV0
2KUzbfRGE0+AnRULRrjpYaPu0XQ2JjdNvtkjBnv27RB89W9Gklxq821eH1Y8got8
FZodjxECgYEA93pz7AQZ2xDs67d1XLCzpX84GxKzttirmyj3OIlxgzVHjEMsvw8v
sjFiBU5xEEQDosrBdSknnlJqyiq1YwWG/WDckr13d8G2RQWoySN7JVmTQfXcLoTu
YGRiiTuoEi3ab3ZqrgGrFgX7T/cHuasbYvzCvhM2b4VIR3aSxU2DTUMCgYEA4x7J
T/ErP6GkU5nKstu/mIXwNzayEO1BJvPYsy7i7EsxTm3xe/b8/6cYOz5fvJLGH5mT
Q8YvuLqBcMwZardrYcwokD55UvNLOyfADDFZ6l3WntIqbA640Ok2g1X4U8J09xIq
ZLIWK1yWbbvi4QCeN5hvWq47e8sIj5QHjIIjRwkCgYEAyNqjltxFN9zmzPDa2d24
EAvOt3pYTYBQ1t9KtqImdL0bUqV6fZ6PsWoPCgt+DBuHb+prVPGP7Bkr/uTmznU/
+AlTO+12NsYLbr2HHagkXE31DEXE7CSLa8RNjN/UKtz4Ohq7vnowJvG35FCz/mb3
FUHbtHTXa2+bGBUOTf/5Hw0CgYBxw0r9EwUhw1qnUYJ5op7OzFAtp+T7m4ul8kCa
SCL8TxGsgl+SQ34opE775dtYfoBk9a0RJqVit3D8yg71KFjOTNAIqHJm/Vyyjc+h
i9rJDSXiuczsAVfLtPVMRfS0J9QkqeG4PIfkQmVLI/CZ2ZBmsqEcX+eFs4ZfPLun
Qsxe2QKBgGuPilIbLeIBDIaPiUI0FwU8v2j8CEQBYvoQn34c95hVQsig/o5z7zlo
UsO0wlTngXKlWdOcCs1kqEhTLrstf48djDxAYAxkw40nzeJOt7q52ib/fvf4/UBy
X024wzbiw1q07jFCyfQmODzURAx1VNT7QVUMdz/N8vy47/H40AZJ
-----END RSA PRIVATE KEY-----
`
func getPrivateKey(data string) *rsa.PrivateKey {
key, _ := jwt.ParseRSAPrivateKeyFromPEM([]byte(data))
return key
}
func getPublicKey(data string) *rsa.PublicKey {
key, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(data))
return key
}
func TestReadPrivateKey(t *testing.T) {
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(privateKey), os.FileMode(0600)); err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
if _, err := serviceaccount.ReadPrivateKey(f.Name()); err != nil {
t.Fatalf("error reading key: %v", err)
}
}
func TestReadPublicKey(t *testing.T) {
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(publicKey), os.FileMode(0600)); err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
if _, err := serviceaccount.ReadPublicKey(f.Name()); err != nil {
t.Fatalf("error reading key: %v", err)
}
}
func TestTokenGenerateAndValidate(t *testing.T) {
expectedUserName := "system:serviceaccount:test:my-service-account"
expectedUserUID := "12345"
// Related API objects
serviceAccount := &api.ServiceAccount{
ObjectMeta: api.ObjectMeta{
Name: "my-service-account",
UID: "12345",
Namespace: "test",
},
}
secret := &api.Secret{
ObjectMeta: api.ObjectMeta{
Name: "my-secret",
Namespace: "test",
},
}
// Generate the token
generator := serviceaccount.JWTTokenGenerator(getPrivateKey(privateKey))
token, err := generator.GenerateToken(*serviceAccount, *secret)
if err != nil {
t.Fatalf("error generating token: %v", err)
}
if len(token) == 0 {
t.Fatalf("no token generated")
}
// "Save" the token
secret.Data = map[string][]byte{
"token": []byte(token),
}
testCases := map[string]struct {
Client clientset.Interface
Keys []*rsa.PublicKey
ExpectedErr bool
ExpectedOK bool
ExpectedUserName string
ExpectedUserUID string
ExpectedGroups []string
}{
"no keys": {
Client: nil,
Keys: []*rsa.PublicKey{},
ExpectedErr: false,
ExpectedOK: false,
},
"invalid keys": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
"valid key": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"rotated keys": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey), getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"valid lookup": {
Client: fake.NewSimpleClientset(serviceAccount, secret),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"invalid secret lookup": {
Client: fake.NewSimpleClientset(serviceAccount),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
"invalid serviceaccount lookup": {
Client: fake.NewSimpleClientset(secret),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
}
for k, tc := range testCases {
getter := serviceaccountcontroller.NewGetterFromClient(tc.Client)
authenticator := serviceaccount.JWTTokenAuthenticator(tc.Keys, tc.Client != nil, getter)
user, ok, err := authenticator.AuthenticateToken(token)
if (err != nil) != tc.ExpectedErr {
t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err)
continue
}
if ok != tc.ExpectedOK {
t.Errorf("%s: Expected ok=%v, got %v", k, tc.ExpectedOK, ok)
continue
}
if err != nil || !ok {
continue
}
if user.GetName() != tc.ExpectedUserName {
t.Errorf("%s: Expected username=%v, got %v", k, tc.ExpectedUserName, user.GetName())
continue
}
if user.GetUID() != tc.ExpectedUserUID {
t.Errorf("%s: Expected userUID=%v, got %v", k, tc.ExpectedUserUID, user.GetUID())
continue
}
if !reflect.DeepEqual(user.GetGroups(), tc.ExpectedGroups) {
t.Errorf("%s: Expected groups=%v, got %v", k, tc.ExpectedGroups, user.GetGroups())
continue
}
}
}
func TestMakeSplitUsername(t *testing.T) {
username := serviceaccount.MakeUsername("ns", "name")
ns, name, err := serviceaccount.SplitUsername(username)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
if ns != "ns" || name != "name" {
t.Errorf("Expected ns/name, got %s/%s", ns, name)
}
invalid := []string{"test", "system:serviceaccount", "system:serviceaccount:", "system:serviceaccount:ns", "system:serviceaccount:ns:name:extra"}
for _, n := range invalid {
_, _, err := serviceaccount.SplitUsername("test")
if err == nil {
t.Errorf("Expected error for %s", n)
}
}
}
|
XiaoningDing/UbernetesPOC
|
pkg/serviceaccount/jwt_test.go
|
GO
|
apache-2.0
| 9,089 |
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
/// ls - related internal functions
const (
printDate = "2006-01-02 15:04:05 MST"
)
// ContentMessage container for content message structure.
type ContentMessage struct {
Filetype string `json:"type"`
Time time.Time `json:"lastModified"`
Size int64 `json:"size"`
Name string `json:"name"`
}
// String colorized string message
func (c ContentMessage) String() string {
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
message = func() string {
if c.Filetype == "folder" {
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name))
}
return message + console.Colorize("File", fmt.Sprintf("%s", c.Name))
}()
return message
}
// JSON jsonified content message
func (c ContentMessage) JSON() string {
jsonMessageBytes, e := json.Marshal(c)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// parseContent parse client Content container into printer struct.
func parseContent(c *client.Content) ContentMessage {
content := ContentMessage{}
content.Time = c.Time.Local()
// guess file type
content.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
// Convert OS Type to match console file printing style.
content.Name = func() string {
switch {
case runtime.GOOS == "windows":
c.Name = strings.Replace(c.Name, "/", "\\", -1)
c.Name = strings.TrimSuffix(c.Name, "\\")
default:
c.Name = strings.TrimSuffix(c.Name, "/")
}
if c.Type.IsDir() {
switch {
case runtime.GOOS == "windows":
return fmt.Sprintf("%s\\", c.Name)
default:
return fmt.Sprintf("%s/", c.Name)
}
}
return c.Name
}()
return content
}
// doList - list all entities inside a folder.
func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error {
var err *probe.Error
var parentContent *client.Content
urlStr := clnt.URL().String()
parentDir := url2Dir(urlStr)
parentClnt, err := url2Client(parentDir)
if err != nil {
return err.Trace(clnt.URL().String())
}
parentContent, err = parentClnt.Stat()
if err != nil {
return err.Trace(clnt.URL().String())
}
for contentCh := range clnt.List(recursive, false) {
if contentCh.Err != nil {
switch contentCh.Err.ToGoError().(type) {
// handle this specifically for filesystem
case client.BrokenSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.")
continue
}
if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) {
if contentCh.Content != nil {
if contentCh.Content.Type.IsDir() {
if contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink {
errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.")
continue
}
errorIf(contentCh.Err.Trace(), "Unable to list folder.")
}
} else {
errorIf(contentCh.Err.Trace(), "Unable to list.")
continue
}
}
err = contentCh.Err.Trace()
break
}
if multipleArgs && parentContent.Type.IsDir() {
contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name))
}
Prints("%s\n", parseContent(contentCh.Content))
}
if err != nil {
return err.Trace()
}
return nil
}
// doListIncomplete - list all incomplete uploads entities inside a folder.
func doListIncomplete(clnt client.Client, recursive, multipleArgs bool) *probe.Error {
var err *probe.Error
var parentContent *client.Content
parentContent, err = clnt.Stat()
if err != nil {
return err.Trace(clnt.URL().String())
}
for contentCh := range clnt.List(recursive, true) {
if contentCh.Err != nil {
switch contentCh.Err.ToGoError().(type) {
// handle this specifically for filesystem
case client.BrokenSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.")
continue
}
if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) {
if contentCh.Content != nil {
if contentCh.Content.Type.IsDir() && (contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink) {
errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.")
continue
}
}
errorIf(contentCh.Err.Trace(), "Unable to list.")
continue
}
err = contentCh.Err.Trace()
break
}
if multipleArgs && parentContent.Type.IsDir() {
contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name))
}
Prints("%s\n", parseContent(contentCh.Content))
}
if err != nil {
return err.Trace()
}
return nil
}
|
winchram/mc
|
ls.go
|
GO
|
apache-2.0
| 5,848 |
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import uiModal from 'angular-ui-bootstrap/src/modal';
import forcegraphComponent from './forcegraph.component';
let forcegraphModule = angular.module('forcegraph', [
uiRouter,
uiModal
])
.config(($stateProvider) => {
"ngInject";
$stateProvider
.state('forcegraph', {
url: '/forcegraph',
component: 'forcegraph'
});
})
.component('forcegraph', forcegraphComponent)
.name;
export default forcegraphModule;
|
garrettwong/GDashboard
|
client/app/components/d3visualizations/forcegraph/forcegraph.js
|
JavaScript
|
apache-2.0
| 510 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/iap/v1/service.proto
#include "google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.h"
#include "absl/memory/memory.h"
#include <memory>
namespace google {
namespace cloud {
namespace iap {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
using ::google::cloud::Idempotency;
IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy::
~IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() = default;
namespace {
class DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy
: public IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy {
public:
~DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() override =
default;
/// Create a new copy of this object.
std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>
clone() const override {
return absl::make_unique<
DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>(
*this);
}
Idempotency ListBrands(
google::cloud::iap::v1::ListBrandsRequest const&) override {
return Idempotency::kIdempotent;
}
Idempotency CreateBrand(
google::cloud::iap::v1::CreateBrandRequest const&) override {
return Idempotency::kNonIdempotent;
}
Idempotency GetBrand(
google::cloud::iap::v1::GetBrandRequest const&) override {
return Idempotency::kIdempotent;
}
Idempotency CreateIdentityAwareProxyClient(
google::cloud::iap::v1::CreateIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency ListIdentityAwareProxyClients(
google::cloud::iap::v1::ListIdentityAwareProxyClientsRequest) override {
return Idempotency::kIdempotent;
}
Idempotency GetIdentityAwareProxyClient(
google::cloud::iap::v1::GetIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kIdempotent;
}
Idempotency ResetIdentityAwareProxyClientSecret(
google::cloud::iap::v1::ResetIdentityAwareProxyClientSecretRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency DeleteIdentityAwareProxyClient(
google::cloud::iap::v1::DeleteIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kNonIdempotent;
}
};
} // namespace
std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>
MakeDefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() {
return absl::make_unique<
DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>();
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace iap
} // namespace cloud
} // namespace google
|
googleapis/google-cloud-cpp
|
google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.cc
|
C++
|
apache-2.0
| 3,353 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.referencing.operation;
import java.util.Collections;
import javax.xml.bind.JAXBException;
import org.opengis.util.FactoryException;
import org.opengis.referencing.crs.GeodeticCRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.CoordinateOperation;
import org.opengis.referencing.operation.MathTransformFactory;
import org.opengis.referencing.operation.NoninvertibleTransformException;
import org.apache.sis.referencing.operation.transform.EllipsoidToCentricTransform;
import org.apache.sis.referencing.datum.HardCodedDatum;
import org.apache.sis.referencing.crs.HardCodedCRS;
import org.apache.sis.internal.system.DefaultFactories;
import org.apache.sis.io.wkt.Convention;
import org.opengis.test.Validators;
import org.apache.sis.test.DependsOn;
import org.apache.sis.test.XMLTestCase;
import org.junit.Test;
import static org.apache.sis.test.MetadataAssert.*;
import static org.apache.sis.test.TestUtilities.getSingleton;
/**
* Tests the {@link DefaultConcatenatedOperation} class.
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.7
* @version 0.7
* @module
*/
@DependsOn({
DefaultTransformationTest.class,
SingleOperationMarshallingTest.class
})
public final strictfp class DefaultConcatenatedOperationTest extends XMLTestCase {
/**
* An XML file in this package containing a projected CRS definition.
*/
private static final String XML_FILE = "ConcatenatedOperation.xml";
/**
* Creates a “Tokyo to JGD2000” transformation.
*
* @see DefaultTransformationTest#createGeocentricTranslation()
*/
private static DefaultConcatenatedOperation createGeocentricTranslation() throws FactoryException, NoninvertibleTransformException {
final MathTransformFactory mtFactory = DefaultFactories.forBuildin(MathTransformFactory.class);
final DefaultTransformation op = DefaultTransformationTest.createGeocentricTranslation();
final DefaultConversion before = new DefaultConversion(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Geographic to geocentric"),
HardCodedCRS.TOKYO, // SourceCRS
op.getSourceCRS(), // TargetCRS
null, // InterpolationCRS
DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3),
EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.TOKYO.getEllipsoid(), true));
final DefaultConversion after = new DefaultConversion(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Geocentric to geographic"),
op.getTargetCRS(), // SourceCRS
HardCodedCRS.JGD2000, // TargetCRS
null, // InterpolationCRS
DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3),
EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.JGD2000.getEllipsoid(), true).inverse());
return new DefaultConcatenatedOperation(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Tokyo to JGD2000"),
new AbstractSingleOperation[] {before, op, after}, mtFactory);
}
/**
* Tests WKT formatting. The WKT format used here is not defined in OGC/ISO standards;
* this is a SIS-specific extension.
*
* @throws FactoryException if an error occurred while creating the test operation.
* @throws NoninvertibleTransformException if an error occurred while creating the test operation.
*/
@Test
public void testWKT() throws FactoryException, NoninvertibleTransformException {
final DefaultConcatenatedOperation op = createGeocentricTranslation();
assertWktEquals(Convention.WKT2_SIMPLIFIED, // Pseudo-WKT actually.
"ConcatenatedOperation[“Tokyo to JGD2000”,\n" +
" SourceCRS[GeodeticCRS[“Tokyo”,\n" +
" Datum[“Tokyo 1918”,\n" +
" Ellipsoid[“Bessel 1841”, 6377397.155, 299.1528128]],\n" +
" CS[ellipsoidal, 3],\n" +
" Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" +
" TargetCRS[GeodeticCRS[“JGD2000”,\n" +
" Datum[“Japanese Geodetic Datum 2000”,\n" +
" Ellipsoid[“GRS 1980”, 6378137.0, 298.257222101]],\n" +
" CS[ellipsoidal, 3],\n" +
" Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" +
" CoordinateOperationStep[“Geographic to geocentric”,\n" +
" Method[“Geographic/geocentric conversions”],\n" +
" Parameter[“semi_major”, 6377397.155, Unit[“metre”, 1]],\n" +
" Parameter[“semi_minor”, 6356078.962818189, Unit[“metre”, 1]]],\n" +
" CoordinateOperationStep[“Tokyo to JGD2000 (GSI)”,\n" +
" Method[“Geocentric translations”],\n" +
" Parameter[“X-axis translation”, -146.414],\n" +
" Parameter[“Y-axis translation”, 507.337],\n" +
" Parameter[“Z-axis translation”, 680.507]],\n" +
" CoordinateOperationStep[“Geocentric to geographic”,\n" +
" Method[“Geographic/geocentric conversions”],\n" +
" Parameter[“semi_major”, 6378137.0, Unit[“metre”, 1]],\n" +
" Parameter[“semi_minor”, 6356752.314140356, Unit[“metre”, 1]]]]", op);
}
/**
* Tests (un)marshalling of a concatenated operation.
*
* @throws JAXBException if an error occurred during (un)marshalling.
*/
@Test
public void testXML() throws JAXBException {
final DefaultConcatenatedOperation op = unmarshalFile(DefaultConcatenatedOperation.class, XML_FILE);
Validators.validate(op);
assertEquals("operations.size()", 2, op.getOperations().size());
final CoordinateOperation step1 = op.getOperations().get(0);
final CoordinateOperation step2 = op.getOperations().get(1);
final CoordinateReferenceSystem sourceCRS = op.getSourceCRS();
final CoordinateReferenceSystem targetCRS = op.getTargetCRS();
assertIdentifierEquals( "identifier", "test", "test", null, "concatenated", getSingleton(op .getIdentifiers()));
assertIdentifierEquals("sourceCRS.identifier", "test", "test", null, "source", getSingleton(sourceCRS.getIdentifiers()));
assertIdentifierEquals("targetCRS.identifier", "test", "test", null, "target", getSingleton(targetCRS.getIdentifiers()));
assertIdentifierEquals( "step1.identifier", "test", "test", null, "step-1", getSingleton(step1 .getIdentifiers()));
assertIdentifierEquals( "step2.identifier", "test", "test", null, "step-2", getSingleton(step2 .getIdentifiers()));
assertInstanceOf("sourceCRS", GeodeticCRS.class, sourceCRS);
assertInstanceOf("targetCRS", GeodeticCRS.class, targetCRS);
assertSame("sourceCRS", step1.getSourceCRS(), sourceCRS);
assertSame("targetCRS", step2.getTargetCRS(), targetCRS);
assertSame("tmp CRS", step1.getTargetCRS(), step2.getSourceCRS());
/*
* Test marshalling and compare with the original file.
*/
assertMarshalEqualsFile(XML_FILE, op, "xmlns:*", "xsi:schemaLocation");
}
}
|
desruisseaux/sis
|
core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/DefaultConcatenatedOperationTest.java
|
Java
|
apache-2.0
| 8,998 |
/*
*
* Copyright 2013 OpenStack Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package hudson.plugins.gearman;
import hudson.model.Hudson;
import hudson.model.Queue;
import hudson.model.Computer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NodeAvailabilityMonitor implements AvailabilityMonitor {
private final Queue queue;
private final Hudson hudson;
private final Computer computer;
private MyGearmanWorkerImpl workerHoldingLock = null;
private String expectedUUID = null;
private static final Logger logger = LoggerFactory
.getLogger(Constants.PLUGIN_LOGGER_NAME);
NodeAvailabilityMonitor(Computer computer)
{
this.computer = computer;
queue = Queue.getInstance();
hudson = Hudson.getInstance();
}
public Computer getComputer() {
return computer;
}
public void lock(MyGearmanWorkerImpl worker)
throws InterruptedException
{
logger.debug("AvailabilityMonitor lock request: " + worker);
while (true) {
boolean busy = false;
// Synchronize on the Jenkins queue so that Jenkins is
// unable to schedule builds while we try to acquire the
// lock.
synchronized(queue) {
if (workerHoldingLock == null) {
if (computer.countIdle() == 0) {
// If there are no idle executors, we can not
// schedule a build.
busy = true;
} else if (hudson.isQuietingDown()) {
busy = true;
} else {
logger.debug("AvailabilityMonitor got lock: " + worker);
workerHoldingLock = worker;
return;
}
} else {
busy = true;
}
}
if (busy) {
synchronized(this) {
// We get synchronous notification when a
// build finishes, but there are lots of other
// reasons circumstances could change (adding
// an executor, canceling shutdown, etc), so
// we slowly busy wait to cover all those
// reasons.
this.wait(5000);
}
}
}
}
public void unlock(MyGearmanWorkerImpl worker) {
logger.debug("AvailabilityMonitor unlock request: " + worker);
synchronized(queue) {
if (workerHoldingLock == worker) {
workerHoldingLock = null;
expectedUUID = null;
logger.debug("AvailabilityMonitor unlocked: " + worker);
} else {
logger.debug("Worker does not own AvailabilityMonitor lock: " +
worker);
}
}
wake();
}
public void wake() {
// Called when we know circumstances may have changed in a way
// that may allow someone to get the lock.
logger.debug("AvailabilityMonitor wake request");
synchronized(this) {
logger.debug("AvailabilityMonitor woken");
notifyAll();
}
}
public void expectUUID(String UUID) {
// The Gearman worker which holds the lock is about to
// schedule this build, so when Jenkins asks to run it, say
// "yes".
if (expectedUUID != null) {
logger.error("AvailabilityMonitor told to expect UUID " +
UUID + "while already expecting " + expectedUUID);
}
expectedUUID = UUID;
}
public boolean canTake(Queue.BuildableItem item)
{
// Jenkins calls this from within the scheduler maintenance
// function (while owning the queue monitor). If we are
// locked, only allow the build we are expecting to run.
logger.debug("AvailabilityMonitor canTake request for " +
workerHoldingLock);
NodeParametersAction param = item.getAction(NodeParametersAction.class);
if (param != null) {
logger.debug("AvailabilityMonitor canTake request for UUID " +
param.getUuid() + " expecting " + expectedUUID);
if (expectedUUID == param.getUuid()) {
return true;
}
}
return (workerHoldingLock == null);
}
}
|
hudson3-plugins/gearman-plugin
|
src/main/java/hudson/plugins/gearman/NodeAvailabilityMonitor.java
|
Java
|
apache-2.0
| 5,039 |
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
import org.yeastrc.ms.parser.DataProviderException;
import org.yeastrc.ms.parser.ms2File.Ms2FileReader;
import org.yeastrc.ms.util.Sha1SumCalculator;
/**
*
*/
public class MS2FileValidator {
private static final Logger log = Logger.getLogger(MS2FileValidator.class);
public static final int VALIDATION_ERR_SHA1SUM = 1;
public static final int VALIDATION_ERR_READ = 2;
public static final int VALIDATION_ERR_HEADER = 3;
public static final int VALIDATION_ERR_SCAN = 4;
public static final int VALID = 0;
public int validateFile(String filePath) {
log.info("VALIDATING file: "+filePath);
Ms2FileReader dataProvider = new Ms2FileReader();
String sha1sum = getSha1Sum(filePath);
if (sha1sum == null) {
log.error("ERROR calculating sha1sum for file: "+filePath+". EXITING...");
return VALIDATION_ERR_SHA1SUM;
}
// open the file
try {
dataProvider.open(filePath, sha1sum);
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_READ;
}
// read the header
try {
dataProvider.getRunHeader();
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_HEADER;
}
// read the scans
while (true) {
try {
if(dataProvider.getNextScan() == null)
break;
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_SCAN;
}
}
dataProvider.close();
return VALID;
}
private String getSha1Sum(String filePath) {
try {
return Sha1SumCalculator.instance().sha1SumFor(new File(filePath));
}
catch (IOException e) {
log.error(e.getMessage(), e);
return null;
}
catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);
return null;
}
}
}
|
yeastrc/msdapl
|
MS_LIBRARY/src/MS2FileValidator.java
|
Java
|
apache-2.0
| 2,486 |
package loadBalance;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.zip.Inflater;
/**
* Created by Administrator on 2017/1/17.
*/
public class IpMap {
public static Map<String, Integer> serverMap = new HashMap<String, Integer>();
static {
serverMap.put("192.168.1.1", 1);
serverMap.put("192.168.1.2", 2);
serverMap.put("192.168.1.3", 3);
}
public static Map<String, Integer> copy() {
return new HashMap<String, Integer>(serverMap);
}
}
|
yekevin/JavaPractise
|
src/loadBalance/IpMap.java
|
Java
|
apache-2.0
| 563 |
<?php
// Contact
$to = 'jasonekstromdev@gmail.com';
$subject = 'Job Opportunity';
if(isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_message'])){
$name = $_POST['c_name'];
$from = $_POST['c_email'];
$message = $_POST['c_message'];
if (mail($to, $subject, $message, $from)) {
$result = array(
'message' => 'Thanks for contacting me!',
'sendstatus' => 1
);
echo json_encode($result);
} else {
$result = array(
'message' => 'Sorry, something is wrong',
'sendstatus' => 1
);
echo json_encode($result);
}
}
?>
|
jmekstrom/Portfolio
|
assets/php/contactForm.php
|
PHP
|
apache-2.0
| 628 |
#
# Author:: Shawn Neal <sneal@daptiv.com>
# Cookbook Name:: visualstudio
# Recipe:: install
#
# Copyright 2013, Daptiv Solutions, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
::Chef::Recipe.send(:include, Visualstudio::Helper)
vs_is_installed = is_vs_installed?()
# Ensure the installation ISO url has been set by the user
if !node['visualstudio']['source']
raise 'visualstudio source attribute must be set before running this cookbook'
end
version = 'vs' + node['visualstudio']['version']
edition = node['visualstudio']['edition']
install_url = File.join(node['visualstudio']['source'], node['visualstudio'][edition]['filename'])
install_log_file = win_friendly_path(
File.join(node['visualstudio']['install_dir'], 'vsinstall.log'))
iso_extraction_dir = win_friendly_path(File.join(Chef::Config[:file_cache_path], version))
setup_exe_path = File.join(iso_extraction_dir, node['visualstudio'][edition]['installer_file'])
admin_deployment_xml_file = win_friendly_path(File.join(iso_extraction_dir, 'AdminDeployment.xml'))
# Extract the ISO image to the tmp dir
seven_zip_archive 'extract_vs_iso' do
path iso_extraction_dir
source install_url
overwrite true
checksum node['visualstudio'][edition]['checksum']
not_if { vs_is_installed }
end
# Create installation config file
cookbook_file admin_deployment_xml_file do
source version + '/AdminDeployment-' + edition + '.xml'
action :create
not_if { vs_is_installed }
end
# Install Visual Studio
windows_package node['visualstudio'][edition]['package_name'] do
source setup_exe_path
installer_type :custom
options "/Q /norestart /Log \"#{install_log_file}\" /AdminFile \"#{admin_deployment_xml_file}\""
notifies :delete, "directory[#{iso_extraction_dir}]"
timeout 3600 # 1hour
not_if { vs_is_installed }
end
# Cleanup extracted ISO files from tmp dir
directory iso_extraction_dir do
action :nothing
recursive true
not_if { node['visualstudio']['preserve_extracted_files'] }
end
|
dthagard/opschef-cookbook-visualstudio
|
recipes/install.rb
|
Ruby
|
apache-2.0
| 2,479 |
/**
* class for student
*/
'use strict'
const util = require('util')
const Person = require('./person');
function Student() {
Person.call(this);
}
// student继承自person
util.inherits(Student, Person);
Student.prototype.study = function() {
console.log('i am learning...');
};
module.exports = Student;
|
EvanDylan/node
|
base/mods/inhertis/student.js
|
JavaScript
|
apache-2.0
| 318 |
package module
import (
"net"
"sync"
)
type TCP_server struct {
Port uint16
NewAgent func(*TCPConn) Agent
ln net.Listener
mutexConns sync.Mutex
}
func (server *TCP_server) Start() {
}
|
swordhell/go_server
|
src/td.com/module/module.go
|
GO
|
apache-2.0
| 210 |
import * as Preact from '#preact';
import {boolean, number, select, withKnobs} from '@storybook/addon-knobs';
import {withAmp} from '@ampproject/storybook-addon';
export default {
title: 'amp-twitter-1_0',
decorators: [withKnobs, withAmp],
parameters: {
extensions: [
{
name: 'amp-twitter',
version: '1.0',
},
{
name: 'amp-bind',
version: '0.1',
},
],
experiments: ['bento'],
},
};
export const Default = () => {
const tweetId = select(
'tweet id',
['1356304203044499462', '495719809695621121', '463440424141459456'],
'1356304203044499462'
);
const cards = boolean('show cards', true) ? undefined : 'hidden';
const conversation = boolean('show conversation', false) ? undefined : 'none';
return (
<amp-twitter
width="300"
height="200"
data-tweetid={tweetId}
data-cards={cards}
data-conversation={conversation}
/>
);
};
export const Moments = () => {
const limit = number('limit to', 2);
return (
<amp-twitter
data-limit={limit}
data-momentid="1009149991452135424"
width="300"
height="200"
/>
);
};
export const Timelines = () => {
const tweetLimit = number('limit to', 5);
const timelineSourceType = select(
'source type',
['profile', 'likes', 'list', 'source', 'collection', 'url', 'widget'],
'profile'
);
const timelineScreenName = 'amphtml';
const timelineUserId = '3450662892';
return (
<amp-twitter
data-tweet-limit={tweetLimit}
data-timeline-source-type={timelineSourceType}
data-timeline-scree-name={timelineScreenName}
data-timeline-user-id={timelineUserId}
width="300"
height="200"
/>
);
};
export const DeletedTweet = () => {
const withFallback = boolean('include fallback?', true);
return (
<amp-twitter
width="390"
height="330"
layout="fixed"
data-tweetid="882818033403789316"
data-cards="hidden"
>
<blockquote placeholder>
<p lang="en" dir="ltr">
In case you missed it last week, check out our recap of AMP in 2020
⚡🙌
</p>
<p>
Watch here ➡️
<br />
<a href="https://t.co/eaxT3MuSAK">https://t.co/eaxT3MuSAK</a>
</p>
</blockquote>
{withFallback && (
<div fallback>
An error occurred while retrieving the tweet. It might have been
deleted.
</div>
)}
</amp-twitter>
);
};
export const InvalidTweet = () => {
return (
<amp-twitter
width="390"
height="330"
layout="fixed"
data-tweetid="1111111111111641653602164060160"
data-cards="hidden"
>
<blockquote placeholder class="twitter-tweet" data-lang="en">
<p>
This placeholder should never change because given tweet-id is
invalid.
</p>
</blockquote>
</amp-twitter>
);
};
export const MutatedTweetId = () => {
return (
<>
<button on="tap:AMP.setState({tweetid: '495719809695621121'})">
Change tweet
</button>
<amp-state id="tweetid">
<script type="application/json">1356304203044499462</script>
</amp-state>
<amp-twitter
width="375"
height="472"
layout="responsive"
data-tweetid="1356304203044499462"
data-amp-bind-data-tweetid="tweetid"
></amp-twitter>
</>
);
};
|
jpettitt/amphtml
|
extensions/amp-twitter/1.0/storybook/Basic.amp.js
|
JavaScript
|
apache-2.0
| 3,469 |
// This is a generated file. Not intended for manual editing.
package com.github.joshholl.intellij.csharp.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.github.joshholl.intellij.csharp.lang.lexer.CSharpTokenTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.github.joshholl.intellij.csharp.lang.psi.*;
public class CSharpImplicitAnonymousFunctionParameterListImpl extends ASTWrapperPsiElement implements CSharpImplicitAnonymousFunctionParameterList {
public CSharpImplicitAnonymousFunctionParameterListImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof CSharpVisitor) ((CSharpVisitor)visitor).visitImplicitAnonymousFunctionParameterList(this);
else super.accept(visitor);
}
@Override
@NotNull
public List<CSharpImplicitAnonymousFunctionParameter> getImplicitAnonymousFunctionParameterList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, CSharpImplicitAnonymousFunctionParameter.class);
}
}
|
joshholl/intellij-csharp
|
gen/com/github/joshholl/intellij/csharp/lang/psi/impl/CSharpImplicitAnonymousFunctionParameterListImpl.java
|
Java
|
apache-2.0
| 1,220 |
using System;
using ruibarbo.core.Search;
using ruibarbo.core.Wpf.Base;
namespace ruibarbo.core.Wpf.Helpers
{
public static class ComboBoxExtensions
{
public static void OpenAndClickFirst<TItem>(this IComboBox me)
where TItem : class, IComboBoxItem
{
OpenAndClickFirst<TItem>(me, By.Empty);
}
public static void OpenAndClickFirst<TItem>(this IComboBox me, params Func<IByBuilder<TItem>, By>[] byBuilders)
where TItem : class, IComboBoxItem
{
OpenAndClickFirst<TItem>(me, byBuilders.Build());
}
public static void OpenAndClickFirst<TItem>(this IComboBox me, params By[] bys)
where TItem : class, IComboBoxItem
{
var item = me.FindFirstItem<TItem>(bys);
item.OpenAndClick();
}
}
}
|
toroso/ruibarbo
|
ruibarbo.core/Wpf/Helpers/ComboBoxExtensions.cs
|
C#
|
apache-2.0
| 879 |
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.am.integration.tests.api.lifecycle;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* This class tests the behaviour of API when there is choice of selection between oauth2 and mutual ssl in API Manager.
*/
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
public class APISecurityTestCase extends APIManagerLifecycleBaseTest {
private final String API_NAME = "mutualsslAPI";
private final String API_NAME_2 = "mutualsslAPI2";
private final String API_CONTEXT = "mutualsslAPI";
private final String API_CONTEXT_2 = "mutualsslAPI2";
private final String API_END_POINT_METHOD = "/customers/123";
private final String API_VERSION_1_0_0 = "1.0.0";
private final String APPLICATION_NAME = "AccessibilityOfDeprecatedOldAPIAndPublishedCopyAPITestCase";
private String accessToken;
private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
private String apiEndPointUrl;
private String applicationId;
private String apiId1, apiId2;
@BeforeClass(alwaysRun = true)
public void initialize()
throws APIManagerIntegrationTestException, IOException, ApiException, org.wso2.am.integration.clients.store.api.ApiException, XPathExpressionException, AutomationUtilException {
super.init();
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
APIRequest apiRequest1 = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl));
apiRequest1.setVersion(API_VERSION_1_0_0);
apiRequest1.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest1.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest1.setTags(API_TAGS);
apiRequest1.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue());
APIOperationsDTO apiOperationsDTO1 = new APIOperationsDTO();
apiOperationsDTO1.setVerb("GET");
apiOperationsDTO1.setTarget("/customers/{id}");
apiOperationsDTO1.setAuthType("Application & Application User");
apiOperationsDTO1.setThrottlingPolicy("Unlimited");
List<APIOperationsDTO> operationsDTOS = new ArrayList<>();
operationsDTOS.add(apiOperationsDTO1);
apiRequest1.setOperationsDTOS(operationsDTOS);
List<String> securitySchemes = new ArrayList<>();
securitySchemes.add("mutualssl");
apiRequest1.setSecurityScheme(securitySchemes);
HttpResponse response1 = restAPIPublisher.addAPI(apiRequest1);
apiId1 = response1.getData();
String certOne = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
+ File.separator + "example.crt";
restAPIPublisher.uploadCertificate(new File(certOne), "example", apiId1, APIMIntegrationConstants.API_TIER.UNLIMITED);
APIRequest apiRequest2 = new APIRequest(API_NAME_2, API_CONTEXT_2, new URL(apiEndPointUrl));
apiRequest2.setVersion(API_VERSION_1_0_0);
apiRequest2.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest2.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest2.setTags(API_TAGS);
apiRequest2.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue());
apiRequest2.setOperationsDTOS(operationsDTOS);
List<String> securitySchemes2 = new ArrayList<>();
securitySchemes2.add("mutualssl");
securitySchemes2.add("oauth2");
securitySchemes2.add("api_key");
apiRequest2.setSecurityScheme(securitySchemes2);
HttpResponse response2 = restAPIPublisher.addAPI(apiRequest2);
apiId2 = response2.getData();
String certTwo = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
+ File.separator + "abcde.crt";
restAPIPublisher.uploadCertificate(new File(certTwo), "abcde", apiId2, APIMIntegrationConstants.API_TIER.UNLIMITED);
restAPIPublisher.changeAPILifeCycleStatus(apiId1, APILifeCycleAction.PUBLISH.getAction());
restAPIPublisher.changeAPILifeCycleStatus(apiId2, APILifeCycleAction.PUBLISH.getAction());
HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME,
"Test Application", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED,
ApplicationDTO.TokenTypeEnum.JWT);
applicationId = applicationResponse.getData();
restAPIStore.subscribeToAPI(apiId2, applicationId, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED);
ArrayList grantTypes = new ArrayList();
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD);
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(applicationId, "36000", "",
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
//get access token
accessToken = applicationKeyDTO.getToken().getAccessToken();
}
@Test(description = "This test case tests the behaviour of APIs that are protected with mutual SSL and OAuth2 "
+ "when the client certificate is not presented but OAuth2 token is presented.")
public void testCreateAndPublishAPIWithOAuth2() throws XPathExpressionException, IOException, JSONException {
// Create requestHeaders
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("accept", "application/json");
requestHeaders.put("Authorization", "Bearer " + accessToken);
HttpResponse apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
JSONObject response = new JSONObject(apiResponse.getData());
//fix test failure due to error code changes introduced in product-apim pull #7106
assertEquals(response.getJSONObject("fault").getInt("code"), 900901,
"API invocation succeeded with the access token without need for mutual ssl");
apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD,
requestHeaders);
assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
"API invocation failed for a test case with valid access token when the API is protected with "
+ "both mutual sso and oauth2");
}
@Test(description = "Testing the invocation with API Keys", dependsOnMethods = {"testCreateAndPublishAPIWithOAuth2"})
public void testInvocationWithApiKeys() throws Exception {
APIKeyDTO apiKeyDTO = restAPIStore
.generateAPIKeys(applicationId, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION.toString(), -1);
assertNotNull(apiKeyDTO, "API Key generation failed");
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("accept", "application/json");
requestHeaders.put("apikey", apiKeyDTO.getApikey());
HttpResponse apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD,
requestHeaders);
assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
"API invocation failed for a test case with valid api key when the API is protected with "
+ "API Keys");
}
// @Test(description = "This method tests the behaviour of APIs that are protected with mutual SSL and when the "
// + "authentication is done using mutual SSL", dependsOnMethods = "testCreateAndPublishAPIWithOAuth2")
// public void testAPIInvocationWithMutualSSL()
// throws IOException, XPathExpressionException, InterruptedException,
// NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {
// String expectedResponseData = "<id>123</id><name>John</name></Customer>";
// // We need to wait till the relevant listener reloads.
// Thread.sleep(60000);
// Map<String, String> requestHeaders = new HashMap<>();
// requestHeaders.put("accept", "text/xml");
// // Check with the correct client certificate for an API that is only protected with mutual ssl.
// HttpResponse response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "Mutual SSL Authentication has not succeeded");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
// /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, without
// an access token.*/
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED,
// "Mutual SSL Authentication has succeeded for a different certificate");
// /* Check with the correct client certificate for an API that is protected with mutual ssl and oauth2, without
// an access token.*/
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "test.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "Mutual SSL Authentication has not succeeded");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
//
// /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, with a
// correct access token.*/
// requestHeaders.put("Authorization", "Bearer " + accessToken);
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "OAuth2 authentication was not checked in the event of mutual SSL failure");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
// }
@AfterClass(alwaysRun = true)
public void cleanUpArtifacts() throws IOException, AutomationUtilException, ApiException {
restAPIStore.deleteApplication(applicationId);
restAPIPublisher.deleteAPI(apiId1);
restAPIPublisher.deleteAPI(apiId2);
}
}
|
jaadds/product-apim
|
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/APISecurityTestCase.java
|
Java
|
apache-2.0
| 14,024 |
using System;
using System.Net;
namespace Exceptionless.Api.Controllers {
public class PermissionResult {
public bool Allowed { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public HttpStatusCode StatusCode { get; set; }
public static PermissionResult Allow = new PermissionResult { Allowed = true, StatusCode = HttpStatusCode.OK };
public static PermissionResult Deny = new PermissionResult { Allowed = false, StatusCode = HttpStatusCode.BadRequest };
public static PermissionResult DenyWithNotFound(string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
StatusCode = HttpStatusCode.NotFound
};
}
public static PermissionResult DenyWithMessage(string message, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = HttpStatusCode.BadRequest
};
}
public static PermissionResult DenyWithStatus(HttpStatusCode statusCode, string message = null, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = statusCode
};
}
public static PermissionResult DenyWithPlanLimitReached(string message, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = HttpStatusCode.UpgradeRequired
};
}
}
}
|
adamzolotarev/Exceptionless
|
Source/Api/Controllers/Base/PermissionResult.cs
|
C#
|
apache-2.0
| 1,762 |
package org.apache.luke.client;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.apache.luke.client.data.FieldsDummyData;
import org.getopt.luke.KeepAllIndexDeletionPolicy;
import org.getopt.luke.KeepLastIndexDeletionPolicy;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class LukeInspector implements EntryPoint {
public static Version LV = Version.LUCENE_46;
private final static String solrIndexDir = "D:\\Projects\\information_retrieval\\solr\\solr-4.6.0\\solr-4.6.0\\example\\solr\\collection1\\data\\index";
private String pName = null;
private Directory dir = null;
private IndexReader ir = null;
private IndexSearcher is = null;
public void onModuleLoad() {
final RootPanel rootPanel = RootPanel.get();
CaptionPanel cptnpnlNewPanel = new CaptionPanel("New panel");
cptnpnlNewPanel.setCaptionHTML("Luke version 5.0");
rootPanel.add(cptnpnlNewPanel, 10, 10);
cptnpnlNewPanel.setSize("959px", "652px");
TabPanel tabPanel = new TabPanel();
cptnpnlNewPanel.setContentWidget(tabPanel);
tabPanel.setSize("5cm", "636px");
//LuceneIndexLoader.loadIndex(pName, this);
SplitLayoutPanel splitLayoutPanel = new SplitLayoutPanel();
tabPanel.add(splitLayoutPanel, "Index overview", false);
tabPanel.setVisible(true);
splitLayoutPanel.setSize("652px", "590px");
SplitLayoutPanel splitLayoutPanel_1 = new SplitLayoutPanel();
splitLayoutPanel.addNorth(splitLayoutPanel_1, 288.0);
Label lblIndexStatistics = new Label("Index statistics");
lblIndexStatistics.setDirectionEstimator(true);
lblIndexStatistics.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
splitLayoutPanel_1.addNorth(lblIndexStatistics, 26.0);
VerticalPanel verticalPanel = new VerticalPanel();
splitLayoutPanel_1.addWest(verticalPanel, 125.0);
Label lblTest = new Label("Index name:");
verticalPanel.add(lblTest);
lblTest.setWidth("109px");
Label lblTest_1 = new Label("# fields:");
verticalPanel.add(lblTest_1);
Label lblNumber = new Label("# documents:");
verticalPanel.add(lblNumber);
lblNumber.setWidth("101px");
Label lblTerms = new Label("# terms:");
verticalPanel.add(lblTerms);
Label lblHasDeletions = new Label("Has deletions?");
verticalPanel.add(lblHasDeletions);
Label lblNewLabel = new Label("Optimised?");
verticalPanel.add(lblNewLabel);
Label lblIndexVersion = new Label("Index version:");
verticalPanel.add(lblIndexVersion);
SplitLayoutPanel splitLayoutPanel_2 = new SplitLayoutPanel();
splitLayoutPanel.addWest(splitLayoutPanel_2, 240.0);
// Create name column.
TextColumn<Field> nameColumn = new TextColumn<Field>() {
@Override
public String getValue(Field field) {
return field.getName();
}
};
// Make the name column sortable.
nameColumn.setSortable(true);
// Create termCount column.
TextColumn<Field> termCountColumn = new TextColumn<Field>() {
@Override
public String getValue(Field contact) {
return contact.getTermCount();
}
};
// Create decoder column.
TextColumn<Field> decoderColumn = new TextColumn<Field>() {
@Override
public String getValue(Field contact) {
return contact.getDecoder();
}
};
final CellTable<Field> cellTable = new CellTable<Field>();
cellTable.addColumn(nameColumn, "Name");
cellTable.addColumn(termCountColumn, "Term count");
cellTable.addColumn(decoderColumn, "Decoder");
cellTable.setRowCount(FieldsDummyData.Fields.size(), true);
// Set the range to display. In this case, our visible range is smaller than
// the data set.
cellTable.setVisibleRange(0, 3);
// Create a data provider.
AsyncDataProvider<Field> dataProvider = new AsyncDataProvider<Field>() {
@Override
protected void onRangeChanged(HasData<Field> display) {
final Range range = display.getVisibleRange();
// Get the ColumnSortInfo from the table.
final ColumnSortList sortList = cellTable.getColumnSortList();
// This timer is here to illustrate the asynchronous nature of this data
// provider. In practice, you would use an asynchronous RPC call to
// request data in the specified range.
new Timer() {
@Override
public void run() {
int start = range.getStart();
int end = start + range.getLength();
// This sorting code is here so the example works. In practice, you
// would sort on the server.
Collections.sort(FieldsDummyData.Fields, new Comparator<Field>() {
public int compare(Field o1, Field o2) {
if (o1 == o2) {
return 0;
}
// Compare the name columns.
int diff = -1;
if (o1 != null) {
diff = (o2 != null) ? o1.getName().compareTo(o2.getName()) : 1;
}
return sortList.get(0).isAscending() ? diff : -diff;
}
});
List<Field> dataInRange = FieldsDummyData.Fields.subList(start, end);
// Push the data back into the list.
cellTable.setRowData(start, dataInRange);
}
}.schedule(2000);
}
};
// Connect the list to the data provider.
dataProvider.addDataDisplay(cellTable);
// Add a ColumnSortEvent.AsyncHandler to connect sorting to the
// AsyncDataPRrovider.
AsyncHandler columnSortHandler = new AsyncHandler(cellTable);
cellTable.addColumnSortHandler(columnSortHandler);
// We know that the data is sorted alphabetically by default.
cellTable.getColumnSortList().push(nameColumn);
splitLayoutPanel_2.add(cellTable);
SplitLayoutPanel splitLayoutPanel_3 = new SplitLayoutPanel();
splitLayoutPanel.addEast(splitLayoutPanel_3, 215.0);
StackPanel stackPanel = new StackPanel();
rootPanel.add(stackPanel, 714, 184);
stackPanel.setSize("259px", "239px");
FlowPanel flowPanel = new FlowPanel();
stackPanel.add(flowPanel, "Open index", false);
flowPanel.setSize("100%", "100%");
TextBox textBox = new TextBox();
flowPanel.add(textBox);
Button btnNewButton = new Button("...");
btnNewButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
DirectoryLister directoryLister = new DirectoryLister();
directoryLister.setPopupPosition(rootPanel.getAbsoluteLeft() + rootPanel.getOffsetWidth() / 2,
rootPanel.getAbsoluteTop() + rootPanel.getOffsetHeight() / 2);
directoryLister.show();
}
});
flowPanel.add(btnNewButton);
// exception handling
// credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void onUncaughtException(Throwable e) {
Window.alert("uncaught: " + e.getMessage());
String s = buildStackTrace(e, "RuntimeExceotion:\n");
Window.alert(s);
e.printStackTrace();
}
});
}
// showing the stacktrace
// credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
final String buildStackTrace(Throwable t, String log) {
// return "disabled";
if (t != null) {
log += t.getClass().toString();
log += t.getMessage();
//
StackTraceElement[] stackTrace = t.getStackTrace();
if (stackTrace != null) {
StringBuffer trace = new StringBuffer();
for (int i = 0; i < stackTrace.length; i++) {
trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "("
+ stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber());
}
log += trace.toString();
}
//
Throwable cause = t.getCause();
if (cause != null && cause != t) {
log += buildStackTrace(cause, "CausedBy:\n");
}
}
return log;
}
public Directory openDirectory(String dirImpl, String file, boolean create) throws Exception {
File f = new File(file);
if (!f.exists()) {
throw new Exception("Index directory doesn't exist.");
}
Directory res = null;
if (dirImpl == null || dirImpl.equals(Directory.class.getName()) || dirImpl.equals(FSDirectory.class.getName())) {
return FSDirectory.open(f);
}
try {
Class implClass = Class.forName(dirImpl);
Constructor<Directory> constr = implClass.getConstructor(File.class);
if (constr != null) {
res = constr.newInstance(f);
} else {
constr = implClass.getConstructor(File.class, LockFactory.class);
res = constr.newInstance(f, (LockFactory)null);
}
} catch (Throwable e) {
//errorMsg("Invalid directory implementation class: " + dirImpl + " " + e);
return null;
}
if (res != null) return res;
// fall-back to FSDirectory.
if (res == null) return FSDirectory.open(f);
return null;
}
/**
* open Lucene index and re-init all the sub-widgets
* @param name
* @param force
* @param dirImpl
* @param ro
* @param ramdir
* @param keepCommits
* @param point
* @param tiiDivisor
*/
public void openIndex(String name, boolean force, String dirImpl, boolean ro,
boolean ramdir, boolean keepCommits, IndexCommit point, int tiiDivisor) {
pName = name;
File baseFileDir = new File(name);
ArrayList<Directory> dirs = new ArrayList<Directory>();
Throwable lastException = null;
try {
Directory d = openDirectory(dirImpl, pName, false);
if (IndexWriter.isLocked(d)) {
if (!ro) {
if (force) {
IndexWriter.unlock(d);
} else {
//errorMsg("Index is locked. Try 'Force unlock' when opening.");
d.close();
d = null;
return;
}
}
}
boolean existsSingle = false;
// IR.indexExists doesn't report the cause of error
try {
new SegmentInfos().read(d);
existsSingle = true;
} catch (Throwable e) {
e.printStackTrace();
lastException = e;
//
}
if (!existsSingle) { // try multi
File[] files = baseFileDir.listFiles();
for (File f : files) {
if (f.isFile()) {
continue;
}
Directory d1 = openDirectory(dirImpl, f.toString(), false);
if (IndexWriter.isLocked(d1)) {
if (!ro) {
if (force) {
IndexWriter.unlock(d1);
} else {
//errorMsg("Index is locked. Try 'Force unlock' when opening.");
d1.close();
d1 = null;
return;
}
}
}
existsSingle = false;
try {
new SegmentInfos().read(d1);
existsSingle = true;
} catch (Throwable e) {
lastException = e;
e.printStackTrace();
}
if (!existsSingle) {
d1.close();
continue;
}
dirs.add(d1);
}
} else {
dirs.add(d);
}
if (dirs.size() == 0) {
if (lastException != null) {
//errorMsg("Invalid directory at the location, check console for more information. Last exception:\n" + lastException.toString());
} else {
//errorMsg("No valid directory at the location, try another location.\nCheck console for other possible causes.");
}
return;
}
if (ramdir) {
//showStatus("Loading index into RAMDirectory ...");
Directory dir1 = new RAMDirectory();
IndexWriterConfig cfg = new IndexWriterConfig(LV, new WhitespaceAnalyzer(LV));
IndexWriter iw1 = new IndexWriter(dir1, cfg);
iw1.addIndexes((Directory[])dirs.toArray(new Directory[dirs.size()]));
iw1.close();
//showStatus("RAMDirectory loading done!");
if (dir != null) dir.close();
dirs.clear();
dirs.add(dir1);
}
IndexDeletionPolicy policy;
if (keepCommits) {
policy = new KeepAllIndexDeletionPolicy();
} else {
policy = new KeepLastIndexDeletionPolicy();
}
ArrayList<DirectoryReader> readers = new ArrayList<DirectoryReader>();
for (Directory dd : dirs) {
DirectoryReader reader;
if (tiiDivisor > 1) {
reader = DirectoryReader.open(dd, tiiDivisor);
} else {
reader = DirectoryReader.open(dd);
}
readers.add(reader);
}
if (readers.size() == 1) {
ir = readers.get(0);
dir = ((DirectoryReader)ir).directory();
} else {
ir = new MultiReader((IndexReader[])readers.toArray(new IndexReader[readers.size()]));
}
is = new IndexSearcher(ir);
// XXX
//slowAccess = false;
//initOverview();
//initPlugins();
//showStatus("Index successfully open.");
} catch (Exception e) {
e.printStackTrace();
//errorMsg(e.getMessage());
return;
}
}
}
|
DmitryKey/luke-gwt
|
src/main/java/org/apache/luke/client/LukeInspector.java
|
Java
|
apache-2.0
| 17,271 |
angular.module('app').factory('Entity', function ($resource) {
var __apiBase__ = 'http://localhost:8080/GenericBackend/';
return {
Model : $resource(__apiBase__ + 'api/models/fqns'),
User : $resource(__apiBase__ + 'api/users/:id', {id: '@id', profileId :'@profileId'},{
getPermissions : {method : 'GET', url : __apiBase__ + 'api/userProfileRules/:profileId/allowedPermissions', isArray : true},
changePassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/changePassword', isArray : false},
resetPassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/resetPassword', isArray : false},
activate : {method : 'POST', url : __apiBase__ + 'api/users/:id/activate', isArray : false},
deactivate : {method : 'POST', url : __apiBase__ + 'api/users/:id/deactivate', isArray : false}
}),
Authentication : $resource(__apiBase__ + 'api/authentication/:id', {id: '@id', newStatus:'@newStatus'},{
login : {method : 'POST', url : __apiBase__ + 'api/authentication/login'},
logout : {method : 'POST', url : __apiBase__ + 'api/authentication/logout'},
getLoggedInUser : {method : 'GET', url : __apiBase__ + 'api/authentication/loggedinUser'}
}),
Role : $resource(__apiBase__ + 'api/roles/:id', {id: '@id'}),
Profile : $resource(__apiBase__ + 'api/profiles/:id', {id: '@id'}),
UserProfileRule : $resource(__apiBase__ + 'api/userProfileRules/:id', {id: '@id', newStatus:'@newStatus'},{
togglePermission : {method : 'POST', url : __apiBase__ + 'api/userProfileRules/:id/toggleStatus'}
}),
SchemeAccess : $resource(__apiBase__ + 'api/schemeAccess/:id', {id: '@id'}, {
toggleAccess : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/toggleAccess'},
switchOrganization : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/switchScheme'},
}),
UserOrganization : $resource(__apiBase__ + 'api/userOrganizations/:id', {id: '@id'}),
Permission : $resource(__apiBase__ + 'api/permissions/:id', {id: '@id'}, {
createPermissions : {method : 'POST', url : 'api/permissions/createPermissions'}
}),
UserPermission : $resource(__apiBase__ + 'api/user_permissions/:userId', {id: '@userId'}),
SQLExecutor : $resource(__apiBase__ + 'api/sqlExecutor/:id', {id: '@id'},{
execute : {method : 'POST', url : __apiBase__ + 'api/sqlExecutor/execute', isArray: true}
})
}
}
);
|
kodero/generic-angular-frontend
|
app/common/services/EntityFactory.js
|
JavaScript
|
apache-2.0
| 2,708 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "subprocess.h"
#include <stdio.h>
#include <algorithm>
#include "util.h"
namespace {
void Win32Fatal(const char* function) {
Fatal("%s: %s", function, GetLastErrorString().c_str());
}
} // anonymous namespace
Subprocess::Subprocess() : child_(NULL) , overlapped_() {
}
Subprocess::~Subprocess() {
// Reap child if forgotten.
if (child_)
Finish();
}
HANDLE Subprocess::SetupPipe(HANDLE ioport) {
char pipe_name[100];
snprintf(pipe_name, sizeof(pipe_name),
"\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);
pipe_ = ::CreateNamedPipeA(pipe_name,
PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE,
PIPE_UNLIMITED_INSTANCES,
0, 0, INFINITE, NULL);
if (pipe_ == INVALID_HANDLE_VALUE)
Win32Fatal("CreateNamedPipe");
if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
Win32Fatal("CreateIoCompletionPort");
memset(&overlapped_, 0, sizeof(overlapped_));
if (!ConnectNamedPipe(pipe_, &overlapped_) &&
GetLastError() != ERROR_IO_PENDING) {
Win32Fatal("ConnectNamedPipe");
}
// Get the write end of the pipe as a handle inheritable across processes.
HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, 0, NULL);
HANDLE output_write_child;
if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
GetCurrentProcess(), &output_write_child,
0, TRUE, DUPLICATE_SAME_ACCESS)) {
Win32Fatal("DuplicateHandle");
}
CloseHandle(output_write_handle);
return output_write_child;
}
bool Subprocess::Start(SubprocessSet* set, const string& command) {
HANDLE child_pipe = SetupPipe(set->ioport_);
STARTUPINFOA startup_info;
memset(&startup_info, 0, sizeof(startup_info));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdOutput = child_pipe;
// TODO: what does this hook up stdin to?
startup_info.hStdInput = NULL;
// TODO: is it ok to reuse pipe like this?
startup_info.hStdError = child_pipe;
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof(process_info));
// Do not prepend 'cmd /c' on Windows, this breaks command
// lines greater than 8,191 chars.
if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
/* inherit handles */ TRUE, 0,
NULL, NULL,
&startup_info, &process_info)) {
Win32Fatal("CreateProcess");
}
// Close pipe channel only used by the child.
if (child_pipe)
CloseHandle(child_pipe);
CloseHandle(process_info.hThread);
child_ = process_info.hProcess;
return true;
}
void Subprocess::OnPipeReady() {
DWORD bytes;
if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
CloseHandle(pipe_);
pipe_ = NULL;
return;
}
Win32Fatal("GetOverlappedResult");
}
if (bytes)
buf_.append(overlapped_buf_, bytes);
memset(&overlapped_, 0, sizeof(overlapped_));
if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
&bytes, &overlapped_)) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
CloseHandle(pipe_);
pipe_ = NULL;
return;
}
if (GetLastError() != ERROR_IO_PENDING)
Win32Fatal("ReadFile");
}
// Even if we read any bytes in the readfile call, we'll enter this
// function again later and get them at that point.
}
bool Subprocess::Finish() {
// TODO: add error handling for all of these.
WaitForSingleObject(child_, INFINITE);
DWORD exit_code = 0;
GetExitCodeProcess(child_, &exit_code);
CloseHandle(child_);
child_ = NULL;
return exit_code == 0;
}
bool Subprocess::Done() const {
return pipe_ == NULL;
}
const string& Subprocess::GetOutput() const {
return buf_;
}
SubprocessSet::SubprocessSet() {
ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
if (!ioport_)
Win32Fatal("CreateIoCompletionPort");
}
SubprocessSet::~SubprocessSet() {
CloseHandle(ioport_);
}
void SubprocessSet::Add(Subprocess* subprocess) {
running_.push_back(subprocess);
}
void SubprocessSet::DoWork() {
DWORD bytes_read;
Subprocess* subproc;
OVERLAPPED* overlapped;
if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
&overlapped, INFINITE)) {
if (GetLastError() != ERROR_BROKEN_PIPE)
Win32Fatal("GetQueuedCompletionStatus");
}
subproc->OnPipeReady();
if (subproc->Done()) {
vector<Subprocess*>::iterator end =
std::remove(running_.begin(), running_.end(), subproc);
if (running_.end() != end) {
finished_.push(subproc);
running_.resize(end - running_.begin());
}
}
}
Subprocess* SubprocessSet::NextFinished() {
if (finished_.empty())
return NULL;
Subprocess* subproc = finished_.front();
finished_.pop();
return subproc;
}
|
nornagon/ninja
|
src/subprocess-win32.cc
|
C++
|
apache-2.0
| 5,723 |
package org.omg.CosNaming.NamingContextPackage;
/**
* org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/CosNaming/nameservice.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/
abstract public class NotEmptyHelper
{
private static String _id = "IDL:omg.org/CosNaming/NamingContext/NotEmpty:1.0";
public static void insert (org.omg.CORBA.Any a, NotEmpty that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static NotEmpty extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (NotEmptyHelper.id (), "NotEmpty", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static NotEmpty read (org.omg.CORBA.portable.InputStream istream)
{
NotEmpty value = new NotEmpty ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, NotEmpty value)
{
// write the repository ID
ostream.write_string (id ());
}
}
|
wangsongpeng/jdk-src
|
src/main/java/org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java
|
Java
|
apache-2.0
| 2,045 |
//-------------------------------------------------------------------------------
// <copyright file="InMemoryTraceListener.cs" company="frokonet.ch">
// Copyright (C) frokonet.ch, 2014-2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace SimpleDomain.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
/// <summary>
/// A trace listener which holds all traced messages in a list
/// </summary>
public class InMemoryTraceListener : TraceListener
{
private static readonly Lazy<InMemoryTraceListener> InternalInstance = new Lazy<InMemoryTraceListener>(() => new InMemoryTraceListener());
private static readonly List<string> InternalLogMessages = new List<string>();
private static bool locked;
/// <summary>
/// Gets a singleton instance of this class
/// </summary>
public static TraceListener Instance => InternalInstance.Value;
/// <summary>
/// Gets all recorded log messages
/// </summary>
public static IEnumerable<string> LogMessages => InternalLogMessages;
/// <summary>
/// Clears all recorded log messages
/// </summary>
public static void ClearLogMessages()
{
WaitForUnlock();
InternalLogMessages.Clear();
}
/// <summary>
/// Locks the listener
/// </summary>
public static void Lock()
{
locked = true;
}
/// <summary>
/// Unlocks the listener
/// </summary>
public static void Unlock()
{
locked = false;
}
/// <inheritdoc />
public override void Write(string message)
{
WaitForUnlock();
InternalLogMessages.Add(message);
}
/// <inheritdoc />
public override void WriteLine(string message)
{
WaitForUnlock();
InternalLogMessages.Add(message);
}
private static void WaitForUnlock()
{
while (locked)
{
Thread.Sleep(100);
}
}
}
}
|
froko/SimpleDomain
|
src/SimpleDomain/Common/InMemoryTraceListener.cs
|
C#
|
apache-2.0
| 2,853 |
package com.jan.flc.firstlinecode.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.jan.flc.firstlinecode.R;
/**
* Created by huangje on 17-3-8.
*/
public class UIActivity extends BaseActivity {
public static final String[] UI_SECTIONS = new String[]{
"常用控件", "布局-百分比布局", "ListView", "RecyclerView", "聊天界面"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chapter_ui);
ListView lv = (ListView) findViewById(R.id.uiChapterList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, UI_SECTIONS);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
startActivity(new Intent(UIActivity.this, BaseUIActivity.class));
break;
case 1:
startActivity(new Intent(UIActivity.this, PercentLayoutActivity.class));
break;
case 2:
startActivity(new Intent(UIActivity.this, ListViewActivity.class));
break;
case 3:
setRecyclerViewStyle();
break;
case 4:
startActivity(new Intent(UIActivity.this, ChatActivity.class));
break;
default:
break;
}
}
});
}
private void setRecyclerViewStyle() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setItems(new String[]{"纵向", "横向", "表格", "瀑布流"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(UIActivity.this, RecyclerViewActivity.class);
intent.putExtra("style", i);
startActivity(intent);
}
});
builder.create().show();
}
}
|
uzmakinaruto/FirstLineCode
|
app/src/main/java/com/jan/flc/firstlinecode/activity/UIActivity.java
|
Java
|
apache-2.0
| 2,700 |
#!/usr/bin/ruby
#
# Author:: api.sgomes@gmail.com (Sérgio Gomes)
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates how to create a negative campaign criterion for a
# given campaign. To create a campaign, run add_campaign.rb.
#
# Tags: CampaignCriterionService.mutate
require 'rubygems'
gem 'google-adwords-api'
require 'adwords_api'
API_VERSION = :v201003
def add_negative_campaign_criterion()
# AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
# when called without parameters.
adwords = AdwordsApi::Api.new
campaign_criterion_srv =
adwords.service(:CampaignCriterionService, API_VERSION)
campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i
# Prepare for adding criterion.
operation = {
:operator => 'ADD',
:operand => {
# The 'xsi_type' field allows you to specify the xsi:type of the object
# being created. It's only necessary when you must provide an explicit
# type that the client library can't infer.
:xsi_type => 'NegativeCampaignCriterion',
:campaign_id => campaign_id,
:criterion => {
:xsi_type => 'Keyword',
:text => 'jupiter cruise',
:match_type => 'BROAD'
}
}
}
# Add criterion.
response = campaign_criterion_srv.mutate([operation])
campaign_criterion = response[:value].first
puts 'Campaign criterion id %d was successfully added.' %
campaign_criterion[:criterion][:id]
end
if __FILE__ == $0
# To enable logging of SOAP requests, set the ADWORDSAPI_DEBUG environment
# variable to 'true'. This can be done either from your operating system
# environment or via code, as done below.
ENV['ADWORDSAPI_DEBUG'] = 'false'
begin
add_negative_campaign_criterion()
# Connection error. Likely transitory.
rescue Errno::ECONNRESET, SOAP::HTTPStreamError, SocketError => e
puts 'Connection Error: %s' % e
puts 'Source: %s' % e.backtrace.first
# API Error.
rescue AdwordsApi::Errors::ApiException => e
puts 'API Exception caught.'
puts 'Message: %s' % e.message
puts 'Code: %d' % e.code if e.code
puts 'Trigger: %s' % e.trigger if e.trigger
puts 'Errors:'
if e.errors
e.errors.each_with_index do |error, index|
puts ' %d. Error type is %s. Fields:' % [index + 1, error[:xsi_type]]
error.each_pair do |field, value|
if field != :xsi_type
puts ' %s: %s' % [field, value]
end
end
end
end
end
end
|
sylow/google-adwords-api
|
examples/v201003/add_negative_campaign_criterion.rb
|
Ruby
|
apache-2.0
| 3,158 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Serialization;
using System.Configuration;
using System.IO;
namespace GetServiceInfo
{
class GetOutletServiceInfo
{
static void Main(string[] args)
{
// Your username, password and customer number are imported from the following file
// CPCWS_ServiceInfo_DotNet_Samples\REST\serviceinfo\user.xml
var username = ConfigurationSettings.AppSettings["username"];
var password = ConfigurationSettings.AppSettings["password"];
// REST URI
String url = "https://ct.soa-gw.canadapost.ca/rs/serviceinfo/outlet";
var method = "GET"; // HTTP Method
String responseAsString = ".NET Framework " + Environment.Version.ToString() + "\r\n\r\n";
try
{
// Create REST Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
// Set Basic Authentication Header using username and password variables
string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
request.Headers = new WebHeaderCollection();
request.Headers.Add("Authorization", auth);
request.Headers.Add("Accept-Language", "en-CA");
request.Accept = "application/vnd.cpc.serviceinfo-v2+xml";
// Execute REST Request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseAsString += "HTTP Response Status: " + (int)response.StatusCode + "\r\n\r\n";
// Deserialize xml response to customer object
XmlSerializer serializer = new XmlSerializer(typeof(InfoMessagesType));
TextReader reader = new StreamReader(response.GetResponseStream());
InfoMessagesType infoMessages = (InfoMessagesType)serializer.Deserialize(reader);
if (infoMessages.infomessage != null)
{
foreach (InfoMessageType infoMessage in infoMessages.infomessage)
{
responseAsString += " Message Type is :" + infoMessage.messagetype + "\r\n";
responseAsString += " Message Text is :" + infoMessage.messagetext + "\r\n";
responseAsString += " Message Start Time is :" + infoMessage.fromdatetime + "\r\n";
responseAsString += " Message End Time is :" + infoMessage.todatetime + "\r\n";
}
}
}
catch (WebException webEx)
{
HttpWebResponse response = (HttpWebResponse)webEx.Response;
if (response != null)
{
responseAsString += "HTTP Response Status: " + webEx.Message + "\r\n";
// Retrieve errors from messages object
try
{
// Deserialize xml response to messages object
XmlSerializer serializer = new XmlSerializer(typeof(messages));
TextReader reader = new StreamReader(response.GetResponseStream());
messages myMessages = (messages)serializer.Deserialize(reader);
if (myMessages.message != null)
{
foreach (var item in myMessages.message)
{
responseAsString += "Error Code: " + item.code + "\r\n";
responseAsString += "Error Msg: " + item.description + "\r\n";
}
}
}
catch (Exception ex)
{
// Misc Exception
responseAsString += "ERROR: " + ex.Message;
}
}
else
{
// Invalid Request
responseAsString += "ERROR: " + webEx.Message;
}
}
catch (Exception ex)
{
// Misc Exception
responseAsString += "ERROR: " + ex.Message;
}
Console.WriteLine(responseAsString);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
|
Kiandr/MS
|
Languages/CSharp/CPCWS_DotNet_Samples/REST/serviceinfo/GetOutletServiceInfo/GetOutletServiceInfo.cs
|
C#
|
apache-2.0
| 4,631 |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.ui;
import com.google.android.apps.iosched.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this
* activity is forwarded to the fragment as arguments during fragment instantiation. Derived
* activities should only need to implement
* {@link com.google.android.apps.iosched.ui.BaseSinglePaneActivity#onCreatePane()}.
*/
public abstract class BaseSinglePaneActivity extends BaseActivity {
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlepane_empty);
final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
//getActivityHelper().setActionBarTitle(customTitle != null ? customTitle : getTitle());
if (savedInstanceState == null) {
mFragment = onCreatePane();
mFragment.setArguments(intentToFragmentArguments(getIntent()));
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container, mFragment)
.commit();
}
}
/**
* Called in <code>onCreate</code> when the fragment constituting this activity is needed.
* The returned fragment's arguments will be set to the intent used to invoke this activity.
*/
protected abstract Fragment onCreatePane();
}
|
skyisle/iosched2011
|
android/src/com/google/android/apps/iosched/ui/BaseSinglePaneActivity.java
|
Java
|
apache-2.0
| 2,149 |
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spring.data.datastore.core.mapping.event;
import org.springframework.context.ApplicationEvent;
/** An event published when entities are read from Cloud Datastore. */
public class ReadEvent extends ApplicationEvent {
/**
* Constructor.
*
* @param results A list of results from the read operation where each item was mapped from a
* Cloud Datastore entity.
*/
public ReadEvent(Iterable results) {
super(results);
}
/**
* Get the list of results from the read operation.
*
* @return the list of results from the read operation.
*/
public Iterable getResults() {
return (Iterable) getSource();
}
}
|
GoogleCloudPlatform/spring-cloud-gcp
|
spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/mapping/event/ReadEvent.java
|
Java
|
apache-2.0
| 1,298 |
import logging
from types import FunctionType
import ray
import ray.cloudpickle as pickle
from ray.experimental.internal_kv import _internal_kv_initialized, \
_internal_kv_get, _internal_kv_put
from ray.tune.error import TuneError
TRAINABLE_CLASS = "trainable_class"
ENV_CREATOR = "env_creator"
RLLIB_MODEL = "rllib_model"
RLLIB_PREPROCESSOR = "rllib_preprocessor"
RLLIB_ACTION_DIST = "rllib_action_dist"
TEST = "__test__"
KNOWN_CATEGORIES = [
TRAINABLE_CLASS, ENV_CREATOR, RLLIB_MODEL, RLLIB_PREPROCESSOR,
RLLIB_ACTION_DIST, TEST
]
logger = logging.getLogger(__name__)
def has_trainable(trainable_name):
return _global_registry.contains(TRAINABLE_CLASS, trainable_name)
def get_trainable_cls(trainable_name):
validate_trainable(trainable_name)
return _global_registry.get(TRAINABLE_CLASS, trainable_name)
def validate_trainable(trainable_name):
if not has_trainable(trainable_name):
# Make sure everything rllib-related is registered.
from ray.rllib import _register_all
_register_all()
if not has_trainable(trainable_name):
raise TuneError("Unknown trainable: " + trainable_name)
def register_trainable(name, trainable, warn=True):
"""Register a trainable function or class.
This enables a class or function to be accessed on every Ray process
in the cluster.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration.
"""
from ray.tune.trainable import Trainable
from ray.tune.function_runner import wrap_function
if isinstance(trainable, type):
logger.debug("Detected class for trainable.")
elif isinstance(trainable, FunctionType):
logger.debug("Detected function for trainable.")
trainable = wrap_function(trainable, warn=warn)
elif callable(trainable):
logger.info(
"Detected unknown callable for trainable. Converting to class.")
trainable = wrap_function(trainable, warn=warn)
if not issubclass(trainable, Trainable):
raise TypeError("Second argument must be convertable to Trainable",
trainable)
_global_registry.register(TRAINABLE_CLASS, name, trainable)
def register_env(name, env_creator):
"""Register a custom environment for use with RLlib.
This enables the environment to be accessed on every Ray process
in the cluster.
Args:
name (str): Name to register.
env_creator (obj): Function that creates an env.
"""
if not isinstance(env_creator, FunctionType):
raise TypeError("Second argument must be a function.", env_creator)
_global_registry.register(ENV_CREATOR, name, env_creator)
def check_serializability(key, value):
_global_registry.register(TEST, key, value)
def _make_key(category, key):
"""Generate a binary key for the given category and key.
Args:
category (str): The category of the item
key (str): The unique identifier for the item
Returns:
The key to use for storing a the value.
"""
return (b"TuneRegistry:" + category.encode("ascii") + b"/" +
key.encode("ascii"))
class _Registry:
def __init__(self):
self._to_flush = {}
def register(self, category, key, value):
"""Registers the value with the global registry.
Raises:
PicklingError if unable to pickle to provided file.
"""
if category not in KNOWN_CATEGORIES:
from ray.tune import TuneError
raise TuneError("Unknown category {} not among {}".format(
category, KNOWN_CATEGORIES))
self._to_flush[(category, key)] = pickle.dumps_debug(value)
if _internal_kv_initialized():
self.flush_values()
def contains(self, category, key):
if _internal_kv_initialized():
value = _internal_kv_get(_make_key(category, key))
return value is not None
else:
return (category, key) in self._to_flush
def get(self, category, key):
if _internal_kv_initialized():
value = _internal_kv_get(_make_key(category, key))
if value is None:
raise ValueError(
"Registry value for {}/{} doesn't exist.".format(
category, key))
return pickle.loads(value)
else:
return pickle.loads(self._to_flush[(category, key)])
def flush_values(self):
for (category, key), value in self._to_flush.items():
_internal_kv_put(_make_key(category, key), value, overwrite=True)
self._to_flush.clear()
_global_registry = _Registry()
ray.worker._post_init_hooks.append(_global_registry.flush_values)
class _ParameterRegistry:
def __init__(self):
self.to_flush = {}
self.references = {}
def put(self, k, v):
self.to_flush[k] = v
if ray.is_initialized():
self.flush()
def get(self, k):
if not ray.is_initialized():
return self.to_flush[k]
return ray.get(self.references[k])
def flush(self):
for k, v in self.to_flush.items():
self.references[k] = ray.put(v)
self.to_flush.clear()
parameter_registry = _ParameterRegistry()
ray.worker._post_init_hooks.append(parameter_registry.flush)
|
richardliaw/ray
|
python/ray/tune/registry.py
|
Python
|
apache-2.0
| 5,525 |
# Copyright (c) 2018-2021 Micro Focus or one of its affiliates.
# Copyright (c) 2018 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright (c) 2013-2017 Uber Technologies, Inc.
#
# 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.
from __future__ import print_function, division, absolute_import
from six import text_type, binary_type
from ..message import BulkFrontendMessage
class CopyData(BulkFrontendMessage):
message_id = b'd'
def __init__(self, data, unicode_error='strict'):
BulkFrontendMessage.__init__(self)
if isinstance(data, text_type):
self.bytes_ = data.encode(encoding='utf-8', errors=unicode_error)
elif isinstance(data, binary_type):
self.bytes_ = data
else:
raise TypeError("Data should be string or bytes")
def read_bytes(self):
return self.bytes_
|
uber/vertica-python
|
vertica_python/vertica/messages/frontend_messages/copy_data.py
|
Python
|
apache-2.0
| 2,393 |
"use strict";
require('../core/setup');
var $ = require('jquery'),
L = require('leaflet'),
assert = require('chai').assert,
sinon = require('sinon'),
Marionette = require('../../shim/backbone.marionette'),
App = require('../app'),
models = require('./models'),
utils = require('./utils'),
views = require('./views'),
settings = require('../core/settings'),
testUtils = require('../core/testUtils');
var sandboxId = 'sandbox',
sandboxSelector = '#' + sandboxId,
TEST_SHAPE = {
'type': 'MultiPolygon',
'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
};
var SandboxRegion = Marionette.Region.extend({
el: sandboxSelector
});
describe('Draw', function() {
before(function() {
// Ensure that draw tools are enabled before testing
settings.set('draw_tools', [
'SelectArea', // Boundary Selector
'Draw', // Custom Area or 1 Sq Km stamp
'PlaceMarker', // Delineate Watershed
'ResetDraw',
]);
});
beforeEach(function() {
$('body').append('<div id="sandbox">');
});
afterEach(function() {
$(sandboxSelector).remove();
window.location.hash = '';
testUtils.resetApp(App);
});
describe('ToolbarView', function() {
// Setup the toolbar controls, enable/disable them, and verify
// the correct CSS classes are applied.
it('enables/disables toolbar controls when the model enableTools/disableTools methods are called', function() {
var sandbox = new SandboxRegion(),
$el = sandbox.$el,
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
});
sandbox.show(view);
populateSelectAreaDropdown($el, model);
// Nothing should be disabled at this point.
// Test that toggling the `toolsEnabled` property on the model
// will disable all drawing tools.
assert.equal($el.find('.disabled').size(), 0);
model.disableTools();
assert.equal($el.find('.disabled').size(), 3);
model.enableTools();
assert.equal($el.find('.disabled').size(), 0);
});
it('adds an AOI to the map after calling getShapeAndAnalyze', function(done) {
var successCount = 2,
deferred = setupGetShapeAndAnalyze(successCount),
success;
deferred.
done(function() {
assert.equal(App.map.get('areaOfInterest'), TEST_SHAPE);
success = true;
}).
fail(function() {
success = false;
}).
always(function() {
assert.equal(success, true);
done();
});
});
it('fails to add AOI when shape id cannot be retrieved by getShapeAndAnalyze', function(done) {
// Set successCount high enough so that the polling will fail.
var successCount = 6,
deferred = setupGetShapeAndAnalyze(successCount),
success;
deferred.
done(function() {
success = true;
}).
fail(function() {
success = false;
}).
always(function() {
assert.equal(success, false);
done();
});
});
it('resets the current area of interest on Reset', function() {
var setup = setupResetTestObject();
App.map.set('areaOfInterest', TEST_SHAPE);
setup.resetRegion.currentView.resetDrawingState();
assert.isNull(App.map.get('areaOfInterest',
'Area of Interest was not removed on reset from the map'));
});
it('resets the boundary layer on Reset', function() {
var setup = setupResetTestObject(),
ofg = L.featureGroup(),
testFeature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
};
ofg.addLayer(L.geoJson(testFeature));
assert.equal(ofg.getLayers().length, 1);
setup.model.set('outlineFeatureGroup', ofg);
setup.resetRegion.currentView.resetDrawingState();
assert.equal(ofg.getLayers().length, 0,
'Boundary Layer should have been removed from layer group');
});
it('removes in progress drawing on Reset', function() {
var setup = setupResetTestObject(),
spy = sinon.spy(utils, 'cancelDrawing');
utils.drawPolygon(setup.map);
setup.resetRegion.currentView.resetDrawingState();
assert.equal(spy.callCount, 1);
});
});
});
function setupGetShapeAndAnalyze(successCount) {
var sandbox = new SandboxRegion(),
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
}),
shapeId = 1,
e = {latlng: L.latLng(50.5, 30.5)},
ofg = model.get('outlineFeatureGroup'),
grid = {
callCount: 0,
_objectForEvent: function() { //mock grid returns shapeId on second call
this.callCount++;
if (this.callCount >= successCount) {
return {data: {id: shapeId}};
} else {
return {};
}
}
},
tableId = 2;
sandbox.show(view);
App.restApi = {
getPolygon: function() {
return $.Deferred().resolve(TEST_SHAPE).promise();
}
};
return views.getShapeAndAnalyze(e, model, ofg, grid, tableId);
}
function setupResetTestObject() {
var sandbox = new SandboxRegion(),
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
}),
resetRegion = view.getRegion('resetRegion'),
map = App.getLeafletMap();
sandbox.show(view);
return {
sandbox: sandbox,
model: model,
view: view,
resetRegion: resetRegion,
map: map
};
}
function assertTextEqual($el, sel, text) {
assert.equal($el.find(sel).text().trim(), text);
}
function populateSelectAreaDropdown($el, toolbarModel) {
// This control should start off in a Loading state.
assertTextEqual($el, '#select-area-region button', 'Loading...');
// Load some shapes...
toolbarModel.set('predefinedShapeTypes', [
{
"endpoint": "http://localhost:4000/0/{z}/{x}/{y}",
"display": "Congressional Districts",
"name": "tiles"
}]);
// This dropdown should now be populated.
assertTextEqual($el, '#select-area-region button', 'Select by Boundary');
assertTextEqual($el, '#select-area-region li', 'Congressional Districts');
}
|
lliss/model-my-watershed
|
src/mmw/js/src/draw/tests.js
|
JavaScript
|
apache-2.0
| 7,248 |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.am.service.validators;
import io.gravitee.am.service.exception.InvalidPathException;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
* @author GraviteeSource Team
*/
public class PathValidatorTest {
@Test
public void validate() {
Throwable throwable = PathValidator.validate("/test").blockingGet();
assertNull(throwable);
}
@Test
public void validateSpecialCharacters() {
Throwable throwable = PathValidator.validate("/test/subpath/subpath2_with-and.dot/AND_UPPERCASE").blockingGet();
assertNull(throwable);
}
@Test
public void validate_invalidEmptyPath() {
Throwable throwable = PathValidator.validate("").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_nullPath() {
Throwable throwable = PathValidator.validate(null).blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_multipleSlashesPath() {
Throwable throwable = PathValidator.validate("/////test////").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_invalidCharacters() {
Throwable throwable = PathValidator.validate("/test$:\\;,+").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
}
|
gravitee-io/graviteeio-access-management
|
gravitee-am-service/src/test/java/io/gravitee/am/service/validators/PathValidatorTest.java
|
Java
|
apache-2.0
| 2,272 |
<?php
/**
* 支付配置
* @author hfc
* @date 2015-8-31
*/
namespace apps\admin\controllers;
use apps\admin\models\Payment;
use apps\admin\models\PaymentPlugin;
use enums\SystemEnums;
use Phalcon\Db\Profiler;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
class PayconfigController extends AdminBaseController
{
public function initialize()
{
parent::initialize();
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '使用支付' )
* @method( method = 'indexAction' )
* @op( op = 'r' )
*/
public function indexAction()
{
$pageNum = $this->request->getQuery( 'page', 'int' );
$currentPage = $pageNum ? $pageNum : 1;
$payModel = new Payment();
$pay = $payModel->getPayment( $this->shopId );
$pagination = new PaginatorModel( array( 'data' => $pay,
'limit' => 10,
'page' => $currentPage
));
$page = $pagination->getPaginate();
$this->view->page = $page;
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '全部支付' )
* @method( method = 'indexAction' )
* @op( op = 'r' )
*/
public function allAction()
{
$pageNum = $this->request->getQuery( 'page', 'int' );
$currentPage = $pageNum ? $pageNum : 1;
$pay = PaymentPlugin::find( 'delsign=' . SystemEnums::DELSIGN_NO );
$pagination = new PaginatorModel( array( 'data' => $pay,
'limit' => 10,
'page' => $currentPage
));
$page = $pagination->getPaginate();
$this->view->page = $page;
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '删除已使用的支付' )
* @method( method = 'deleteAction' )
* @op( op = 'd' )
*/
public function deleteAction()
{
$id = $this->request->getPost( 'id', 'int' );
$profile = new Profiler();
$payment = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $payment )
{
$status = $payment->update( array( 'delsign' => SystemEnums::DELSIGN_YES ) );
if( $status )
{
$this->success( '删除成功' );
}
else
{
$this->error( '删除失败' );
}
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的添加显示' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function addAction()
{
$id = $this->request->getQuery( 'id', 'int' );
if( $id )
{
$plugin = PaymentPlugin::findFirst( array( 'id=?0', 'bind' => array( $id ), 'columns' => 'id,name'));
if( $plugin )
{
$this->view->plugin = $plugin->toArray();
}
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的编辑' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function editAction()
{
$id = $this->request->getQuery( 'id', 'int' );
$pay = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $pay )
{
$this->view->pay = $pay->toArray();
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的编辑' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function readAction()
{
$this->editAction();
$this->view->isRead = true;
$this->view->pick( 'payconfig/edit' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的更新' )
* @method( method = 'updateAction' )
* @op( op = 'u' )
*/
public function updateAction()
{
$this->csrfCheck();
$id = $this->request->getPost( 'id', 'int' );
$data[ 'pay_name' ] = $this->request->getPost( 'pay_name', 'string' );
$data[ 'partner_id' ] = $this->request->getPost( 'partner_id', 'string' );
$data[ 'partner_key' ] = $this->request->getPost( 'partner_key', 'string' );
$data[ 'status' ] = $this->request->getPost( 'status', 'int' );
$data[ 'sort' ] = $this->request->getPost( 'sort', 'int' );
$this->validation( $data );
$pay = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $pay )
{
$status = $pay->update( $data );
if( $status )
{
$this->success( '更新成功' );
}
}
$this->error( '更新失败' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的添加' )
* @method( method = 'insertAction' )
* @op( op = 'c' )
*/
public function insertAction()
{
$this->csrfCheck();
$data[ 'pay_name' ] = $this->request->getPost( 'pay_name', 'string' );
$data[ 'plugin_id' ] = $this->request->getPost( 'plugin_id', 'string' );
$data[ 'partner_id' ] = $this->request->getPost( 'partner_id', 'string' );
$data[ 'partner_key' ] = $this->request->getPost( 'partner_key', 'string' );
$data[ 'status' ] = $this->request->getPost( 'status', 'int' );
$data[ 'sort' ] = $this->request->getPost( 'sort', 'int' );
$this->validation( $data );
$data[ 'delsign' ] = $data[ 'status' ] = 0;
$data[ 'shop_id' ] = $this->shopId;
$pay = new Payment();
if( $pay )
{
$status = $pay->save( $data );
if( $status )
{
$this->success( '添加成功' );
}
}
$this->error( '添加失败' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '验证数据' )
* @method( method = 'validation' )
* @op( op = 'u' )
*/
private function validation( $data )
{
$validation = new Validation();
$validation->add( 'partner_id', new PresenceOf( array(
'message' => '合作者身份必学填写'
) ) );
$validation->add( 'partner_key', new PresenceOf( array(
'message' => '安全校验码必学填写'
) ) );
$msgs = $validation->validate( $data );
if( count( $msgs ))
{
foreach( $msgs as $m )
{
$this->error( $m->getMessage() );
}
}
}
}
|
sxyunfeng/fcms
|
apps/admin/controllers/PayconfigController.php
|
PHP
|
apache-2.0
| 7,003 |
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.execution.ddl;
import io.crate.metadata.RelationName;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import java.io.IOException;
public final class RelationNameSwap implements Writeable {
private final RelationName source;
private final RelationName target;
public RelationNameSwap(RelationName source, RelationName target) {
this.source = source;
this.target = target;
}
public RelationNameSwap(StreamInput in) throws IOException {
this.source = new RelationName(in);
this.target = new RelationName(in);
}
public RelationName source() {
return source;
}
public RelationName target() {
return target;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
source.writeTo(out);
target.writeTo(out);
}
}
|
EvilMcJerkface/crate
|
server/src/main/java/io/crate/execution/ddl/RelationNameSwap.java
|
Java
|
apache-2.0
| 1,976 |
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import axios, { AxiosBasicCredentials, AxiosError, AxiosInstance } from 'axios';
import addOAuthInterceptor from 'axios-oauth-1.0a';
import { Request, Response } from 'express';
import firebase from 'firebase/app';
import * as fs from 'fs';
import {
BlockTwitterUsersRequest,
BlockTwitterUsersResponse,
GetTweetsRequest,
GetTweetsResponse,
HideRepliesTwitterRequest,
HideRepliesTwitterResponse,
MuteTwitterUsersRequest,
MuteTwitterUsersResponse,
Tweet,
TweetObject,
TwitterApiResponse,
} from '../../common-types';
import { TwitterApiCredentials } from '../serving';
// Max results per twitter call.
const BATCH_SIZE = 500;
interface TwitterApiRequest {
query: string;
maxResults?: number;
fromDate?: string;
toDate?: string;
next?: string;
}
export async function getTweets(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
let twitterDataPromise: Promise<TwitterApiResponse>;
if (fs.existsSync('src/server/twitter_sample_results.json')) {
twitterDataPromise = loadLocalTwitterData();
} else {
if (!enterpriseSearchCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Enterprise Search API credentials'));
return;
}
twitterDataPromise = loadTwitterData(apiCredentials, req.body);
}
try {
const twitterData = await twitterDataPromise;
const tweets = twitterData.results.map(parseTweet);
res.send({ tweets, nextPageToken: twitterData.next } as GetTweetsResponse);
} catch (e) {
console.error('Error loading Twitter data: ' + e);
res.status(500).send('Error loading Twitter data');
}
}
export async function blockTwitterUsers(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as BlockTwitterUsersRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await blockUsers(apiCredentials, userCredential, request);
if (response.error) {
// All block API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
export async function muteTwitterUsers(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as MuteTwitterUsersRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await muteUsers(apiCredentials, userCredential, request);
if (response.error) {
// All mute API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
export async function hideTwitterReplies(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as HideRepliesTwitterRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await hideReplies(apiCredentials, userCredential, request);
if (response.error) {
// All hide reply API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
async function blockUsers(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: BlockTwitterUsersRequest
): Promise<BlockTwitterUsersResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const requestUrl = 'https://api.twitter.com/1.1/blocks/create.json';
const response: BlockTwitterUsersResponse = {};
const requests = request.users.map(user =>
client
.post<BlockTwitterUsersResponse>(
requestUrl,
{},
{ params: { screen_name: user } }
)
.catch(e => {
console.error(`Unable to block Twitter user: @${user} because ${e}`);
response.failedScreennames = [
...(response.failedScreennames ?? []),
user,
];
})
);
await Promise.all(requests);
if (request.users.length === response.failedScreennames?.length) {
response.error = 'Unable to block Twitter users';
}
return response;
}
async function muteUsers(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: MuteTwitterUsersRequest
): Promise<MuteTwitterUsersResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const requestUrl = 'https://api.twitter.com/1.1/mutes/users/create.json';
const response: MuteTwitterUsersResponse = {};
const requests = request.users.map(user =>
client
.post<MuteTwitterUsersResponse>(
requestUrl,
{},
{ params: { screen_name: user } }
)
.catch(e => {
console.error(`Unable to mute Twitter user: @${user} because ${e}`);
response.failedScreennames = [
...(response.failedScreennames ?? []),
user,
];
})
);
await Promise.all(requests);
if (request.users.length === response.failedScreennames?.length) {
response.error = 'Unable to mute Twitter users';
}
return response;
}
async function hideReplies(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: HideRepliesTwitterRequest
): Promise<HideRepliesTwitterResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const response: HideRepliesTwitterResponse = {};
let quotaExhaustedErrors = 0;
let otherErrors = 0;
const requests = request.tweetIds.map(id =>
client
.put<HideRepliesTwitterResponse>(
`https://api.twitter.com/2/tweets/${id}/hidden`,
{ hidden: true }
)
.catch((e: AxiosError) => {
console.error(`Unable to hide tweet ID: ${id} because ${e}`);
if (
e.response?.status === 429 ||
e.response?.statusText.includes('Too Many Requests')
) {
quotaExhaustedErrors += 1;
} else {
otherErrors += 1;
}
})
);
await Promise.all(requests);
response.numQuotaFailures = quotaExhaustedErrors;
response.numOtherFailures = otherErrors;
if (otherErrors === request.tweetIds.length) {
response.error = 'Unable to hide replies';
}
return response;
}
function loadTwitterData(
credentials: TwitterApiCredentials,
request: GetTweetsRequest
): Promise<TwitterApiResponse> {
const requestUrl = `https://gnip-api.twitter.com/search/fullarchive/accounts/${credentials.accountName}/prod.json`;
// These are the *user's* credentials for Twitter.
const user = request.credentials?.additionalUserInfo?.username;
if (!user) {
throw new Error('No user credentials in GetTweetsRequest');
}
const twitterApiRequest: TwitterApiRequest = {
query: `(@${user} OR url:twitter.com/${user}) -from:${user} -is:retweet`,
maxResults: BATCH_SIZE,
};
if (request.fromDate) {
twitterApiRequest.fromDate = request.fromDate;
}
if (request.toDate) {
twitterApiRequest.toDate = request.toDate;
}
if (request.nextPageToken) {
twitterApiRequest.next = request.nextPageToken;
}
const auth: AxiosBasicCredentials = {
username: credentials!.username,
password: credentials!.password,
};
return axios
.post<TwitterApiResponse>(requestUrl, twitterApiRequest, { auth })
.then(response => response.data)
.catch(error => {
const errorStr =
`Error while fetching tweets with request ` +
`${JSON.stringify(request)}: ${error}`;
throw new Error(errorStr);
});
}
function loadLocalTwitterData(): Promise<TwitterApiResponse> {
return fs.promises
.readFile('src/server/twitter_sample_results.json')
.then((data: Buffer) => {
// Remove the `next` page token so the client doesn't infinitely issue
// requests for a next page of data.
const response = JSON.parse(data.toString()) as TwitterApiResponse;
response.next = '';
return response;
});
}
function enterpriseSearchCredentialsAreValid(
credentials: TwitterApiCredentials
): boolean {
return (
!!credentials.accountName &&
!!credentials.username &&
!!credentials.password
);
}
function standardApiCredentialsAreValid(
credentials: TwitterApiCredentials
): boolean {
return !!credentials.appKey && !!credentials.appToken;
}
function createAxiosInstance(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential
): AxiosInstance {
const token = userCredential.accessToken;
const tokenSecret = userCredential.secret;
if (!token || !tokenSecret) {
throw new Error('Twitter user access token and secret are missing');
}
const client = axios.create();
// Add OAuth 1.0a credentials.
addOAuthInterceptor(client, {
algorithm: 'HMAC-SHA1',
key: apiCredentials.appKey,
includeBodyHash: false,
secret: apiCredentials.appToken,
token,
tokenSecret,
});
return client;
}
function parseTweet(tweetObject: TweetObject): Tweet {
// Still pass the rest of the metadata in case we want to use it
// later, but surface the comment in a top-level field.
//
// Firestore doesn't support writing nested arrays, so we have to
// manually build the Tweet object to avoid accidentally including the nested
// arrays in the TweetObject from the Twitter API response.
const tweet: Tweet = {
created_at: tweetObject.created_at,
date: new Date(),
display_text_range: tweetObject.display_text_range,
entities: tweetObject.entities,
extended_entities: tweetObject.extended_entities,
extended_tweet: tweetObject.extended_tweet,
favorite_count: tweetObject.favorite_count,
favorited: tweetObject.favorited,
in_reply_to_status_id: tweetObject.in_reply_to_status_id,
id_str: tweetObject.id_str,
lang: tweetObject.lang,
reply_count: tweetObject.reply_count,
retweet_count: tweetObject.retweet_count,
retweeted_status: tweetObject.retweeted_status,
source: tweetObject.source,
text: tweetObject.text,
truncated: tweetObject.truncated,
url: `https://twitter.com/i/web/status/${tweetObject.id_str}`,
user: tweetObject.user,
};
if (tweetObject.truncated && tweetObject.extended_tweet) {
tweet.text = tweetObject.extended_tweet.full_text;
}
if (tweetObject.created_at) {
tweet.date = new Date(tweetObject.created_at);
}
if (tweetObject.user) {
tweet.authorName = tweetObject.user.name;
tweet.authorScreenName = tweetObject.user.screen_name;
tweet.authorUrl = `https://twitter.com/${tweetObject.user.screen_name}`;
tweet.authorAvatarUrl = tweetObject.user.profile_image_url;
tweet.verified = tweetObject.user.verified;
}
if (tweetObject.extended_entities && tweetObject.extended_entities.media) {
tweet.hasImage = true;
}
return tweet;
}
|
conversationai/harassment-manager
|
src/server/middleware/twitter.middleware.ts
|
TypeScript
|
apache-2.0
| 11,910 |
/**
* 添加教师js,主要处理积点的问题。
* 分模块化
* Created by admin on 2016/9/26.
*/
$(function(){
//第一个问题
var work_load = $('#is_work_load').val();
$("#work_load input[type='checkbox']").live('click', function(e){
var is_work_load = $(this).val();
if($(this).is(':checked') && is_work_load == 1){
$("#is_work_load").val(1);
$('#work_load').find(".no").attr('checked', false);
$('#work_load').find(".yes").attr('checked', true);
}else{
$("#is_work_load").val(0);
$('#work_load').find(".no").attr('checked', true);
$('#work_load').find(".yes").attr('checked', false);
}
});
//第二个问题
var teaching_good = $('#is_teaching_good').val();
$("#teaching_good input[type='checkbox']").live('click', function(e){
var is_teaching_good = $(this).val();
if($(this).is(':checked') && is_teaching_good == 1){
$("#is_teaching_good").val(1);
$('#teaching_good').find(".no").attr('checked', false);
$('#teaching_good').find(".yes").attr('checked', true);
}else{
$("#is_teaching_good").val(0);
$('#teaching_good').find(".no").attr('checked', true);
$('#teaching_good').find(".yes").attr('checked', false);
}
});
//第三个问题
var teaching_behavior = $('#is_teaching_behavior').val();
$("#teaching_behavior input[type='checkbox']").live('click', function(e){
var is_teaching_behavior = $(this).val();
if($(this).is(':checked') && is_teaching_behavior == 1){
$("#is_teaching_behavior").val(1);
$('#teaching_behavior').find(".no").attr('checked', false);
$('#teaching_behavior').find(".yes").attr('checked', true);
}else{
$("#is_teaching_behavior").val(0);
$('#teaching_behavior').find(".no").attr('checked', true);
$('#teaching_behavior').find(".yes").attr('checked', false);
}
});
//第四个问题
var student_statis = $('#is_student_statis').val();
$("#student_statis input[type='checkbox']").live('click', function(e){
var is_student_statis = $(this).val();
if($(this).is(':checked') && is_student_statis == 1){
$("#is_student_statis").val(1);
$('#student_statis').find(".no").attr('checked', false);
$('#student_statis').find(".yes").attr('checked', true);
}else{
$("#is_student_statis").val(0);
$('#student_statis').find(".no").attr('checked', true);
$('#student_statis').find(".yes").attr('checked', false);
}
});
//第五个问题
var subject_good = $('#is_subject_good').val();
$("#subject_good input[type='checkbox']").live('click', function(e){
var is_subject_good = $(this).val();
if($(this).is(':checked') && is_subject_good == 1){
$("#is_subject_good").val(1);
$('#subject_good').find(".no").attr('checked', false);
$('#subject_good').find(".yes").attr('checked', true);
}else{
$("#is_subject_good").val(0);
$('#subject_good').find(".no").attr('checked', true);
$('#subject_good').find(".yes").attr('checked', false);
}
});
//第六个问题
var academic = $('#is_academic').val();
$("#academic input[type='checkbox']").live('click', function(e){
var is_academic = $(this).val();
if($(this).is(':checked') && is_academic == 1){
$("#is_academic").val(1);
$('#academic').find(".no").attr('checked', false);
$('#academic').find(".yes").attr('checked', true);
}else{
$("#is_academic").val(0);
$('#academic').find(".no").attr('checked', true);
$('#academic').find(".yes").attr('checked', false);
}
});
//第七个问题
var organ_sub = $('#is_organ_sub').val();
$("#organ_sub input[type='checkbox']").live('click', function(e){
var is_organ_sub = $(this).val();
if($(this).is(':checked') && is_organ_sub == 1){
$("#is_organ_sub").val(1);
$('#organ_sub').find(".no").attr('checked', false);
$('#organ_sub').find(".yes").attr('checked', true);
}else{
$("#is_organ_sub").val(0);
$('#organ_sub').find(".no").attr('checked', true);
$('#organ_sub').find(".yes").attr('checked', false);
}
});
//第八个问题
var school_forum = $('#is_school_forum').val();
$("#school_forum input[type='checkbox']").live('click', function(e){
var is_school_forum = $(this).val();
if($(this).is(':checked') && is_school_forum == 1){
$("#is_school_forum").val(1);
$('#school_forum').find(".no").attr('checked', false);
$('#school_forum').find(".yes").attr('checked', true);
}else{
$("#is_school_forum").val(0);
$('#school_forum').find(".no").attr('checked', true);
$('#school_forum').find(".yes").attr('checked', false);
}
});
//第九个问题
var backtone_teacher = $('#is_backtone_teacher').val();
$("#backtone_teacher input[type='checkbox']").live('click', function(e){
var is_backtone_teacher = $(this).val();
if($(this).is(':checked') && is_backtone_teacher == 1){
$("#is_backtone_teacher").val(1);
$('#backtone_teacher').find(".no").attr('checked', false);
$('#backtone_teacher').find(".yes").attr('checked', true);
}else{
$("#is_backtone_teacher").val(0);
$('#backtone_teacher').find(".no").attr('checked', true);
$('#backtone_teacher').find(".yes").attr('checked', false);
}
});
//第10个问题
var teach_intern = $('#is_teach_intern').val();
$("#teach_intern input[type='checkbox']").live('click', function(e){
var is_teach_intern = $(this).val();
if($(this).is(':checked') && is_teach_intern == 1){
$("#is_teach_intern").val(1);
$('#teach_intern').find(".no").attr('checked', false);
$('#teach_intern').find(".yes").attr('checked', true);
}else{
$("#is_teach_intern").val(0);
$('#teach_intern').find(".no").attr('checked', true);
$('#teach_intern').find(".yes").attr('checked', false);
}
});
//第11个问题
var person_write = $('#is_person_write').val();
$("#person_write input[type='checkbox']").live('click', function(e){
var is_person_write = $(this).val();
if($(this).is(':checked') && is_person_write == 1){
$("#is_teach_intern").val(1);
$('#person_write').find(".no").attr('checked', false);
$('#person_write').find(".yes").attr('checked', true);
}else{
$("#is_person_write").val(0);
$('#person_write').find(".no").attr('checked', true);
$('#person_write').find(".yes").attr('checked', false);
}
});
//第12个问题
var semester = $('#is_semester').val();
$("#semester input[type='checkbox']").live('click', function(e){
var is_semester = $(this).val();
if($(this).is(':checked') && is_semester == 1){
$("#is_teach_intern").val(1);
$('#semester').find(".no").attr('checked', false);
$('#semester').find(".yes").attr('checked', true);
}else{
$("#is_semester").val(0);
$('#semester').find(".no").attr('checked', true);
$('#semester').find(".yes").attr('checked', false);
}
});
//第13个问题
var head_teacher = $('#is_head_teacher').val();
$("#head_teacher input[type='checkbox']").live('click', function(e){
var is_head_teacher = $(this).val();
if($(this).is(':checked') && is_head_teacher == 1){
$("#is_head_teacher").val(1);
$('#head_teacher').find(".no").attr('checked', false);
$('#head_teacher').find(".yes").attr('checked', true);
}else{
$("#is_head_teacher").val(0);
$('#head_teacher').find(".no").attr('checked', true);
$('#head_teacher').find(".yes").attr('checked', false);
}
});
//第14个问题
var learning_exper = $('#is_learning_exper').val();
$("#learning_exper input[type='checkbox']").live('click', function(e){
var is_learning_exper = $(this).val();
if($(this).is(':checked') && is_learning_exper == 1){
$("#is_learning_exper").val(1);
$('#learning_exper').find(".no").attr('checked', false);
$('#learning_exper').find(".yes").attr('checked', true);
}else{
$("#is_learning_exper").val(0);
$('#learning_exper').find(".no").attr('checked', true);
$('#learning_exper').find(".yes").attr('checked', false);
}
});
//第15个问题
var class_meeting = $('#is_class_meeting').val();
$("#class_meeting input[type='checkbox']").live('click', function(e){
var is_class_meeting = $(this).val();
if($(this).is(':checked') && is_class_meeting == 1){
$("#is_class_meeting").val(1);
$('#class_meeting').find(".no").attr('checked', false);
$('#class_meeting').find(".yes").attr('checked', true);
}else{
$("#is_class_meeting").val(0);
$('#class_meeting').find(".no").attr('checked', true);
$('#class_meeting').find(".yes").attr('checked', false);
}
});
//第16个问题
var good_head_teacher = $('#is_good_head_teacher').val();
$("#good_head_teacher input[type='checkbox']").live('click', function(e){
var is_good_head_teacher = $(this).val();
if($(this).is(':checked') && is_good_head_teacher == 1){
$("#is_good_head_teacher").val(1);
$('#good_head_teacher').find(".no").attr('checked', false);
$('#good_head_teacher').find(".yes").attr('checked', true);
}else{
$("#is_good_head_teacher").val(0);
$('#good_head_teacher').find(".no").attr('checked', true);
$('#good_head_teacher').find(".yes").attr('checked', false);
}
});
//第17个问题
var fes_activity = $('#is_fes_activity').val();
$("#fes_activity input[type='checkbox']").live('click', function(e){
var is_fes_activity = $(this).val();
if($(this).is(':checked') && is_fes_activity == 1){
$("#is_fes_activity").val(1);
$('#fes_activity').find(".no").attr('checked', false);
$('#fes_activity').find(".yes").attr('checked', true);
}else{
$("#is_fes_activity").val(0);
$('#fes_activity').find(".no").attr('checked', true);
$('#fes_activity').find(".yes").attr('checked', false);
}
});
//第18个问题
var work_for_school = $('#is_work_for_school').val();
$("#work_for_school input[type='checkbox']").live('click', function(e){
var is_work_for_school = $(this).val();
if($(this).is(':checked') && is_work_for_school == 1){
$("#is_work_for_school").val(1);
$('#work_for_school').find(".no").attr('checked', false);
$('#work_for_school').find(".yes").attr('checked', true);
}else{
$("#is_work_for_school").val(0);
$('#work_for_school').find(".no").attr('checked', true);
$('#work_for_school').find(".yes").attr('checked', false);
}
});
//第19个问题
var manange_school = $('#is_manange_school').val();
$("#manange_school input[type='checkbox']").live('click', function(e){
var is_manange_school = $(this).val();
if($(this).is(':checked') && is_manange_school == 1){
$("#is_manange_school").val(1);
$('#manange_school').find(".no").attr('checked', false);
$('#manange_school').find(".yes").attr('checked', true);
}else{
$("#is_manange_school").val(0);
$('#manange_school').find(".no").attr('checked', true);
$('#manange_school').find(".yes").attr('checked', false);
}
});
//第20个问题
var research_school = $('#is_research_school').val();
$("#research_school input[type='checkbox']").live('click', function(e){
var is_research_school = $(this).val();
if($(this).is(':checked') && is_research_school == 1){
$("#is_research_school").val(1);
$('#research_school').find(".no").attr('checked', false);
$('#research_school').find(".yes").attr('checked', true);
}else{
$("#is_research_school").val(0);
$('#research_school').find(".no").attr('checked', true);
$('#research_school').find(".yes").attr('checked', false);
}
});
});
|
lnc2014/school
|
template/js/add_per.js
|
JavaScript
|
apache-2.0
| 13,016 |
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "AlphaCompositeTileOperation.h"
#include <memory>
#include "../../fb/DistributedFrameBuffer.h"
#include "fb/DistributedFrameBuffer_ispc.h"
namespace ospray {
struct BufferedTile
{
ospray::Tile tile;
/*! determines order of this tile relative to other tiles.
Tiles will get blended with the 'over' operator in
increasing 'BufferedTile::sortOrder' value */
float sortOrder;
};
/* LiveTileOperation for data-parallel or hybrid-parallel rendering, where
* different (or partially shared) data is rendered on each rank
*/
struct LiveAlphaCompositeTile : public LiveTileOperation
{
LiveAlphaCompositeTile(DistributedFrameBuffer *dfb,
const vec2i &begin,
size_t tileID,
size_t ownerID);
void newFrame() override;
void process(const ospray::Tile &tile) override;
private:
std::vector<std::unique_ptr<BufferedTile>> bufferedTiles;
int currentGeneration;
int expectedInNextGeneration;
int missingInCurrentGeneration;
std::mutex mutex;
void reportCompositingError(const vec2i &tile);
};
LiveAlphaCompositeTile::LiveAlphaCompositeTile(DistributedFrameBuffer *dfb,
const vec2i &begin,
size_t tileID,
size_t ownerID)
: LiveTileOperation(dfb, begin, tileID, ownerID)
{}
void LiveAlphaCompositeTile::newFrame()
{
std::lock_guard<std::mutex> lock(mutex);
currentGeneration = 0;
expectedInNextGeneration = 0;
missingInCurrentGeneration = 1;
if (!bufferedTiles.empty()) {
handleError(OSP_INVALID_OPERATION,
std::to_string(mpicommon::workerRank())
+ " is starting with buffered tiles!");
}
}
void LiveAlphaCompositeTile::process(const ospray::Tile &tile)
{
std::lock_guard<std::mutex> lock(mutex);
{
auto addTile = rkcommon::make_unique<BufferedTile>();
std::memcpy(&addTile->tile, &tile, sizeof(tile));
bufferedTiles.push_back(std::move(addTile));
}
if (tile.generation == currentGeneration) {
--missingInCurrentGeneration;
expectedInNextGeneration += tile.children;
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
while (missingInCurrentGeneration == 0 && expectedInNextGeneration > 0) {
currentGeneration++;
missingInCurrentGeneration = expectedInNextGeneration;
expectedInNextGeneration = 0;
for (uint32_t i = 0; i < bufferedTiles.size(); i++) {
const BufferedTile *bt = bufferedTiles[i].get();
if (bt->tile.generation == currentGeneration) {
--missingInCurrentGeneration;
expectedInNextGeneration += bt->tile.children;
}
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
}
}
}
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
if (missingInCurrentGeneration == 0) {
// Sort for back-to-front blending
std::sort(bufferedTiles.begin(),
bufferedTiles.end(),
[](const std::unique_ptr<BufferedTile> &a,
const std::unique_ptr<BufferedTile> &b) {
return a->tile.sortOrder > b->tile.sortOrder;
});
Tile **tileArray = STACK_BUFFER(Tile *, bufferedTiles.size());
std::transform(bufferedTiles.begin(),
bufferedTiles.end(),
tileArray,
[](std::unique_ptr<BufferedTile> &t) { return &t->tile; });
ispc::DFB_sortAndBlendFragments(
(ispc::VaryingTile **)tileArray, bufferedTiles.size());
finished.region = tile.region;
finished.fbSize = tile.fbSize;
finished.rcp_fbSize = tile.rcp_fbSize;
accumulate(bufferedTiles[0]->tile);
bufferedTiles.clear();
tileIsFinished();
}
}
void LiveAlphaCompositeTile::reportCompositingError(const vec2i &tile)
{
std::stringstream str;
str << "negative missing on " << mpicommon::workerRank()
<< ", missing = " << missingInCurrentGeneration
<< ", expectedInNex = " << expectedInNextGeneration
<< ", current generation = " << currentGeneration << ", tile = " << tile;
handleError(OSP_INVALID_OPERATION, str.str());
}
std::shared_ptr<LiveTileOperation> AlphaCompositeTileOperation::makeTile(
DistributedFrameBuffer *dfb,
const vec2i &tileBegin,
size_t tileID,
size_t ownerID)
{
return std::make_shared<LiveAlphaCompositeTile>(
dfb, tileBegin, tileID, ownerID);
}
std::string AlphaCompositeTileOperation::toString() const
{
return "ospray::AlphaCompositeTileOperation";
}
} // namespace ospray
|
ospray/OSPRay
|
modules/mpi/ospray/render/distributed/AlphaCompositeTileOperation.cpp
|
C++
|
apache-2.0
| 4,549 |
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.services.clientpolicy;
/**
* Events on which client policies mechanism detects and do its operation
*
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
*/
public enum ClientPolicyEvent {
REGISTER,
REGISTERED,
UPDATE,
UPDATED,
VIEW,
UNREGISTER,
AUTHORIZATION_REQUEST,
TOKEN_REQUEST,
SERVICE_ACCOUNT_TOKEN_REQUEST,
TOKEN_REFRESH,
TOKEN_REVOKE,
TOKEN_INTROSPECT,
USERINFO_REQUEST,
LOGOUT_REQUEST,
BACKCHANNEL_AUTHENTICATION_REQUEST,
BACKCHANNEL_TOKEN_REQUEST,
PUSHED_AUTHORIZATION_REQUEST,
DEVICE_AUTHORIZATION_REQUEST,
DEVICE_TOKEN_REQUEST
}
|
pedroigor/keycloak
|
server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java
|
Java
|
apache-2.0
| 1,353 |
var THREE = require('three');
var cgaprocessor = require('./cgaprocessor')
// function t(sizes, size, repeat) {
// console.log(sizes, size, repeat);
// console.log(cgaprocessor._compute_splits( sizes, size, repeat ));
// }
// t([ { size: 2 } ], 4, true);
// t([ { size: 2 } ], 5, true);
// t([ { size: 2 }, { size: 2 } ], 4, true);
// t([ { size: 2 }, { size: 2 } ], 5, true);
// t([ { size: 2, _float: true }, { size: 2 } ], 3, true);
// t([ { size: 2 }, { size: 2, _float: true }, { size: 2 } ], 4.5, true);
// t([ { size: 2 }, { size: 1, _float: true }, { size: 2, _float: true }, { size: 2 } ], 4.5, true);
//var preg = new THREE.BoxGeometry(2,2,2);
var preg = new THREE.Geometry();
preg.vertices.push(new THREE.Vector3(0,0,0),
new THREE.Vector3(1,1,0),
new THREE.Vector3(2,0,0));
preg.faces.push(new THREE.Face3(0,1,2));
//preg.translate(2,0,0);
// var preg = new THREE.Geometry();
// preg.vertices.push(new THREE.Vector3(-1,0,0),
// new THREE.Vector3(-1,1,0),
// new THREE.Vector3(1,0,0));
// preg.faces.push(new THREE.Face3(0,1,2));
// preg.translate(2,0,0);
preg.computeBoundingBox();
console.dir(preg.boundingBox);
console.log(preg.vertices.length, preg.faces.length);
debugger;
var g = cgaprocessor.split_geometry('x', preg, 0.5, 1.5);
g.computeBoundingBox();
console.dir(g.boundingBox);
console.log(g.vertices.length, g.faces.length);
g.vertices.forEach( v => console.log(v) );
g.faces.forEach( v => console.log(v.a,v.b,v.c) );
|
gromgull/cgajs
|
test/test_splitting.js
|
JavaScript
|
apache-2.0
| 1,531 |
import { Entity } from '../entity/entity';
/*******************************************************************************************************************************************************************************************************
*
* @data FragmentType - FragmentType inherited from Entity it is a specific type of a LevelGraphNode
*
* Entity
* @superFields - id: number - ID of the FragmentType
* @superFields - name: string - Name of the FragmentType
* @superFields - expectedProperties: ExpectedProperty[] - Array of expected properties of the FragmentType
* @superFields - providedProperties: ProvidedProperty[] - Array of provided properties of the FragmentType
*
* @author Arthur Kaul
*
******************************************************************************************************************************************************************************************************/
export class FragmentType extends Entity {
constructor() {
super();
}
}
|
kaular/ArchRef
|
ArchRefClient/ArchRefClient/src/app/shared/datamodels/types/fragmenttype.ts
|
TypeScript
|
apache-2.0
| 1,002 |
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.extensions.events;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.extensions.api.changes.NotifyHandling;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.RevisionInfo;
import com.google.gerrit.extensions.events.ChangeRestoredListener;
import com.google.gerrit.server.GpgException;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gerrit.server.patch.PatchListObjectTooLargeException;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.plugincontext.PluginSetContext;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.time.Instant;
/** Helper class to fire an event when a change has been restored. */
@Singleton
public class ChangeRestored {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final PluginSetContext<ChangeRestoredListener> listeners;
private final EventUtil util;
@Inject
ChangeRestored(PluginSetContext<ChangeRestoredListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
public void fire(
ChangeData changeData, PatchSet ps, AccountState restorer, String reason, Instant when) {
if (listeners.isEmpty()) {
return;
}
try {
Event event =
new Event(
util.changeInfo(changeData),
util.revisionInfo(changeData.project(), ps),
util.accountInfo(restorer),
reason,
when);
listeners.runEach(l -> l.onChangeRestored(event));
} catch (PatchListObjectTooLargeException e) {
logger.atWarning().log("Couldn't fire event: %s", e.getMessage());
} catch (PatchListNotAvailableException
| GpgException
| IOException
| StorageException
| PermissionBackendException e) {
logger.atSevere().withCause(e).log("Couldn't fire event");
}
}
/** Event to be fired when a change has been restored. */
private static class Event extends AbstractRevisionEvent implements ChangeRestoredListener.Event {
private String reason;
Event(
ChangeInfo change,
RevisionInfo revision,
AccountInfo restorer,
String reason,
Instant when) {
super(change, revision, restorer, when, NotifyHandling.ALL);
this.reason = reason;
}
@Override
public String getReason() {
return reason;
}
}
}
|
GerritCodeReview/gerrit
|
java/com/google/gerrit/server/extensions/events/ChangeRestored.java
|
Java
|
apache-2.0
| 3,450 |
package net.safedata.spring.boot.training.solace.publisher;
import net.safedata.spring.boot.training.solace.channel.OutboundChannels;
import net.safedata.spring.boot.training.solace.event.AddProductToOrderCommand;
import net.safedata.spring.boot.training.solace.event.OrderUpdatedEvent;
import net.safedata.spring.boot.training.solace.message.MessageCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.stereotype.Component;
@Component
@EnableBinding(OutboundChannels.class)
public class MessagePublisher {
private final OutboundChannels outboundChannels;
@Autowired
public MessagePublisher(final OutboundChannels outboundChannels) {
this.outboundChannels = outboundChannels;
}
public void publishAddProductToOrderEvent(final AddProductToOrderCommand addProductToOrderCommand) {
outboundChannels.addProductToOrder()
.send(MessageCreator.create(addProductToOrderCommand));
}
public void publishOrderUpdatedEvent(final OrderUpdatedEvent orderUpdatedEvent) {
outboundChannels.orderUpdated()
.send(MessageCreator.create(orderUpdatedEvent));
}
}
|
bogdansolga/spring-boot-training
|
d04/d04s01-async-processing/d04s01e05-async-messaging-using-solace/d04s01e05-product-publisher/src/main/java/net/safedata/spring/boot/training/solace/publisher/MessagePublisher.java
|
Java
|
apache-2.0
| 1,255 |
package cn.demoz.www.adapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.List;
import cn.demoz.www.holder.BaseHolder;
import cn.demoz.www.holder.MoreHolder;
import cn.demoz.www.manager.ThreadManager;
import cn.demoz.www.tools.UiUtils;
public abstract class DefaultAdapter<Data> extends BaseAdapter implements OnItemClickListener {
protected List<Data> datas;
private static final int DEFAULT_ITEM = 0;
private static final int MORE_ITEM = 1;
private ListView lv;
public List<Data> getDatas() {
return datas;
}
public void setDatas(List<Data> datas) {
this.datas = datas;
}
public DefaultAdapter(List<Data> datas, ListView lv) {
this.datas = datas;
// 给ListView设置条目的点击事件
lv.setOnItemClickListener(this);
this.lv = lv;
}
// ListView 条目点击事件回调的方法
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Toast.makeText(UiUtils.getContext(), "position:"+position, 0).show();
position = position - lv.getHeaderViewsCount();// 获取到顶部条目的数量 位置去掉顶部view的数量
onInnerItemClick(position);
}
/**
* 在该方法去处理条目的点击事件
*/
public void onInnerItemClick(int position) {
}
@Override
public int getCount() {
return datas.size() + 1; // 最后的一个条目 就是加载更多的条目
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
/**
* 根据位置 判断当前条目是什么类型
*/
@Override
public int getItemViewType(int position) { //20
if (position == datas.size()) { // 当前是最后一个条目
return MORE_ITEM;
}
return getInnerItemViewType(position); // 如果不是最后一个条目 返回默认类型
}
protected int getInnerItemViewType(int position) {
return DEFAULT_ITEM;
}
/**
* 当前ListView 有几种不同的条目类型
*/
@Override
public int getViewTypeCount() {
return super.getViewTypeCount() + 1; // 2 有两种不同的类型
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
BaseHolder holder = null;
switch (getItemViewType(position)) { // 判断当前条目时什么类型
case MORE_ITEM:
if (convertView == null) {
holder = getMoreHolder();
} else {
holder = (BaseHolder) convertView.getTag();
}
break;
default:
if (convertView == null) {
holder = getHolder();
} else {
holder = (BaseHolder) convertView.getTag();
}
if (position < datas.size()) {
holder.setData(datas.get(position));
}
break;
}
return holder.getContentView(); // 如果当前Holder 恰好是MoreHolder 证明MoreHOlder已经显示
}
private MoreHolder holder;
private BaseHolder getMoreHolder() {
if (holder != null) {
return holder;
} else {
holder = new MoreHolder(this, hasMore());
return holder;
}
}
/**
* 是否有额外的数据
*
* @return
*/
protected boolean hasMore() {
return true;
}
protected abstract BaseHolder<Data> getHolder();
/**
* 当加载更多条目显示的时候 调用该方法
*/
public void loadMore() {
ThreadManager.getInstance().createLongPool().execute(new Runnable() {
@Override
public void run() {
// 在子线程中加载更多
final List<Data> newData = onload();
UiUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (newData == null) {
holder.setData(MoreHolder.LOAD_ERROR);//
} else if (newData.size() == 0) {
holder.setData(MoreHolder.HAS_NO_MORE);
} else {
// 成功了
holder.setData(MoreHolder.HAS_MORE);
datas.addAll(newData);// 给listView之前的集合添加一个新的集合
notifyDataSetChanged();// 刷新界面
}
}
});
}
});
}
/**
* 加载更多数据
*/
protected abstract List<Data> onload();
}
|
jxent/Demoz
|
Demoz/app/src/main/java/cn/demoz/www/adapter/DefaultAdapter.java
|
Java
|
apache-2.0
| 5,112 |
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.tools.attach;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.spi.AttachProvider;
import java.io.InputStream;
import java.io.IOException;
import java.io.File;
/*
* Linux implementation of HotSpotVirtualMachine
*/
public class LinuxVirtualMachine extends HotSpotVirtualMachine {
// "/tmp" is used as a global well-known location for the files
// .java_pid<pid>. and .attach_pid<pid>. It is important that this
// location is the same for all processes, otherwise the tools
// will not be able to find all Hotspot processes.
// Any changes to this needs to be synchronized with HotSpot.
private static final String tmpdir = "/tmp";
// Indicates if this machine uses the old LinuxThreads
static boolean isLinuxThreads;
// The patch to the socket file created by the target VM
String path;
/**
* Attaches to the target VM
*/
public LinuxVirtualMachine(AttachProvider provider, String vmid)
throws AttachNotSupportedException, IOException
{
super(provider, vmid);
// This provider only understands pids
int pid;
try {
pid = Integer.parseInt(vmid);
} catch (NumberFormatException x) {
throw new AttachNotSupportedException("Invalid process identifier");
}
// Find the socket file. If not found then we attempt to start the
// attach mechanism in the target VM by sending it a QUIT signal.
// Then we attempt to find the socket file again.
path = findSocketFile(pid);
if (path == null) {
File f = createAttachFile(pid);
try {
// On LinuxThreads each thread is a process and we don't have the
// pid of the VMThread which has SIGQUIT unblocked. To workaround
// this we get the pid of the "manager thread" that is created
// by the first call to pthread_create. This is parent of all
// threads (except the initial thread).
if (isLinuxThreads) {
int mpid;
try {
mpid = getLinuxThreadsManager(pid);
} catch (IOException x) {
throw new AttachNotSupportedException(x.getMessage());
}
assert(mpid >= 1);
sendQuitToChildrenOf(mpid);
} else {
sendQuitTo(pid);
}
// give the target VM time to start the attach mechanism
int i = 0;
long delay = 200;
int retries = (int)(attachTimeout() / delay);
do {
try {
Thread.sleep(delay);
} catch (InterruptedException x) { }
path = findSocketFile(pid);
i++;
} while (i <= retries && path == null);
if (path == null) {
throw new AttachNotSupportedException(
"Unable to open socket file: target process not responding " +
"or HotSpot VM not loaded");
}
} finally {
f.delete();
}
}
// Check that the file owner/permission to avoid attaching to
// bogus process
checkPermissions(path);
// Check that we can connect to the process
// - this ensures we throw the permission denied error now rather than
// later when we attempt to enqueue a command.
int s = socket();
try {
connect(s, path);
} finally {
close(s);
}
}
/**
* Detach from the target VM
*/
@Override
public void detach() throws IOException {
synchronized (this) {
if (this.path != null) {
this.path = null;
}
}
}
// protocol version
private final static String PROTOCOL_VERSION = "1";
// known errors
private final static int ATTACH_ERROR_BADVERSION = 101;
/**
* Execute the given command in the target VM.
*/
@Override
InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
assert args.length <= 3; // includes null
// did we detach?
String p;
synchronized (this) {
if (this.path == null) {
throw new IOException("Detached from target VM");
}
p = this.path;
}
// create UNIX socket
int s = socket();
// connect to target VM
try {
connect(s, p);
} catch (IOException x) {
close(s);
throw x;
}
IOException ioe = null;
// connected - write request
// <ver> <cmd> <args...>
try {
writeString(s, PROTOCOL_VERSION);
writeString(s, cmd);
for (int i=0; i<3; i++) {
if (i < args.length && args[i] != null) {
writeString(s, (String)args[i]);
} else {
writeString(s, "");
}
}
} catch (IOException x) {
ioe = x;
}
// Create an input stream to read reply
SocketInputStream sis = new SocketInputStream(s);
// Read the command completion status
int completionStatus;
try {
completionStatus = readInt(sis);
} catch (IOException x) {
sis.close();
if (ioe != null) {
throw ioe;
} else {
throw x;
}
}
if (completionStatus != 0) {
sis.close();
// In the event of a protocol mismatch then the target VM
// returns a known error so that we can throw a reasonable
// error.
if (completionStatus == ATTACH_ERROR_BADVERSION) {
throw new IOException("Protocol mismatch with target VM");
}
// Special-case the "load" command so that the right exception is
// thrown.
if (cmd.equals("load")) {
throw new AgentLoadException("Failed to load agent library");
} else {
throw new IOException("Command failed in target VM");
}
}
// Return the input stream so that the command output can be read
return sis;
}
/*
* InputStream for the socket connection to get target VM
*/
private class SocketInputStream extends InputStream {
int s;
public SocketInputStream(int s) {
this.s = s;
}
@Override
public synchronized int read() throws IOException {
byte b[] = new byte[1];
int n = this.read(b, 0, 1);
if (n == 1) {
return b[0] & 0xff;
} else {
return -1;
}
}
@Override
public synchronized int read(byte[] bs, int off, int len) throws IOException {
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0)
return 0;
return LinuxVirtualMachine.read(s, bs, off, len);
}
@Override
public void close() throws IOException {
LinuxVirtualMachine.close(s);
}
}
// Return the socket file for the given process.
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
// On Solaris/Linux a simple handshake is used to start the attach mechanism
// if not already started. The client creates a .attach_pid<pid> file in the
// target VM's working directory (or temp directory), and the SIGQUIT handler
// checks for the file.
private File createAttachFile(int pid) throws IOException {
String fn = ".attach_pid" + pid;
String path = "/proc/" + pid + "/cwd/" + fn;
File f = new File(path);
try {
f.createNewFile();
} catch (IOException x) {
f = new File(tmpdir, fn);
f.createNewFile();
}
return f;
}
/*
* Write/sends the given to the target VM. String is transmitted in
* UTF-8 encoding.
*/
private void writeString(int fd, String s) throws IOException {
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
LinuxVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
}
//-- native methods
static native boolean isLinuxThreads();
static native int getLinuxThreadsManager(int pid) throws IOException;
static native void sendQuitToChildrenOf(int pid) throws IOException;
static native void sendQuitTo(int pid) throws IOException;
static native void checkPermissions(String path) throws IOException;
static native int socket() throws IOException;
static native void connect(int fd, String path) throws IOException;
static native void close(int fd) throws IOException;
static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;
static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;
static {
System.loadLibrary("attach");
isLinuxThreads = isLinuxThreads();
}
}
|
gstamac/powermock
|
powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java
|
Java
|
apache-2.0
| 11,227 |
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AsyncResolverDef,
ResolverReturnDef,
SyncResolverDef,
VariableSource,
getNavigationData,
getTimingDataAsync,
getTimingDataSync,
} from './variable-source';
import {Expander, NOENCODE_WHITELIST} from './url-expander/expander';
import {Services} from '../services';
import {WindowInterface} from '../window-interface';
import {
addMissingParamsToUrl,
addParamsToUrl,
getSourceUrl,
isProtocolValid,
parseQueryString,
parseUrlDeprecated,
removeAmpJsParamsFromUrl,
removeFragment,
} from '../url';
import {dev, rethrowAsync, user} from '../log';
import {getMode} from '../mode';
import {getTrackImpressionPromise} from '../impression.js';
import {hasOwn} from '../utils/object';
import {
installServiceInEmbedScope,
registerServiceBuilderForDoc,
} from '../service';
import {isExperimentOn} from '../experiments';
import {tryResolve} from '../utils/promise';
/** @private @const {string} */
const TAG = 'UrlReplacements';
const EXPERIMENT_DELIMITER = '!';
const VARIANT_DELIMITER = '.';
const GEO_DELIM = ',';
const ORIGINAL_HREF_PROPERTY = 'amp-original-href';
const ORIGINAL_VALUE_PROPERTY = 'amp-original-value';
/**
* Returns a encoded URI Component, or an empty string if the value is nullish.
* @param {*} val
* @return {string}
*/
function encodeValue(val) {
if (val == null) {
return '';
}
return encodeURIComponent(/** @type {string} */(val));
}
/**
* Returns a function that executes method on a new Date instance. This is a
* byte saving hack.
*
* @param {string} method
* @return {!SyncResolverDef}
*/
function dateMethod(method) {
return () => new Date()[method]();
}
/**
* Returns a function that returns property of screen. This is a byte saving
* hack.
*
* @param {!Screen} screen
* @param {string} property
* @return {!SyncResolverDef}
*/
function screenProperty(screen, property) {
return () => screen[property];
}
/**
* Class to provide variables that pertain to top level AMP window.
*/
export class GlobalVariableSource extends VariableSource {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
super(ampdoc);
/** @private {?Promise<?Object<string, string>>} */
this.variants_ = null;
/** @private {?Promise<?ShareTrackingFragmentsDef>} */
this.shareTrackingFragments_ = null;
}
/**
* Utility function for setting resolver for timing data that supports
* sync and async.
* @param {string} varName
* @param {string} startEvent
* @param {string=} endEvent
* @return {!VariableSource}
* @private
*/
setTimingResolver_(varName, startEvent, endEvent) {
return this.setBoth(varName, () => {
return getTimingDataSync(this.ampdoc.win, startEvent, endEvent);
}, () => {
return getTimingDataAsync(this.ampdoc.win, startEvent, endEvent);
});
}
/** @override */
initialize() {
/** @const {!./viewport/viewport-impl.Viewport} */
const viewport = Services.viewportForDoc(this.ampdoc);
// Returns a random value for cache busters.
this.set('RANDOM', () => Math.random());
// Provides a counter starting at 1 per given scope.
const counterStore = Object.create(null);
this.set('COUNTER', scope => {
return counterStore[scope] = (counterStore[scope] | 0) + 1;
});
// Returns the canonical URL for this AMP document.
this.set('CANONICAL_URL', this.getDocInfoUrl_('canonicalUrl'));
// Returns the host of the canonical URL for this AMP document.
this.set('CANONICAL_HOST', this.getDocInfoUrl_('canonicalUrl', 'host'));
// Returns the hostname of the canonical URL for this AMP document.
this.set('CANONICAL_HOSTNAME', this.getDocInfoUrl_('canonicalUrl',
'hostname'));
// Returns the path of the canonical URL for this AMP document.
this.set('CANONICAL_PATH', this.getDocInfoUrl_('canonicalUrl', 'pathname'));
// Returns the referrer URL.
this.setAsync('DOCUMENT_REFERRER', /** @type {AsyncResolverDef} */(() => {
return Services.viewerForDoc(this.ampdoc).getReferrerUrl();
}));
// Like DOCUMENT_REFERRER, but returns null if the referrer is of
// same domain or the corresponding CDN proxy.
this.setAsync('EXTERNAL_REFERRER', /** @type {AsyncResolverDef} */(() => {
return Services.viewerForDoc(this.ampdoc).getReferrerUrl()
.then(referrer => {
if (!referrer) {
return null;
}
const referrerHostname = parseUrlDeprecated(getSourceUrl(referrer))
.hostname;
const currentHostname =
WindowInterface.getHostname(this.ampdoc.win);
return referrerHostname === currentHostname ? null : referrer;
});
}));
// Returns the title of this AMP document.
this.set('TITLE', () => {
// The environment may override the title and set originalTitle. Prefer
// that if available.
return this.ampdoc.win.document['originalTitle'] ||
this.ampdoc.win.document.title;
});
// Returns the URL for this AMP document.
this.set('AMPDOC_URL', () => {
return removeFragment(
this.addReplaceParamsIfMissing_(
this.ampdoc.win.location.href));
});
// Returns the host of the URL for this AMP document.
this.set('AMPDOC_HOST', () => {
const url = parseUrlDeprecated(this.ampdoc.win.location.href);
return url && url.host;
});
// Returns the hostname of the URL for this AMP document.
this.set('AMPDOC_HOSTNAME', () => {
const url = parseUrlDeprecated(this.ampdoc.win.location.href);
return url && url.hostname;
});
// Returns the Source URL for this AMP document.
const expandSourceUrl = () => {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
return removeFragment(this.addReplaceParamsIfMissing_(docInfo.sourceUrl));
};
this.setBoth('SOURCE_URL',
() => expandSourceUrl(),
() => getTrackImpressionPromise().then(() => expandSourceUrl()));
// Returns the host of the Source URL for this AMP document.
this.set('SOURCE_HOST', this.getDocInfoUrl_('sourceUrl', 'host'));
// Returns the hostname of the Source URL for this AMP document.
this.set('SOURCE_HOSTNAME', this.getDocInfoUrl_('sourceUrl', 'hostname'));
// Returns the path of the Source URL for this AMP document.
this.set('SOURCE_PATH', this.getDocInfoUrl_('sourceUrl', 'pathname'));
// Returns a random string that will be the constant for the duration of
// single page view. It should have sufficient entropy to be unique for
// all the page views a single user is making at a time.
this.set('PAGE_VIEW_ID', this.getDocInfoUrl_('pageViewId'));
this.setBoth('QUERY_PARAM', (param, defaultValue = '') => {
return this.getQueryParamData_(param, defaultValue);
}, (param, defaultValue = '') => {
return getTrackImpressionPromise().then(() => {
return this.getQueryParamData_(param, defaultValue);
});
});
// Returns the value of the given field name in the fragment query string.
// Second parameter is an optional default value.
// For example, if location is 'pub.com/amp.html?x=1#y=2' then
// FRAGMENT_PARAM(y) returns '2' and FRAGMENT_PARAM(z, 3) returns 3.
this.setAsync('FRAGMENT_PARAM',
this.getViewerIntegrationValue_('fragmentParam', 'FRAGMENT_PARAM'));
// Returns the first item in the ancestorOrigins array, if available.
this.setAsync('ANCESTOR_ORIGIN',
this.getViewerIntegrationValue_('ancestorOrigin', 'ANCESTOR_ORIGIN'));
/**
* Stores client ids that were generated during this page view
* indexed by scope.
* @type {?Object<string, string>}
*/
let clientIds = null;
// Synchronous alternative. Only works for scopes that were previously
// requested using the async method.
this.setBoth('CLIENT_ID', scope => {
if (!clientIds) {
return null;
}
return clientIds[dev().assertString(scope)];
}, (scope, opt_userNotificationId, opt_cookieName) => {
user().assertString(scope,
'The first argument to CLIENT_ID, the fallback' +
/*OK*/' Cookie name, is required');
if (getMode().runtime == 'inabox') {
return /** @type {!Promise<ResolverReturnDef>} */(Promise.resolve(null));
}
let consent = Promise.resolve();
// If no `opt_userNotificationId` argument is provided then
// assume consent is given by default.
if (opt_userNotificationId) {
consent = Services.userNotificationManagerForDoc(this.ampdoc)
.then(service => {
return service.get(opt_userNotificationId);
});
}
return Services.cidForDoc(this.ampdoc).then(cid => {
return cid.get({
scope: dev().assertString(scope),
createCookieIfNotPresent: true,
cookieName: opt_cookieName,
}, consent);
}).then(cid => {
if (!clientIds) {
clientIds = Object.create(null);
}
// A temporary work around to extract Client ID from _ga cookie. #5761
// TODO: replace with "filter" when it's in place. #2198
const cookieName = opt_cookieName || scope;
if (cid && cookieName == '_ga') {
if (typeof cid === 'string') {
cid = extractClientIdFromGaCookie(cid);
} else {
// TODO(@jridgewell, #11120): remove once #11120 is figured out.
// Do not log the CID directly, that's PII.
dev().error(TAG, 'non-string cid, what is it?', Object.keys(cid));
}
}
clientIds[scope] = cid;
return cid;
});
});
// Returns assigned variant name for the given experiment.
this.setAsync('VARIANT', /** @type {AsyncResolverDef} */(experiment => {
return this.getVariantsValue_(variants => {
const variant = variants[/** @type {string} */(experiment)];
user().assert(variant !== undefined,
'The value passed to VARIANT() is not a valid experiment name:' +
experiment);
// When no variant assigned, use reserved keyword 'none'.
return variant === null ? 'none' : /** @type {string} */(variant);
}, 'VARIANT');
}));
// Returns all assigned experiment variants in a serialized form.
this.setAsync('VARIANTS', /** @type {AsyncResolverDef} */(() => {
return this.getVariantsValue_(variants => {
const experiments = [];
for (const experiment in variants) {
const variant = variants[experiment];
experiments.push(
experiment + VARIANT_DELIMITER + (variant || 'none'));
}
return experiments.join(EXPERIMENT_DELIMITER);
}, 'VARIANTS');
}));
// Returns assigned geo value for geoType or all groups.
this.setAsync('AMP_GEO', /** @type {AsyncResolverDef} */(geoType => {
return this.getGeo_(geos => {
if (geoType) {
user().assert(geoType === 'ISOCountry',
'The value passed to AMP_GEO() is not valid name:' + geoType);
return /** @type {string} */ (geos[geoType] || 'unknown');
}
return /** @type {string} */ (geos.ISOCountryGroups.join(GEO_DELIM));
}, 'AMP_GEO');
}));
// Returns incoming share tracking fragment.
this.setAsync('SHARE_TRACKING_INCOMING', /** @type {AsyncResolverDef} */(
() => {
return this.getShareTrackingValue_(fragments => {
return fragments.incomingFragment;
}, 'SHARE_TRACKING_INCOMING');
}));
// Returns outgoing share tracking fragment.
this.setAsync('SHARE_TRACKING_OUTGOING', /** @type {AsyncResolverDef} */(
() => {
return this.getShareTrackingValue_(fragments => {
return fragments.outgoingFragment;
}, 'SHARE_TRACKING_OUTGOING');
}));
// Returns the number of milliseconds since 1 Jan 1970 00:00:00 UTC.
this.set('TIMESTAMP', dateMethod('getTime'));
// Returns the human readable timestamp in format of
// 2011-01-01T11:11:11.612Z.
this.set('TIMESTAMP_ISO', dateMethod('toISOString'));
// Returns the user's time-zone offset from UTC, in minutes.
this.set('TIMEZONE', dateMethod('getTimezoneOffset'));
// Returns the IANA timezone code
this.set('TIMEZONE_CODE', () => {
let tzCode;
if ('Intl' in this.ampdoc.win &&
'DateTimeFormat' in this.ampdoc.win.Intl) {
// It could be undefined (i.e. IE11)
tzCode = new Intl.DateTimeFormat().resolvedOptions().timeZone;
}
return tzCode || '';
});
// Returns a promise resolving to viewport.getScrollTop.
this.set('SCROLL_TOP', () => viewport.getScrollTop());
// Returns a promise resolving to viewport.getScrollLeft.
this.set('SCROLL_LEFT', () => viewport.getScrollLeft());
// Returns a promise resolving to viewport.getScrollHeight.
this.set('SCROLL_HEIGHT', () => viewport.getScrollHeight());
// Returns a promise resolving to viewport.getScrollWidth.
this.set('SCROLL_WIDTH', () => viewport.getScrollWidth());
// Returns the viewport height.
this.set('VIEWPORT_HEIGHT', () => viewport.getHeight());
// Returns the viewport width.
this.set('VIEWPORT_WIDTH', () => viewport.getWidth());
const {screen} = this.ampdoc.win;
// Returns screen.width.
this.set('SCREEN_WIDTH', screenProperty(screen, 'width'));
// Returns screen.height.
this.set('SCREEN_HEIGHT', screenProperty(screen, 'height'));
// Returns screen.availHeight.
this.set('AVAILABLE_SCREEN_HEIGHT', screenProperty(screen, 'availHeight'));
// Returns screen.availWidth.
this.set('AVAILABLE_SCREEN_WIDTH', screenProperty(screen, 'availWidth'));
// Returns screen.ColorDepth.
this.set('SCREEN_COLOR_DEPTH', screenProperty(screen, 'colorDepth'));
// Returns document characterset.
this.set('DOCUMENT_CHARSET', () => {
const doc = this.ampdoc.win.document;
return doc.characterSet || doc.charset;
});
// Returns the browser language.
this.set('BROWSER_LANGUAGE', () => {
const nav = this.ampdoc.win.navigator;
return (nav.language || nav.userLanguage || nav.browserLanguage || '')
.toLowerCase();
});
// Returns the user agent.
this.set('USER_AGENT', () => {
const nav = this.ampdoc.win.navigator;
return nav.userAgent;
});
// Returns the time it took to load the whole page. (excludes amp-* elements
// that are not rendered by the system yet.)
this.setTimingResolver_(
'PAGE_LOAD_TIME', 'navigationStart', 'loadEventStart');
// Returns the time it took to perform DNS lookup for the domain.
this.setTimingResolver_(
'DOMAIN_LOOKUP_TIME', 'domainLookupStart', 'domainLookupEnd');
// Returns the time it took to connect to the server.
this.setTimingResolver_(
'TCP_CONNECT_TIME', 'connectStart', 'connectEnd');
// Returns the time it took for server to start sending a response to the
// request.
this.setTimingResolver_(
'SERVER_RESPONSE_TIME', 'requestStart', 'responseStart');
// Returns the time it took to download the page.
this.setTimingResolver_(
'PAGE_DOWNLOAD_TIME', 'responseStart', 'responseEnd');
// Returns the time it took for redirects to complete.
this.setTimingResolver_(
'REDIRECT_TIME', 'navigationStart', 'fetchStart');
// Returns the time it took for DOM to become interactive.
this.setTimingResolver_(
'DOM_INTERACTIVE_TIME', 'navigationStart', 'domInteractive');
// Returns the time it took for content to load.
this.setTimingResolver_(
'CONTENT_LOAD_TIME', 'navigationStart', 'domContentLoadedEventStart');
// Access: Reader ID.
this.setAsync('ACCESS_READER_ID', /** @type {AsyncResolverDef} */(() => {
return this.getAccessValue_(accessService => {
return accessService.getAccessReaderId();
}, 'ACCESS_READER_ID');
}));
// Access: data from the authorization response.
this.setAsync('AUTHDATA', /** @type {AsyncResolverDef} */(field => {
user().assert(field,
'The first argument to AUTHDATA, the field, is required');
return this.getAccessValue_(accessService => {
return accessService.getAuthdataField(field);
}, 'AUTHDATA');
}));
// Returns an identifier for the viewer.
this.setAsync('VIEWER', () => {
return Services.viewerForDoc(this.ampdoc)
.getViewerOrigin().then(viewer => {
return viewer == undefined ? '' : viewer;
});
});
// Returns the total engaged time since the content became viewable.
this.setAsync('TOTAL_ENGAGED_TIME', () => {
return Services.activityForDoc(this.ampdoc).then(activity => {
return activity.getTotalEngagedTime();
});
});
// Returns the incremental engaged time since the last push under the
// same name.
this.setAsync('INCREMENTAL_ENGAGED_TIME', (name, reset) => {
return Services.activityForDoc(this.ampdoc).then(activity => {
return activity.getIncrementalEngagedTime(name, reset !== 'false');
});
});
this.set('NAV_TIMING', (startAttribute, endAttribute) => {
user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' +
'start attribute name, is required');
return getTimingDataSync(
this.ampdoc.win,
/**@type {string}*/(startAttribute),
/**@type {string}*/(endAttribute));
});
this.setAsync('NAV_TIMING', (startAttribute, endAttribute) => {
user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' +
'start attribute name, is required');
return getTimingDataAsync(
this.ampdoc.win,
/**@type {string}*/(startAttribute),
/**@type {string}*/(endAttribute));
});
this.set('NAV_TYPE', () => {
return getNavigationData(this.ampdoc.win, 'type');
});
this.set('NAV_REDIRECT_COUNT', () => {
return getNavigationData(this.ampdoc.win, 'redirectCount');
});
// returns the AMP version number
this.set('AMP_VERSION', () => '$internalRuntimeVersion$');
this.set('BACKGROUND_STATE', () => {
return Services.viewerForDoc(this.ampdoc).isVisible() ? '0' : '1';
});
this.setAsync('VIDEO_STATE', (id, property) => {
const root = this.ampdoc.getRootNode();
const video = user().assertElement(
root.getElementById(/** @type {string} */ (id)),
`Could not find an element with id="${id}" for VIDEO_STATE`);
return Services.videoManagerForDoc(this.ampdoc)
.getAnalyticsDetails(video)
.then(details => details ? details[property] : '');
});
this.setAsync('STORY_PAGE_INDEX', this.getStoryValue_('pageIndex',
'STORY_PAGE_INDEX'));
this.setAsync('STORY_PAGE_ID', this.getStoryValue_('pageId',
'STORY_PAGE_ID'));
this.setAsync('FIRST_CONTENTFUL_PAINT', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getFirstContentfulPaint());
});
this.setAsync('FIRST_VIEWPORT_READY', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getFirstViewportReady());
});
this.setAsync('MAKE_BODY_VISIBLE', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getMakeBodyVisible());
});
this.setAsync('AMP_STATE', key => {
return Services.bindForDocOrNull(this.ampdoc).then(bind => {
if (!bind) {
return '';
}
return bind.getStateValue(/** @type {string} */ (key));
});
});
}
/**
* Merges any replacement parameters into a given URL's query string,
* preferring values set in the original query string.
* @param {string} orig The original URL
* @return {string} The resulting URL
* @private
*/
addReplaceParamsIfMissing_(orig) {
const {replaceParams} =
/** @type {!Object} */ (Services.documentInfoForDoc(this.ampdoc));
if (!replaceParams) {
return orig;
}
return addMissingParamsToUrl(removeAmpJsParamsFromUrl(orig), replaceParams);
}
/**
* Resolves the value via one of document info's urls.
* @param {string} field A field on the docInfo
* @param {string=} opt_urlProp A subproperty of the field
* @return {T}
* @template T
*/
getDocInfoUrl_(field, opt_urlProp) {
return () => {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
const value = docInfo[field];
return opt_urlProp ? parseUrlDeprecated(value)[opt_urlProp] : value;
};
}
/**
* Resolves the value via access service. If access service is not configured,
* the resulting value is `null`.
* @param {function(!../../extensions/amp-access/0.1/access-vars.AccessVars):(T|!Promise<T>)} getter
* @param {string} expr
* @return {T|null}
* @template T
* @private
*/
getAccessValue_(getter, expr) {
return Promise.all([
Services.accessServiceForDocOrNull(this.ampdoc),
Services.subscriptionsServiceForDocOrNull(this.ampdoc),
]).then(services => {
const service = /** @type {?../../extensions/amp-access/0.1/access-vars.AccessVars} */ (
services[0] || services[1]);
if (!service) {
// Access/subscriptions service is not installed.
user().error(
TAG,
'Access or subsciptions service is not installed to access: ',
expr);
return null;
}
return getter(service);
});
}
/**
* Return the QUERY_PARAM from the current location href
* @param {*} param
* @param {string} defaultValue
* @return {string}
* @private
*/
getQueryParamData_(param, defaultValue) {
user().assert(param,
'The first argument to QUERY_PARAM, the query string ' +
'param is required');
const url = parseUrlDeprecated(
removeAmpJsParamsFromUrl(this.ampdoc.win.location.href));
const params = parseQueryString(url.search);
const key = user().assertString(param);
const {replaceParams} = Services.documentInfoForDoc(this.ampdoc);
if (typeof params[key] !== 'undefined') {
return params[key];
}
if (replaceParams && typeof replaceParams[key] !== 'undefined') {
return /** @type {string} */(replaceParams[key]);
}
return defaultValue;
}
/**
* Resolves the value via amp-experiment's variants service.
* @param {function(!Object<string, string>):(?string)} getter
* @param {string} expr
* @return {!Promise<?string>}
* @template T
* @private
*/
getVariantsValue_(getter, expr) {
if (!this.variants_) {
this.variants_ = Services.variantForOrNull(this.ampdoc.win);
}
return this.variants_.then(variants => {
user().assert(variants,
'To use variable %s, amp-experiment should be configured',
expr);
return getter(variants);
});
}
/**
* Resolves the value via geo service.
* @param {function(Object<string, string>)} getter
* @param {string} expr
* @return {!Promise<Object<string,(string|Array<string>)>>}
* @template T
* @private
*/
getGeo_(getter, expr) {
return Services.geoForDocOrNull(this.ampdoc)
.then(geo => {
user().assert(geo,
'To use variable %s, amp-geo should be configured',
expr);
return getter(geo);
});
}
/**
* Resolves the value via amp-share-tracking's service.
* @param {function(!ShareTrackingFragmentsDef):T} getter
* @param {string} expr
* @return {!Promise<T>}
* @template T
* @private
*/
getShareTrackingValue_(getter, expr) {
if (!this.shareTrackingFragments_) {
this.shareTrackingFragments_ =
Services.shareTrackingForOrNull(this.ampdoc.win);
}
return this.shareTrackingFragments_.then(fragments => {
user().assert(fragments, 'To use variable %s, ' +
'amp-share-tracking should be configured',
expr);
return getter(/** @type {!ShareTrackingFragmentsDef} */ (fragments));
});
}
/**
* Resolves the value via amp-story's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getStoryValue_(property, name) {
return () => {
const service = Services.storyVariableServiceForOrNull(this.ampdoc.win);
return service.then(storyVariables => {
user().assert(storyVariables,
'To use variable %s amp-story should be configured', name);
return storyVariables[property];
});
};
}
/**
* Resolves the value via amp-viewer-integration's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getViewerIntegrationValue_(property, name) {
return /** @type {!AsyncResolverDef} */ (
(param, defaultValue = '') => {
const service =
Services.viewerIntegrationVariableServiceForOrNull(this.ampdoc.win);
return service.then(viewerIntegrationVariables => {
user().assert(viewerIntegrationVariables, 'To use variable %s ' +
'amp-viewer-integration must be installed', name);
return viewerIntegrationVariables[property](param, defaultValue);
});
});
}
}
/**
* This class replaces substitution variables with their values.
* Document new values in ../spec/amp-var-substitutions.md
* @package For export
*/
export class UrlReplacements {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!VariableSource} variableSource
*/
constructor(ampdoc, variableSource) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @type {VariableSource} */
this.variableSource_ = variableSource;
/** @type {!Expander} */
this.expander_ = new Expander(this.variableSource_);
}
/**
* Synchronously expands the provided source by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} source
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandStringSync(source, opt_bindings, opt_collectVars, opt_whiteList) {
return /** @type {string} */ (
this.expand_(source, opt_bindings, opt_collectVars, /* opt_sync */ true,
opt_whiteList));
}
/**
* Expands the provided source by replacing all known variables with their
* resolved values. Optional `opt_bindings` can be used to add new variables
* or override existing ones.
* @param {string} source
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList
* @return {!Promise<string>}
*/
expandStringAsync(source, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (this.expand_(source, opt_bindings,
/* opt_collectVars */ undefined,
/* opt_sync */ undefined, opt_whiteList));
}
/**
* Synchronously expands the provided URL by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} url
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandUrlSync(url, opt_bindings, opt_collectVars, opt_whiteList) {
return this.ensureProtocolMatches_(url, /** @type {string} */ (this.expand_(
url, opt_bindings, opt_collectVars, /* opt_sync */ true,
opt_whiteList)));
}
/**
* Expands the provided URL by replacing all known variables with their
* resolved values. Optional `opt_bindings` can be used to add new variables
* or override existing ones.
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of names
* that can be substituted.
* @return {!Promise<string>}
*/
expandUrlAsync(url, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (
this.expand_(url, opt_bindings, undefined, undefined,
opt_whiteList).then(
replacement => this.ensureProtocolMatches_(url, replacement)));
}
/**
* Expands an input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @return {!Promise<string>}
*/
expandInputValueAsync(element) {
return /** @type {!Promise<string>} */ (
this.expandInputValue_(element, /*opt_sync*/ false));
}
/**
* Expands an input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @return {string} Replaced string for testing
*/
expandInputValueSync(element) {
return /** @type {string} */ (
this.expandInputValue_(element, /*opt_sync*/ true));
}
/**
* Expands in input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @param {boolean=} opt_sync
* @return {string|!Promise<string>}
*/
expandInputValue_(element, opt_sync) {
dev().assert(element.tagName == 'INPUT' &&
(element.getAttribute('type') || '').toLowerCase() == 'hidden',
'Input value expansion only works on hidden input fields: %s', element);
const whitelist = this.getWhitelistForElement_(element);
if (!whitelist) {
return opt_sync ? element.value : Promise.resolve(element.value);
}
if (element[ORIGINAL_VALUE_PROPERTY] === undefined) {
element[ORIGINAL_VALUE_PROPERTY] = element.value;
}
const result = this.expand_(
element[ORIGINAL_VALUE_PROPERTY] || element.value,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_sync */ opt_sync,
/* opt_whitelist */ whitelist);
if (opt_sync) {
return element.value = result;
}
return result.then(newValue => {
element.value = newValue;
return newValue;
});
}
/**
* Returns a replacement whitelist from elements' data-amp-replace attribute.
* @param {!Element} element
* @param {!Object<string, boolean>=} opt_supportedReplacement Optional supported
* replacement that filters whitelist to a subset.
* @return {!Object<string, boolean>|undefined}
*/
getWhitelistForElement_(element, opt_supportedReplacement) {
const whitelist = element.getAttribute('data-amp-replace');
if (!whitelist) {
return;
}
const requestedReplacements = {};
whitelist.trim().split(/\s+/).forEach(replacement => {
if (!opt_supportedReplacement ||
hasOwn(opt_supportedReplacement, replacement)) {
requestedReplacements[replacement] = true;
} else {
user().warn('URL', 'Ignoring unsupported replacement', replacement);
}
});
return requestedReplacements;
}
/**
* Returns whether variable substitution is allowed for given url.
* @param {!Location} url
* @return {boolean}
*/
isAllowedOrigin_(url) {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
if (url.origin == parseUrlDeprecated(docInfo.canonicalUrl).origin ||
url.origin == parseUrlDeprecated(docInfo.sourceUrl).origin) {
return true;
}
const meta = this.ampdoc.getRootNode().querySelector(
'meta[name=amp-link-variable-allowed-origin]');
if (meta && meta.hasAttribute('content')) {
const whitelist = meta.getAttribute('content').trim().split(/\s+/);
for (let i = 0; i < whitelist.length; i++) {
if (url.origin == parseUrlDeprecated(whitelist[i]).origin) {
return true;
}
}
}
return false;
}
/**
* Replaces values in the link of an anchor tag if
* - the link opts into it (via data-amp-replace argument)
* - the destination is the source or canonical origin of this doc.
* @param {!Element} element An anchor element.
* @param {?string} defaultUrlParams to expand link if caller request.
* @return {string|undefined} Replaced string for testing
*/
maybeExpandLink(element, defaultUrlParams) {
dev().assert(element.tagName == 'A');
const supportedReplacements = {
'CLIENT_ID': true,
'QUERY_PARAM': true,
'PAGE_VIEW_ID': true,
'NAV_TIMING': true,
};
const additionalUrlParameters =
element.getAttribute('data-amp-addparams') || '';
const whitelist = this.getWhitelistForElement_(
element, supportedReplacements);
if (!whitelist && !additionalUrlParameters && !defaultUrlParams) {
return;
}
// ORIGINAL_HREF_PROPERTY has the value of the href "pre-replacement".
// We set this to the original value before doing any work and use it
// on subsequent replacements, so that each run gets a fresh value.
let href = dev().assertString(
element[ORIGINAL_HREF_PROPERTY] || element.getAttribute('href'));
const url = parseUrlDeprecated(href);
if (element[ORIGINAL_HREF_PROPERTY] == null) {
element[ORIGINAL_HREF_PROPERTY] = href;
}
if (additionalUrlParameters) {
href = addParamsToUrl(
href,
parseQueryString(additionalUrlParameters));
}
const isAllowedOrigin = this.isAllowedOrigin_(url);
if (!isAllowedOrigin) {
if (whitelist) {
user().warn('URL', 'Ignoring link replacement', href,
' because the link does not go to the document\'s' +
' source, canonical, or whitelisted origin.');
}
return element.href = href;
}
// Note that defaultUrlParams is treated differently than
// additionalUrlParameters in two ways #1: If the outgoing url origin is not
// whitelisted: additionalUrlParameters are always appended by not expanded,
// defaultUrlParams will not be appended. #2: If the expansion function is
// not whitelisted: additionalUrlParamters will not be expanded,
// defaultUrlParams will by default support QUERY_PARAM, and will still be
// expanded.
if (defaultUrlParams) {
if (!whitelist || !whitelist['QUERY_PARAM']) {
// override whitelist and expand defaultUrlParams;
const overrideWhitelist = {'QUERY_PARAM': true};
defaultUrlParams = this.expandUrlSync(
defaultUrlParams,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_whitelist */ overrideWhitelist);
}
href = addParamsToUrl(href, parseQueryString(defaultUrlParams));
}
if (whitelist) {
href = this.expandUrlSync(
href,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_whitelist */ whitelist);
}
return element.href = href;
}
/**
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, *>=} opt_collectVars
* @param {boolean=} opt_sync
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of names
* that can be substituted.
* @return {!Promise<string>|string}
* @private
*/
expand_(url, opt_bindings, opt_collectVars, opt_sync, opt_whiteList) {
const isV2ExperimentOn = isExperimentOn(this.ampdoc.win,
'url-replacement-v2');
if (isV2ExperimentOn) {
// TODO(ccordy) support opt_collectVars && opt_whitelist
return this.expander_./*OK*/expand(url, opt_bindings, opt_collectVars,
opt_sync, opt_whiteList);
}
// existing parsing method
const expr = this.variableSource_.getExpr(opt_bindings);
let replacementPromise;
let replacement = url.replace(expr, (match, name, opt_strargs) => {
let args = [];
if (typeof opt_strargs == 'string') {
args = opt_strargs.split(/,\s*/);
}
if (opt_whiteList && !opt_whiteList[name]) {
// Do not perform substitution and just return back the original
// match, so that the string doesn't change.
return match;
}
let binding;
if (opt_bindings && (name in opt_bindings)) {
binding = opt_bindings[name];
} else if ((binding = this.variableSource_.get(name))) {
if (opt_sync) {
binding = binding.sync;
if (!binding) {
user().error(TAG, 'ignoring async replacement key: ', name);
return '';
}
} else {
binding = binding.async || binding.sync;
}
}
let val;
try {
val = (typeof binding == 'function') ?
binding.apply(null, args) : binding;
} catch (e) {
// Report error, but do not disrupt URL replacement. This will
// interpolate as the empty string.
if (opt_sync) {
val = '';
}
rethrowAsync(e);
}
// In case the produced value is a promise, we don't actually
// replace anything here, but do it again when the promise resolves.
if (val && val.then) {
if (opt_sync) {
user().error(TAG, 'ignoring promise value for key: ', name);
return '';
}
/** @const {Promise<string>} */
const p = val.catch(err => {
// Report error, but do not disrupt URL replacement. This will
// interpolate as the empty string.
rethrowAsync(err);
}).then(v => {
replacement = replacement.replace(match,
NOENCODE_WHITELIST[match] ? v : encodeValue(v));
if (opt_collectVars) {
opt_collectVars[match] = v;
}
});
if (replacementPromise) {
replacementPromise = replacementPromise.then(() => p);
} else {
replacementPromise = p;
}
return match;
}
if (opt_collectVars) {
opt_collectVars[match] = val;
}
return NOENCODE_WHITELIST[match] ? val : encodeValue(val);
});
if (replacementPromise) {
replacementPromise = replacementPromise.then(() => replacement);
}
if (opt_sync) {
return replacement;
}
return replacementPromise || Promise.resolve(replacement);
}
/**
* Collects all substitutions in the provided URL and expands them to the
* values for known variables. Optional `opt_bindings` can be used to add
* new variables or override existing ones.
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @return {!Promise<!Object<string, *>>}
*/
collectVars(url, opt_bindings) {
const vars = Object.create(null);
return this.expand_(url, opt_bindings, vars).then(() => vars);
}
/**
* Collects substitutions in the `src` attribute of the given element
* that are _not_ whitelisted via `data-amp-replace` opt-in attribute.
* @param {!Element} element
* @return {!Array<string>}
*/
collectUnwhitelistedVarsSync(element) {
const url = element.getAttribute('src');
const vars = Object.create(null);
this.expandStringSync(url, /* opt_bindings */ undefined, vars);
const varNames = Object.keys(vars);
const whitelist = this.getWhitelistForElement_(element);
if (whitelist) {
return varNames.filter(v => !whitelist[v]);
} else {
// All vars are unwhitelisted if the element has no whitelist.
return varNames;
}
}
/**
* Ensures that the protocol of the original url matches the protocol of the
* replacement url. Returns the replacement if they do, the original if they
* do not.
* @param {string} url
* @param {string} replacement
* @return {string}
*/
ensureProtocolMatches_(url, replacement) {
const newProtocol = parseUrlDeprecated(replacement, /* opt_nocache */ true)
.protocol;
const oldProtocol = parseUrlDeprecated(url, /* opt_nocache */ true)
.protocol;
if (newProtocol != oldProtocol) {
user().error(TAG, 'Illegal replacement of the protocol: ', url);
return url;
}
user().assert(isProtocolValid(replacement),
'The replacement url has invalid protocol: %s', replacement);
return replacement;
}
/**
* @return {VariableSource}
*/
getVariableSource() {
return this.variableSource_;
}
}
/**
* Extracts client ID from a _ga cookie.
* https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id
* @param {string} gaCookie
* @return {string}
*/
export function extractClientIdFromGaCookie(gaCookie) {
return gaCookie.replace(/^(GA1|1)\.[\d-]+\./, '');
}
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
export function installUrlReplacementsServiceForDoc(ampdoc) {
registerServiceBuilderForDoc(
ampdoc,
'url-replace',
function(doc) {
return new UrlReplacements(doc, new GlobalVariableSource(doc));
});
}
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!Window} embedWin
* @param {!VariableSource} varSource
*/
export function installUrlReplacementsForEmbed(ampdoc, embedWin, varSource) {
installServiceInEmbedScope(embedWin, 'url-replace',
new UrlReplacements(ampdoc, varSource));
}
/**
* @typedef {{incomingFragment: string, outgoingFragment: string}}
*/
let ShareTrackingFragmentsDef;
|
kamtschatka/amphtml
|
src/service/url-replacements-impl.js
|
JavaScript
|
apache-2.0
| 42,445 |
package com.chinaweather.android;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.chinaweather.android.db.City;
import com.chinaweather.android.db.County;
import com.chinaweather.android.db.Province;
import com.chinaweather.android.util.HttpUtil;
import com.chinaweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省
*/
private Province selectedProvince;
/**
* 选中的市
*/
private City selectedCity;
/**
* 当前的级别
*/
private int currentLevel;
public ChooseAreaFragment() {
// Required empty public constructor
}
/**
* 先获取一些控件的实例, 然后初始化ArrayAdapter, 并将它设置为ListView中适配器。
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container,false);
titleText = (TextView) view.findViewById(R.id.title_text);
backButton = (Button) view.findViewById(R.id.back_button);
listView = (ListView)view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
/**
* 给ListView和Button设置点击事件。
* @param savedInstanceState
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* 当点击某个省的时候, 就会进入到ListView的onItemClick()方法中, 这个时候就会根据当前的级别来
* 判断是去掉用queryCityies()方法还是queryCounties()方法。
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
}else if (currentLevel == LEVEL_CITY ) {
selectedCity = cityList.get(position);
queryCounties();
}else if (currentLevel == LEVEL_COUNTY ) {
String weatherId = countyList.get(position).getWeatherId();
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
}else if (currentLevel == LEVEL_CITY ) {
queryProvinces();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省, 优先从数据库查询, 如果没有查询到则再去服务器查询。
*/
private void queryProvinces() {
titleText.setText("中国");
backButton.setVisibility(View.GONE); //隐藏返回按钮
//从本地数据库读取省级数据。
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0 ) {
dataList.clear();;
for (Province province : provinceList ) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
}else {
//发起网络请求, 读取数据。
final String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中的省的所有城市, 优先从数据库中查找, 如果没有则再到服务器上查询。
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ? " , String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
}else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内的所有县, 优先从数据库查询, 如果没有查询到再去服务器上查询。
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?" , String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList ) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
queryFromServer(address , "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据。
* @param address
* @param type
*/
private void queryFromServer(String address , final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//通过runOnUiThread()方法回到主线程处理逻辑。
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
}else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
}else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
/**
* 由于queryProvinces()方法涉及到UI操作, 因此必须在主线程中调用, 这里借助runOnUiThread()
* 方法, 就会实现从子线程到主线程。
*/
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
}else if ("city".equals(type)) {
queryCities();
}else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载中...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null ) {
progressDialog.dismiss();
}
}
}
|
weiguolong/wglRepository
|
app/src/main/java/com/chinaweather/android/ChooseAreaFragment.java
|
Java
|
apache-2.0
| 10,217 |
package org.niklas.elemental.Elemental.client.elements;
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
@JsType(
prototype = "DOMTokenList"
)
interface DOMTokenList {
@JsProperty
int getLength();
String item(int index);
boolean contains(String token);
void add(String tokens);
void remove(String tokens);
boolean toggle(String token, boolean force);
}
|
Nickel671/JsInteropGenerator
|
target/generated-sources/gwt/org/niklas/elemental/Elemental/client/elements/DOMTokenList.java
|
Java
|
apache-2.0
| 423 |
/********************************************************
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*********************************************************/
var Util = require('../util/util.js');
function Player() {
// Create an audio graph.
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
var analyser = context.createAnalyser();
//analyser.fftSize = 2048 * 2 * 2
// analyser.fftSize = (window.isMobile)? 2048 : 8192;
analyser.fftSize = (window.isMobile)?1024 : 2048;
analyser.smoothingTimeConstant = 0;
// Create a mix.
var mix = context.createGain();
// Create a bandpass filter.
var bandpass = context.createBiquadFilter();
bandpass.Q.value = 10;
bandpass.type = 'bandpass';
var filterGain = context.createGain();
filterGain.gain.value = 1;
// Connect audio processing graph
mix.connect(analyser);
analyser.connect(filterGain);
filterGain.connect(context.destination);
this.context = context;
this.mix = mix;
// this.bandpass = bandpass;
this.filterGain = filterGain;
this.analyser = analyser;
this.buffers = {};
// Connect an empty source node to the mix.
Util.loadTrackSrc(this.context, 'bin/snd/empty.mp3', function(buffer) {
var source = this.createSource_(buffer, true);
source.loop = true;
source.start(0);
}.bind(this));
}
Player.prototype.playSrc = function(src) {
// Stop all of the mic stuff.
this.filterGain.gain.value = 1;
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
if (this.buffers[src]) {
$('#loadingSound').fadeIn(100).delay(1000).fadeOut(500);
this.playHelper_(src);
return;
}
$('#loadingSound').fadeIn(100);
Util.loadTrackSrc(this.context, src, function(buffer) {
this.buffers[src] = buffer;
this.playHelper_(src);
$('#loadingSound').delay(500).fadeOut(500);
}.bind(this));
};
Player.prototype.playUserAudio = function(src) {
// Stop all of the mic stuff.
this.filterGain.gain.value = 1;
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
this.buffers['user'] = src.buffer;
this.playHelper_('user');
};
Player.prototype.playHelper_ = function(src) {
var buffer = this.buffers[src];
this.source = this.createSource_(buffer, true);
this.source.start(0);
if (!this.loop) {
this.playTimer = setTimeout(function() {
this.stop();
}.bind(this), buffer.duration * 2000);
}
};
Player.prototype.live = function() {
// The AudioContext may be in a suspended state prior to the page receiving a user
// gesture. If it is, resume it.
if (this.context.state === 'suspended') {
this.context.resume();
}
if(window.isIOS){
window.parent.postMessage('error2','*');
console.log("cant use mic on ios");
}else{
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
var self = this;
navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) {
self.onStream_(stream);
}).catch(function() {
self.onStreamError(this);
});
this.filterGain.gain.value = 0;
}
};
Player.prototype.onStream_ = function(stream) {
var input = this.context.createMediaStreamSource(stream);
input.connect(this.mix);
this.input = input;
this.stream = stream;
};
Player.prototype.onStreamError_ = function(e) {
// TODO: Error handling.
};
Player.prototype.setLoop = function(loop) {
this.loop = loop;
};
Player.prototype.createSource_ = function(buffer, loop) {
var source = this.context.createBufferSource();
source.buffer = buffer;
source.loop = loop;
source.connect(this.mix);
return source;
};
Player.prototype.setMicrophoneInput = function() {
// TODO: Implement me!
};
Player.prototype.stop = function() {
if (this.source) {
this.source.stop(0);
this.source = null;
clearTimeout(this.playTimer);
this.playTimer = null;
}
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
};
Player.prototype.getAnalyserNode = function() {
return this.analyser;
};
Player.prototype.setBandpassFrequency = function(freq) {
if (freq == null) {
console.log('Removing bandpass filter');
// Remove the effect of the bandpass filter completely, connecting the mix to the analyser directly.
this.mix.disconnect();
this.mix.connect(this.analyser);
} else {
// console.log('Setting bandpass frequency to %d Hz', freq);
// Only set the frequency if it's specified, otherwise use the old one.
this.bandpass.frequency.value = freq;
this.mix.disconnect();
this.mix.connect(this.bandpass);
// bandpass is connected to filterGain.
this.filterGain.connect(this.analyser);
}
};
Player.prototype.playTone = function(freq) {
if (!this.osc) {
this.osc = this.context.createOscillator();
this.osc.connect(this.mix);
this.osc.type = 'sine';
this.osc.start(0);
}
this.osc.frequency.value = freq;
this.filterGain.gain.value = .2;
};
Player.prototype.stopTone = function() {
this.osc.stop(0);
this.osc = null;
};
module.exports = Player;
|
googlecreativelab/chrome-music-lab
|
spectrogram/src/javascripts/UI/player.js
|
JavaScript
|
apache-2.0
| 5,514 |
/*
* 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 com.alibaba.dubbo.rpc.filter;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor;
import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor;
import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.PojoUtils;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.service.GenericException;
import com.alibaba.dubbo.rpc.support.ProtocolUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* GenericImplInvokerFilter
*/
@Activate(group = Constants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000)
public class GenericImplFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class);
private static final Class<?>[] GENERIC_PARAMETER_TYPES = new Class<?>[]{String.class, String[].class, Object[].class};
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String generic = invoker.getUrl().getParameter(Constants.GENERIC_KEY);
if (ProtocolUtils.isGeneric(generic)
&& !Constants.$INVOKE.equals(invocation.getMethodName())
&& invocation instanceof RpcInvocation) {
RpcInvocation invocation2 = (RpcInvocation) invocation;
String methodName = invocation2.getMethodName();
Class<?>[] parameterTypes = invocation2.getParameterTypes();
Object[] arguments = invocation2.getArguments();
String[] types = new String[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
types[i] = ReflectUtils.getName(parameterTypes[i]);
}
Object[] args;
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
args = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD);
}
} else {
args = PojoUtils.generalize(arguments);
}
invocation2.setMethodName(Constants.$INVOKE);
invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);
invocation2.setArguments(new Object[]{methodName, types, args});
Result result = invoker.invoke(invocation2);
if (!result.hasException()) {
Object value = result.getValue();
try {
Method method = invoker.getInterface().getMethod(methodName, parameterTypes);
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
if (value == null) {
return new RpcResult(value);
} else if (value instanceof JavaBeanDescriptor) {
return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value));
} else {
throw new RpcException(
new StringBuilder(64)
.append("The type of result value is ")
.append(value.getClass().getName())
.append(" other than ")
.append(JavaBeanDescriptor.class.getName())
.append(", and the result is ")
.append(value).toString());
}
} else {
return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType()));
}
} catch (NoSuchMethodException e) {
throw new RpcException(e.getMessage(), e);
}
} else if (result.getException() instanceof GenericException) {
GenericException exception = (GenericException) result.getException();
try {
String className = exception.getExceptionClass();
Class<?> clazz = ReflectUtils.forName(className);
Throwable targetException = null;
Throwable lastException = null;
try {
targetException = (Throwable) clazz.newInstance();
} catch (Throwable e) {
lastException = e;
for (Constructor<?> constructor : clazz.getConstructors()) {
try {
targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]);
break;
} catch (Throwable e1) {
lastException = e1;
}
}
}
if (targetException != null) {
try {
Field field = Throwable.class.getDeclaredField("detailMessage");
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(targetException, exception.getExceptionMessage());
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
result = new RpcResult(targetException);
} else if (lastException != null) {
throw lastException;
}
} catch (Throwable e) {
throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e);
}
}
return result;
}
if (invocation.getMethodName().equals(Constants.$INVOKE)
&& invocation.getArguments() != null
&& invocation.getArguments().length == 3
&& ProtocolUtils.isGeneric(generic)) {
Object[] args = (Object[]) invocation.getArguments()[2];
if (ProtocolUtils.isJavaGenericSerialization(generic)) {
for (Object arg : args) {
if (!(byte[].class == arg.getClass())) {
error(byte[].class.getName(), arg.getClass().getName());
}
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
for (Object arg : args) {
if (!(arg instanceof JavaBeanDescriptor)) {
error(JavaBeanDescriptor.class.getName(), arg.getClass().getName());
}
}
}
((RpcInvocation) invocation).setAttachment(
Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY));
}
return invoker.invoke(invocation);
}
private void error(String expected, String actual) throws RpcException {
throw new RpcException(
new StringBuilder(32)
.append("Generic serialization [")
.append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
.append("] only support message type ")
.append(expected)
.append(" and your message type is ")
.append(actual).toString());
}
}
|
dadarom/dubbo
|
dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java
|
Java
|
apache-2.0
| 9,168 |
package rpcd
import (
"github.com/Cloud-Foundations/Dominator/lib/errors"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
"github.com/Cloud-Foundations/Dominator/proto/hypervisor"
)
func (t *srpcType) ChangeAddressPool(conn *srpc.Conn,
request hypervisor.ChangeAddressPoolRequest,
reply *hypervisor.ChangeAddressPoolResponse) error {
*reply = hypervisor.ChangeAddressPoolResponse{
Error: errors.ErrorToString(t.changeAddressPool(conn, request))}
return nil
}
func (t *srpcType) changeAddressPool(conn *srpc.Conn,
request hypervisor.ChangeAddressPoolRequest) error {
if len(request.AddressesToAdd) > 0 {
err := t.manager.AddAddressesToPool(request.AddressesToAdd)
if err != nil {
return err
}
}
if len(request.AddressesToRemove) > 0 {
err := t.manager.RemoveAddressesFromPool(request.AddressesToRemove)
if err != nil {
return err
}
}
if len(request.MaximumFreeAddresses) > 0 {
err := t.manager.RemoveExcessAddressesFromPool(
request.MaximumFreeAddresses)
if err != nil {
return err
}
}
return nil
}
|
rgooch/Dominator
|
hypervisor/rpcd/changeAddressPool.go
|
GO
|
apache-2.0
| 1,050 |
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.wfu.common.utils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @author wanye
* @date Dec 14, 2008
* @version v 1.0
* @description 得到当前应用的系统路径
*/
public class SystemPath {
public static String getSysPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "").replaceFirst(
"WEB-INF/classes/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getClassPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getSystempPath() {
return System.getProperty("java.io.tmpdir");
}
public static String getSeparator() {
return System.getProperty("file.separator");
}
/**
* 获取服务器的地址
* @return
*/
public static String getServerPath(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
return basePath;
}
public static void main(String[] args) {
System.out.println(getSysPath());
System.out.println(System.getProperty("java.io.tmpdir"));
System.out.println(getSeparator());
System.out.println(getClassPath());
}
}
|
347184068/jybl
|
src/main/java/com/wfu/common/utils/SystemPath.java
|
Java
|
apache-2.0
| 1,970 |
using System;
// ReSharper disable CheckNamespace
namespace DasMulli.Win32.ServiceUtils
{
internal delegate void ServiceControlHandler(ServiceControlCommand control, uint eventType, IntPtr eventData, IntPtr eventContext);
}
|
tonyredondo/TWCore2
|
src/TWCore.Services/DasMulli.Win32.ServiceUtils/ServiceControlHandler.cs
|
C#
|
apache-2.0
| 232 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
namespace FrameworkLibrary.Classes.ControlAdapters
{
public class TreeViewAdapter : ControlAdapter
{
protected CustomTreeView Target
{
get
{
return (this.Control as CustomTreeView);
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteFullBeginTag("ul");
writer.WriteLine();
foreach (CustomTreeNode node in Target.Nodes)
{
RenderNode(node, writer);
}
writer.WriteLine();
writer.WriteEndTag("ul");
}
private void RenderNode(CustomTreeNode node, HtmlTextWriter writer)
{
writer.WriteFullBeginTag("li " + node.GetLIAttributesAsString());
writer.WriteFullBeginTag("a href=\"" + node.NavigateUrl + "\"" + node.GetLinkAttributesAsString());
writer.Write(node.Text);
writer.WriteEndTag("a");
if (node.ChildNodes.Count > 0)
{
writer.WriteFullBeginTag("ul");
foreach (CustomTreeNode childNode in node.ChildNodes)
{
RenderNode(childNode, writer);
}
writer.WriteEndTag("ul");
}
writer.WriteEndTag("li");
}
}
}
|
MacdonaldRobinson/FlexDotnetCMS
|
FrameworkLibrary/Classes/ControlAdapters/TreeViewAdapter.cs
|
C#
|
apache-2.0
| 1,555 |
package redis
import (
"encoding/json"
"errors"
"fmt"
"github.com/go-redis/redis"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/lora"
)
const (
keyType = "lora"
keyDevEUI = "dev_eui"
keyAppID = "app_id"
group = "mainflux.lora"
stream = "mainflux.things"
thingPrefix = "thing."
thingCreate = thingPrefix + "create"
thingUpdate = thingPrefix + "update"
thingRemove = thingPrefix + "remove"
channelPrefix = "channel."
channelCreate = channelPrefix + "create"
channelUpdate = channelPrefix + "update"
channelRemove = channelPrefix + "remove"
exists = "BUSYGROUP Consumer Group name already exists"
)
var (
errMetadataType = errors.New("field lora is missing in the metadata")
errMetadataFormat = errors.New("malformed metadata")
errMetadataAppID = errors.New("application ID not found in channel metadatada")
errMetadataDevEUI = errors.New("device EUI not found in thing metadatada")
)
// Subscriber represents event source for things and channels provisioning.
type Subscriber interface {
// Subscribes to geven subject and receives events.
Subscribe(string) error
}
type eventStore struct {
svc lora.Service
client *redis.Client
consumer string
logger logger.Logger
}
// NewEventStore returns new event store instance.
func NewEventStore(svc lora.Service, client *redis.Client, consumer string, log logger.Logger) Subscriber {
return eventStore{
svc: svc,
client: client,
consumer: consumer,
logger: log,
}
}
func (es eventStore) Subscribe(subject string) error {
err := es.client.XGroupCreateMkStream(stream, group, "$").Err()
if err != nil && err.Error() != exists {
return err
}
for {
streams, err := es.client.XReadGroup(&redis.XReadGroupArgs{
Group: group,
Consumer: es.consumer,
Streams: []string{stream, ">"},
Count: 100,
}).Result()
if err != nil || len(streams) == 0 {
continue
}
for _, msg := range streams[0].Messages {
event := msg.Values
var err error
switch event["operation"] {
case thingCreate:
cte, derr := decodeCreateThing(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateThing(cte)
case thingUpdate:
ute, derr := decodeCreateThing(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateThing(ute)
case thingRemove:
rte := decodeRemoveThing(event)
err = es.handleRemoveThing(rte)
case channelCreate:
cce, derr := decodeCreateChannel(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateChannel(cce)
case channelUpdate:
uce, derr := decodeCreateChannel(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateChannel(uce)
case channelRemove:
rce := decodeRemoveChannel(event)
err = es.handleRemoveChannel(rce)
}
if err != nil && err != errMetadataType {
es.logger.Warn(fmt.Sprintf("Failed to handle event sourcing: %s", err.Error()))
break
}
es.client.XAck(stream, group, msg.ID)
}
}
}
func decodeCreateThing(event map[string]interface{}) (createThingEvent, error) {
strmeta := read(event, "metadata", "{}")
var metadata map[string]interface{}
if err := json.Unmarshal([]byte(strmeta), &metadata); err != nil {
return createThingEvent{}, err
}
cte := createThingEvent{
id: read(event, "id", ""),
}
m, ok := metadata[keyType]
if !ok {
return createThingEvent{}, errMetadataType
}
lm, ok := m.(map[string]interface{})
if !ok {
return createThingEvent{}, errMetadataFormat
}
val, ok := lm[keyDevEUI].(string)
if !ok {
return createThingEvent{}, errMetadataDevEUI
}
cte.loraDevEUI = val
return cte, nil
}
func decodeRemoveThing(event map[string]interface{}) removeThingEvent {
return removeThingEvent{
id: read(event, "id", ""),
}
}
func decodeCreateChannel(event map[string]interface{}) (createChannelEvent, error) {
strmeta := read(event, "metadata", "{}")
var metadata map[string]interface{}
if err := json.Unmarshal([]byte(strmeta), &metadata); err != nil {
return createChannelEvent{}, err
}
cce := createChannelEvent{
id: read(event, "id", ""),
}
m, ok := metadata[keyType]
if !ok {
return createChannelEvent{}, errMetadataType
}
lm, ok := m.(map[string]interface{})
if !ok {
return createChannelEvent{}, errMetadataFormat
}
val, ok := lm[keyAppID].(string)
if !ok {
return createChannelEvent{}, errMetadataAppID
}
cce.loraAppID = val
return cce, nil
}
func decodeRemoveChannel(event map[string]interface{}) removeChannelEvent {
return removeChannelEvent{
id: read(event, "id", ""),
}
}
func (es eventStore) handleCreateThing(cte createThingEvent) error {
return es.svc.CreateThing(cte.id, cte.loraDevEUI)
}
func (es eventStore) handleRemoveThing(rte removeThingEvent) error {
return es.svc.RemoveThing(rte.id)
}
func (es eventStore) handleCreateChannel(cce createChannelEvent) error {
return es.svc.CreateChannel(cce.id, cce.loraAppID)
}
func (es eventStore) handleRemoveChannel(rce removeChannelEvent) error {
return es.svc.RemoveChannel(rce.id)
}
func read(event map[string]interface{}, key, def string) string {
val, ok := event[key].(string)
if !ok {
return def
}
return val
}
|
Mainflux/mainflux-lite
|
lora/redis/streams.go
|
GO
|
apache-2.0
| 5,245 |
#!/usr/bin/python
"""usage: python stylechecker.py /path/to/the/c/code"""
import os
import sys
import string
import re
WHITE = '\033[97m'
CYAN = '\033[96m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
def check_file(file):
if re.search('\.[c|h]$', file) == None:
return
f = open(file)
i = 1
file_name_printed = False
for line in f:
line = line.replace('\n', '')
# check the number of columns greater than 80
if len(line) > 80:
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (GREEN + ' [>80]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
# check the TAB key
if string.find(line, '\t') >= 0:
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (YELLOW + ' [TAB]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
# check blank lines
if line.isspace():
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (CYAN + ' [BLK]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
i = i + 1
f.close()
def walk_dir(dir):
for root, dirs, files in os.walk(dir):
for f in files:
s = root + '/' + f
check_file(s)
for d in dirs:
walk_dir(d)
walk_dir(sys.argv[1])
|
izenecloud/nginx
|
tengine/contrib/stylechecker.py
|
Python
|
apache-2.0
| 1,596 |
package com.javaasc.entity.api;
import java.util.List;
public interface JascValues {
List<String> getValues();
}
|
alonana/JavaAsc
|
entity/src/main/java/com/javaasc/entity/api/JascValues.java
|
Java
|
apache-2.0
| 119 |
package com.commit451.parcelcheck.sample.brokenModels;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
/**
* A phone model, which is missing a few parcelable calls
*/
public class Phone implements Parcelable {
private int modelNumber;
private String manufacturer;
private Date releaseDate;
public Phone() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.modelNumber);
//Comment this out, which makes the parcel test fail
//dest.writeString(this.manufacturer);
dest.writeLong(this.releaseDate != null ? this.releaseDate.getTime() : -1);
}
protected Phone(Parcel in) {
this.modelNumber = in.readInt();
this.manufacturer = in.readString();
long tmpReleaseDate = in.readLong();
this.releaseDate = tmpReleaseDate == -1 ? null : new Date(tmpReleaseDate);
}
public static final Parcelable.Creator<Phone> CREATOR = new Parcelable.Creator<Phone>() {
@Override
public Phone createFromParcel(Parcel source) {
return new Phone(source);
}
@Override
public Phone[] newArray(int size) {
return new Phone[size];
}
};
}
|
Commit451/ParcelCheck
|
app/src/main/java/com/commit451/parcelcheck/sample/brokenModels/Phone.java
|
Java
|
apache-2.0
| 1,342 |
# Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class ValidationFailed(ValueError):
"""User input was inconsistent with API restrictions."""
def __init__(self, msg, *args, **kwargs):
msg = msg.format(*args, **kwargs)
super(ValidationFailed, self).__init__(msg)
class ValidationProgrammingError(ValueError):
"""Caller did not map validations correctly."""
def __init__(self, msg, *args, **kwargs):
msg = msg.format(*args, **kwargs)
super(ValidationProgrammingError, self).__init__(msg)
|
obulpathi/cdn1
|
cdn/transport/validators/stoplight/exceptions.py
|
Python
|
apache-2.0
| 1,077 |
import {TaskQueue} from './task-queue.js';
import { Task } from './task.js';
/**
* An object that controls when tasks are executed from a queue or set of
* queues.
*/
export interface QueueScheduler<Q extends TaskQueue<T>, T extends Task<any>> {
schedule(queue: Q): void;
}
|
PolymerLabs/async-demos
|
packages/scheduler/src/lib/queue-scheduler.ts
|
TypeScript
|
apache-2.0
| 280 |
// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// These event types are shared between the Events API and used as Webhook payloads.
package github
// CommitCommentEvent is triggered when a commit comment is created.
// The Webhook event name is "commit_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent
type CommitCommentEvent struct {
Comment *RepositoryComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Action *string `json:"action,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// CreateEvent represents a created repository, branch, or tag.
// The Webhook event name is "create".
//
// Note: webhooks will not receive this event for created repositories.
// Additionally, webhooks will not receive this event for tags if more
// than three tags are pushed at once.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#createevent
type CreateEvent struct {
Ref *string `json:"ref,omitempty"`
// RefType is the object that was created. Possible values are: "repository", "branch", "tag".
RefType *string `json:"ref_type,omitempty"`
MasterBranch *string `json:"master_branch,omitempty"`
Description *string `json:"description,omitempty"`
// The following fields are only populated by Webhook events.
PusherType *string `json:"pusher_type,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// DeleteEvent represents a deleted branch or tag.
// The Webhook event name is "delete".
//
// Note: webhooks will not receive this event for tags if more than three tags
// are deleted at once.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deleteevent
type DeleteEvent struct {
Ref *string `json:"ref,omitempty"`
// RefType is the object that was deleted. Possible values are: "branch", "tag".
RefType *string `json:"ref_type,omitempty"`
// The following fields are only populated by Webhook events.
PusherType *string `json:"pusher_type,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// DeploymentEvent represents a deployment.
// The Webhook event name is "deployment".
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentevent
type DeploymentEvent struct {
Deployment *Deployment `json:"deployment,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Sender *User `json:"sender,omitempty"`
}
// DeploymentStatusEvent represents a deployment status.
// The Webhook event name is "deployment_status".
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent
type DeploymentStatusEvent struct {
Deployment *Deployment `json:"deployment,omitempty"`
DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Sender *User `json:"sender,omitempty"`
}
// ForkEvent is triggered when a user forks a repository.
// The Webhook event name is "fork".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#forkevent
type ForkEvent struct {
// Forkee is the created repository.
Forkee *Repository `json:"forkee,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// Page represents a single Wiki page.
type Page struct {
PageName *string `json:"page_name,omitempty"`
Title *string `json:"title,omitempty"`
Summary *string `json:"summary,omitempty"`
Action *string `json:"action,omitempty"`
SHA *string `json:"sha,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
}
// GollumEvent is triggered when a Wiki page is created or updated.
// The Webhook event name is "gollum".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#gollumevent
type GollumEvent struct {
Pages []*Page `json:"pages,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssueActivityEvent represents the payload delivered by Issue webhook.
//
// Deprecated: Use IssuesEvent instead.
type IssueActivityEvent struct {
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// EditChange represents the changes when an issue, pull request, or comment has
// been edited.
type EditChange struct {
Title *struct {
From *string `json:"from,omitempty"`
} `json:"title,omitempty"`
Body *struct {
From *string `json:"from,omitempty"`
} `json:"body,omitempty"`
}
// IntegrationInstallationEvent is triggered when an integration is created or deleted.
// The Webhook event name is "integration_installation".
//
// GitHub docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationevent
type IntegrationInstallationEvent struct {
// The action that was performed. Possible values for an "integration_installation"
// event are: "created", "deleted".
Action *string `json:"action,omitempty"`
Installation *Installation `json:"installation,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IntegrationInstallationRepositoriesEvent is triggered when an integration repository
// is added or removed. The Webhook event name is "integration_installation_repositories".
//
// GitHub docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationrepositoriesevent
type IntegrationInstallationRepositoriesEvent struct {
// The action that was performed. Possible values for an "integration_installation_repositories"
// event are: "added", "removed".
Action *string `json:"action,omitempty"`
Installation *Installation `json:"installation,omitempty"`
RepositoriesAdded []*Repository `json:"repositories_added,omitempty"`
RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssueCommentEvent is triggered when an issue comment is created on an issue
// or pull request.
// The Webhook event name is "issue_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent
type IssueCommentEvent struct {
// Action is the action that was performed on the comment.
// Possible values are: "created", "edited", "deleted".
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
Comment *IssueComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssuesEvent is triggered when an issue is assigned, unassigned, labeled,
// unlabeled, opened, closed, or reopened.
// The Webhook event name is "issues".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#issuesevent
type IssuesEvent struct {
// Action is the action that was performed. Possible values are: "assigned",
// "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited".
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
Assignee *User `json:"assignee,omitempty"`
Label *Label `json:"label,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// LabelEvent is triggered when a repository's label is created, edited, or deleted.
// The Webhook event name is "label"
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#labelevent
type LabelEvent struct {
// Action is the action that was performed. Possible values are:
// "created", "edited", "deleted"
Action *string `json:"action,omitempty"`
Label *Label `json:"label,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Org *Organization `json:"organization,omitempty"`
}
// MemberEvent is triggered when a user is added as a collaborator to a repository.
// The Webhook event name is "member".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#memberevent
type MemberEvent struct {
// Action is the action that was performed. Possible value is: "added".
Action *string `json:"action,omitempty"`
Member *User `json:"member,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// MembershipEvent is triggered when a user is added or removed from a team.
// The Webhook event name is "membership".
//
// Events of this type are not visible in timelines, they are only used to
// trigger organization webhooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#membershipevent
type MembershipEvent struct {
// Action is the action that was performed. Possible values are: "added", "removed".
Action *string `json:"action,omitempty"`
// Scope is the scope of the membership. Possible value is: "team".
Scope *string `json:"scope,omitempty"`
Member *User `json:"member,omitempty"`
Team *Team `json:"team,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// MilestoneEvent is triggered when a milestone is created, closed, opened, edited, or deleted.
// The Webhook event name is "milestone".
//
// Github docs: https://developer.github.com/v3/activity/events/types/#milestoneevent
type MilestoneEvent struct {
// Action is the action that was performed. Possible values are:
// "created", "closed", "opened", "edited", "deleted"
Action *string `json:"action,omitempty"`
Milestone *Milestone `json:"milestone,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
Org *Organization `json:"organization,omitempty"`
}
// OrganizationEvent is triggered when a user is added, removed, or invited to an organization.
// Events of this type are not visible in timelines. These events are only used to trigger organization hooks.
// Webhook event name is "organization".
//
// Github docs: https://developer.github.com/v3/activity/events/types/#organizationevent
type OrganizationEvent struct {
// Action is the action that was performed.
// Can be one of "member_added", "member_removed", or "member_invited".
Action *string `json:"action,omitempty"`
// Invitaion is the invitation for the user or email if the action is "member_invited".
Invitation *Invitation `json:"invitation,omitempty"`
// Membership is the membership between the user and the organization.
// Not present when the action is "member_invited".
Membership *Membership `json:"membership,omitempty"`
Organization *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PageBuildEvent represents an attempted build of a GitHub Pages site, whether
// successful or not.
// The Webhook event name is "page_build".
//
// This event is triggered on push to a GitHub Pages enabled branch (gh-pages
// for project pages, master for user and organization pages).
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent
type PageBuildEvent struct {
Build *PagesBuild `json:"build,omitempty"`
// The following fields are only populated by Webhook events.
ID *int `json:"id,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PingEvent is triggered when a Webhook is added to GitHub.
//
// GitHub docs: https://developer.github.com/webhooks/#ping-event
type PingEvent struct {
// Random string of GitHub zen.
Zen *string `json:"zen,omitempty"`
// The ID of the webhook that triggered the ping.
HookID *int `json:"hook_id,omitempty"`
// The webhook configuration.
Hook *Hook `json:"hook,omitempty"`
}
// PublicEvent is triggered when a private repository is open sourced.
// According to GitHub: "Without a doubt: the best GitHub event."
// The Webhook event name is "public".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#publicevent
type PublicEvent struct {
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PullRequestEvent is triggered when a pull request is assigned, unassigned,
// labeled, unlabeled, opened, closed, reopened, or synchronized.
// The Webhook event name is "pull_request".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent
type PullRequestEvent struct {
// Action is the action that was performed. Possible values are: "assigned",
// "unassigned", "labeled", "unlabeled", "opened", "closed", or "reopened",
// "synchronize", "edited". If the action is "closed" and the merged key is false,
// the pull request was closed with unmerged commits. If the action is "closed"
// and the merged key is true, the pull request was merged.
Action *string `json:"action,omitempty"`
Number *int `json:"number,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PullRequestReviewEvent is triggered when a review is submitted on a pull
// request.
// The Webhook event name is "pull_request_review".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent
type PullRequestReviewEvent struct {
// Action is always "submitted".
Action *string `json:"action,omitempty"`
Review *PullRequestReview `json:"review,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
// The following field is only present when the webhook is triggered on
// a repository belonging to an organization.
Organization *Organization `json:"organization,omitempty"`
}
// PullRequestReviewCommentEvent is triggered when a comment is created on a
// portion of the unified diff of a pull request.
// The Webhook event name is "pull_request_review_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
type PullRequestReviewCommentEvent struct {
// Action is the action that was performed on the comment.
// Possible values are: "created", "edited", "deleted".
Action *string `json:"action,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
Comment *PullRequestComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PushEvent represents a git push to a GitHub repository.
//
// GitHub API docs: http://developer.github.com/v3/activity/events/types/#pushevent
type PushEvent struct {
PushID *int `json:"push_id,omitempty"`
Head *string `json:"head,omitempty"`
Ref *string `json:"ref,omitempty"`
Size *int `json:"size,omitempty"`
Commits []PushEventCommit `json:"commits,omitempty"`
Repo *PushEventRepository `json:"repository,omitempty"`
Before *string `json:"before,omitempty"`
DistinctSize *int `json:"distinct_size,omitempty"`
// The following fields are only populated by Webhook events.
After *string `json:"after,omitempty"`
Created *bool `json:"created,omitempty"`
Deleted *bool `json:"deleted,omitempty"`
Forced *bool `json:"forced,omitempty"`
BaseRef *string `json:"base_ref,omitempty"`
Compare *string `json:"compare,omitempty"`
HeadCommit *PushEventCommit `json:"head_commit,omitempty"`
Pusher *User `json:"pusher,omitempty"`
Sender *User `json:"sender,omitempty"`
}
func (p PushEvent) String() string {
return Stringify(p)
}
// PushEventCommit represents a git commit in a GitHub PushEvent.
type PushEventCommit struct {
Message *string `json:"message,omitempty"`
Author *CommitAuthor `json:"author,omitempty"`
URL *string `json:"url,omitempty"`
Distinct *bool `json:"distinct,omitempty"`
// The following fields are only populated by Events API.
SHA *string `json:"sha,omitempty"`
// The following fields are only populated by Webhook events.
ID *string `json:"id,omitempty"`
TreeID *string `json:"tree_id,omitempty"`
Timestamp *Timestamp `json:"timestamp,omitempty"`
Committer *CommitAuthor `json:"committer,omitempty"`
Added []string `json:"added,omitempty"`
Removed []string `json:"removed,omitempty"`
Modified []string `json:"modified,omitempty"`
}
func (p PushEventCommit) String() string {
return Stringify(p)
}
// PushEventRepository represents the repo object in a PushEvent payload.
type PushEventRepository struct {
ID *int `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
FullName *string `json:"full_name,omitempty"`
Owner *PushEventRepoOwner `json:"owner,omitempty"`
Private *bool `json:"private,omitempty"`
Description *string `json:"description,omitempty"`
Fork *bool `json:"fork,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
PushedAt *Timestamp `json:"pushed_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Homepage *string `json:"homepage,omitempty"`
Size *int `json:"size,omitempty"`
StargazersCount *int `json:"stargazers_count,omitempty"`
WatchersCount *int `json:"watchers_count,omitempty"`
Language *string `json:"language,omitempty"`
HasIssues *bool `json:"has_issues,omitempty"`
HasDownloads *bool `json:"has_downloads,omitempty"`
HasWiki *bool `json:"has_wiki,omitempty"`
HasPages *bool `json:"has_pages,omitempty"`
ForksCount *int `json:"forks_count,omitempty"`
OpenIssuesCount *int `json:"open_issues_count,omitempty"`
DefaultBranch *string `json:"default_branch,omitempty"`
MasterBranch *string `json:"master_branch,omitempty"`
Organization *string `json:"organization,omitempty"`
// The following fields are only populated by Webhook events.
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
}
// PushEventRepoOwner is a basic representation of user/org in a PushEvent payload.
type PushEventRepoOwner struct {
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
}
// ReleaseEvent is triggered when a release is published.
// The Webhook event name is "release".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#releaseevent
type ReleaseEvent struct {
// Action is the action that was performed. Possible value is: "published".
Action *string `json:"action,omitempty"`
Release *RepositoryRelease `json:"release,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// RepositoryEvent is triggered when a repository is created.
// The Webhook event name is "repository".
//
// Events of this type are not visible in timelines, they are only used to
// trigger organization webhooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#repositoryevent
type RepositoryEvent struct {
// Action is the action that was performed. Possible values are: "created", "deleted",
// "publicized", "privatized".
Action *string `json:"action,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// StatusEvent is triggered when the status of a Git commit changes.
// The Webhook event name is "status".
//
// Events of this type are not visible in timelines, they are only used to
// trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#statusevent
type StatusEvent struct {
SHA *string `json:"sha,omitempty"`
// State is the new state. Possible values are: "pending", "success", "failure", "error".
State *string `json:"state,omitempty"`
Description *string `json:"description,omitempty"`
TargetURL *string `json:"target_url,omitempty"`
Branches []*Branch `json:"branches,omitempty"`
// The following fields are only populated by Webhook events.
ID *int `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Context *string `json:"context,omitempty"`
Commit *RepositoryCommit `json:"commit,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// TeamAddEvent is triggered when a repository is added to a team.
// The Webhook event name is "team_add".
//
// Events of this type are not visible in timelines. These events are only used
// to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#teamaddevent
type TeamAddEvent struct {
Team *Team `json:"team,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// WatchEvent is related to starring a repository, not watching. See this API
// blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/
//
// The event’s actor is the user who starred a repository, and the event’s
// repository is the repository that was starred.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#watchevent
type WatchEvent struct {
// Action is the action that was performed. Possible value is: "started".
Action *string `json:"action,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
|
pulcy/vault-monkey
|
deps/github.com/hashicorp/vault/vendor/github.com/google/go-github/github/event_types.go
|
GO
|
apache-2.0
| 24,483 |
'use strict';
//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Report', function(){
var _ = require('lodash');
var Reports = require('../../app/reports/reports-page');
var Report = require('../../app/report/report-page');
var reports = new Reports();
var report, reportName, conceptName;
it('Should create a new empty report', function(){
reports.visitPage();
reportName = 'HelloWorld' + Math.floor((Math.random() * 10) + 1);
reports.createReport(reportName);
reports.getCurrentUrl()
.then(function(url){
var id = _.last(url.split('/'));
report = new Report(id);
expect(report.searchBox.isPresent()).toBe(true);
expect(report.label.getText()).toBe(reportName);
});
});
it('Should already contain an element', function(){
report.goToTaxonomy().concepts.goToConcept('h:ReportLineItems');
var concept = report.taxonomy.getConcept('h:ReportLineItems');
expect(concept.label.getAttribute('value')).toBe(reportName);
expect(report.taxonomy.elements.count()).toBe(1);
expect(report.taxonomy.rootElements.count()).toBe(1);
});
it('Shouldn\'t create a new concept with an invalid name', function(){
conceptName = 'hello World';
report.goToTaxonomy();
var concepts = report.taxonomy.concepts;
concepts.createConcept(conceptName);
expect(concepts.errorMessage.isDisplayed()).toBe(true);
expect(concepts.errorMessage.getText()).toBe('Invalid Concept Name');
});
it('Should create a new concept (1)', function(){
conceptName = 'h:helloWorldID';
report.goToTaxonomy();
var concepts = report.taxonomy.concepts;
concepts.createConcept(conceptName);
var concept = report.goToTaxonomy().concepts.goToConcept(conceptName);
expect(concept.label.getAttribute('value')).toBe('Hello World ID');
});
it('Taxonomy Section should be active', function(){
expect(report.getActiveSection()).toBe('Taxonomy');
report.goToFacts();
report.goToTaxonomy();
expect(report.getActiveSection()).toBe('Taxonomy');
});
it('Should create a new concept (2)', function(){
conceptName = 'h:assets';
var concepts = report.taxonomy.concepts;
report.goToTaxonomy();
concepts.createConcept(conceptName);
var concept = report.goToTaxonomy().concepts.goToConcept(conceptName);
expect(concept.label.getAttribute('value')).toBe('Assets');
});
it('Creates a new element', function(){
report.goToTaxonomy().concepts.goToConcept(conceptName);
report.taxonomy.getConcept(conceptName).createElement();
expect(report.taxonomy.elements.count()).toBe(2);
expect(report.taxonomy.rootElements.count()).toBe(1);
});
it('Renames the concept label', function(){
var overview = report.goToTaxonomy().concepts.goToConcept(conceptName).overview;
expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets');
overview.changeLabel('Assets Label');
expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets Label');
});
it('Creates a us-gaap:Assets synonym', function(){
var synonyms = report.taxonomy.getConcept(conceptName).goToSynonyms();
expect(synonyms.list.count()).toBe(0);
synonyms.addSynonym('us-gaap:Assets');
synonyms.addSynonym('us-gaap:AssetsCurrent');
synonyms.addSynonym('us-gaap:AssetsCurrent');
expect(synonyms.list.count()).toBe(2);
expect(synonyms.getName(synonyms.list.first())).toBe('us-gaap:Assets');
expect(synonyms.getName(synonyms.list.last())).toBe('us-gaap:AssetsCurrent');
});
it('Should display the fact table', function() {
report.goToFacts();
expect(report.facts.lineCount()).toBeGreaterThan(0);
});
it('Should display the preview', function() {
report.goToSpreadsheet();
expect(report.spreadsheet.getCellValueByCss('.constraints .header')).toBe('Component: (Network and Table)');
});
it('Should delete report', function() {
reports.visitPage();
reports.list.count().then(function(count){
reports.deleteReport(reportName).then(function(){
expect(reports.list.count()).toBe(count - 1);
});
});
});
});
|
28msec/nolap-report-editor
|
tests/e2e/basic-scenario.js
|
JavaScript
|
apache-2.0
| 4,515 |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_io/core/kernels/video_kernels.h"
extern "C" {
#if defined(__APPLE__)
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height);
void VideoCaptureNextFunction(void* context, void* data, int64_t size);
void VideoCaptureFiniFunction(void* context);
#elif defined(_MSC_VER)
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height) {
return NULL;
}
void VideoCaptureNextFunction(void* context, void* data, int64_t size) {}
void VideoCaptureFiniFunction(void* context) {}
#else
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height) {
tensorflow::data::VideoCaptureContext* p =
new tensorflow::data::VideoCaptureContext();
if (p != nullptr) {
tensorflow::Status status = p->Init(device, bytes, width, height);
if (status.ok()) {
return p;
}
LOG(ERROR) << "unable to initialize video capture: " << status;
delete p;
}
return NULL;
}
void VideoCaptureNextFunction(void* context, void* data, int64_t size) {
tensorflow::data::VideoCaptureContext* p =
static_cast<tensorflow::data::VideoCaptureContext*>(context);
if (p != nullptr) {
tensorflow::Status status = p->Read(data, size);
if (!status.ok()) {
LOG(ERROR) << "unable to read video capture: " << status;
}
}
}
void VideoCaptureFiniFunction(void* context) {
tensorflow::data::VideoCaptureContext* p =
static_cast<tensorflow::data::VideoCaptureContext*>(context);
if (p != nullptr) {
delete p;
}
}
#endif
}
namespace tensorflow {
namespace data {
namespace {
class VideoCaptureReadableResource : public ResourceBase {
public:
VideoCaptureReadableResource(Env* env)
: env_(env), context_(nullptr, [](void* p) {
if (p != nullptr) {
VideoCaptureFiniFunction(p);
}
}) {}
~VideoCaptureReadableResource() {}
Status Init(const string& input) {
mutex_lock l(mu_);
int64_t bytes, width, height;
context_.reset(
VideoCaptureInitFunction(input.c_str(), &bytes, &width, &height));
if (context_.get() == nullptr) {
return errors::InvalidArgument("unable to open device ", input);
}
bytes_ = static_cast<int64>(bytes);
width_ = static_cast<int64>(width);
height_ = static_cast<int64>(height);
return Status::OK();
}
Status Read(
std::function<Status(const TensorShape& shape, Tensor** value_tensor)>
allocate_func) {
mutex_lock l(mu_);
Tensor* value_tensor;
TF_RETURN_IF_ERROR(allocate_func(TensorShape({1}), &value_tensor));
string buffer;
buffer.resize(bytes_);
VideoCaptureNextFunction(context_.get(), (void*)&buffer[0],
static_cast<int64_t>(bytes_));
value_tensor->flat<tstring>()(0) = buffer;
return Status::OK();
}
string DebugString() const override {
mutex_lock l(mu_);
return "VideoCaptureReadableResource";
}
protected:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
std::unique_ptr<void, void (*)(void*)> context_;
int64 bytes_;
int64 width_;
int64 height_;
};
class VideoCaptureReadableInitOp
: public ResourceOpKernel<VideoCaptureReadableResource> {
public:
explicit VideoCaptureReadableInitOp(OpKernelConstruction* context)
: ResourceOpKernel<VideoCaptureReadableResource>(context) {
env_ = context->env();
}
private:
void Compute(OpKernelContext* context) override {
ResourceOpKernel<VideoCaptureReadableResource>::Compute(context);
const Tensor* input_tensor;
OP_REQUIRES_OK(context, context->input("input", &input_tensor));
const string& input = input_tensor->scalar<tstring>()();
OP_REQUIRES_OK(context, resource_->Init(input));
}
Status CreateResource(VideoCaptureReadableResource** resource)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) override {
*resource = new VideoCaptureReadableResource(env_);
return Status::OK();
}
private:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
};
class VideoCaptureReadableReadOp : public OpKernel {
public:
explicit VideoCaptureReadableReadOp(OpKernelConstruction* context)
: OpKernel(context) {
env_ = context->env();
}
void Compute(OpKernelContext* context) override {
VideoCaptureReadableResource* resource;
OP_REQUIRES_OK(context,
GetResourceFromContext(context, "input", &resource));
core::ScopedUnref unref(resource);
OP_REQUIRES_OK(
context, resource->Read([&](const TensorShape& shape,
Tensor** value_tensor) -> Status {
TF_RETURN_IF_ERROR(context->allocate_output(0, shape, value_tensor));
return Status::OK();
}));
}
private:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
};
REGISTER_KERNEL_BUILDER(Name("IO>VideoCaptureReadableInit").Device(DEVICE_CPU),
VideoCaptureReadableInitOp);
REGISTER_KERNEL_BUILDER(Name("IO>VideoCaptureReadableRead").Device(DEVICE_CPU),
VideoCaptureReadableReadOp);
} // namespace
} // namespace data
} // namespace tensorflow
|
tensorflow/io
|
tensorflow_io/core/kernels/video_kernels.cc
|
C++
|
apache-2.0
| 5,927 |
/*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.lisp.mapping.util;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onosproject.lisp.ctl.ExtensionMappingAddressInterpreter;
import org.onosproject.lisp.msg.types.LispAfiAddress;
import org.onosproject.lisp.msg.types.LispAsAddress;
import org.onosproject.lisp.msg.types.LispDistinguishedNameAddress;
import org.onosproject.lisp.msg.types.LispIpv4Address;
import org.onosproject.lisp.msg.types.LispIpv6Address;
import org.onosproject.lisp.msg.types.LispMacAddress;
import org.onosproject.lisp.msg.types.lcaf.LispLcafAddress;
import org.onosproject.mapping.addresses.ExtensionMappingAddress;
import org.onosproject.mapping.addresses.MappingAddress;
import org.onosproject.mapping.addresses.MappingAddresses;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.onosproject.mapping.addresses.ExtensionMappingAddressType.ExtensionMappingAddressTypes.*;
/**
* Mapping address builder class.
*/
public final class MappingAddressBuilder {
private static final Logger log =
LoggerFactory.getLogger(MappingAddressBuilder.class);
private static final int IPV4_PREFIX_LENGTH = 32;
private static final int IPV6_PREFIX_LENGTH = 128;
// prevent from instantiation
private MappingAddressBuilder() {
}
/**
* Converts LispAfiAddress into abstracted mapping address.
*
* @param deviceService device service
* @param deviceId device identifier
* @param address LispAfiAddress
* @return abstracted mapping address
*/
protected static MappingAddress getAddress(DeviceService deviceService,
DeviceId deviceId,
LispAfiAddress address) {
if (address == null) {
log.warn("Address is not specified.");
return null;
}
switch (address.getAfi()) {
case IP4:
return afi2mapping(address);
case IP6:
return afi2mapping(address);
case AS:
int asNum = ((LispAsAddress) address).getASNum();
return MappingAddresses.asMappingAddress(String.valueOf(asNum));
case DISTINGUISHED_NAME:
String dn = ((LispDistinguishedNameAddress)
address).getDistinguishedName();
return MappingAddresses.dnMappingAddress(dn);
case MAC:
MacAddress macAddress = ((LispMacAddress) address).getAddress();
return MappingAddresses.ethMappingAddress(macAddress);
case LCAF:
return deviceService == null ? null :
lcaf2extension(deviceService, deviceId, (LispLcafAddress) address);
default:
log.warn("Unsupported address type {}", address.getAfi());
break;
}
return null;
}
/**
* Converts AFI address to generalized mapping address.
*
* @param afiAddress IP typed AFI address
* @return generalized mapping address
*/
private static MappingAddress afi2mapping(LispAfiAddress afiAddress) {
switch (afiAddress.getAfi()) {
case IP4:
IpAddress ipv4Address = ((LispIpv4Address) afiAddress).getAddress();
IpPrefix ipv4Prefix = IpPrefix.valueOf(ipv4Address, IPV4_PREFIX_LENGTH);
return MappingAddresses.ipv4MappingAddress(ipv4Prefix);
case IP6:
IpAddress ipv6Address = ((LispIpv6Address) afiAddress).getAddress();
IpPrefix ipv6Prefix = IpPrefix.valueOf(ipv6Address, IPV6_PREFIX_LENGTH);
return MappingAddresses.ipv6MappingAddress(ipv6Prefix);
default:
log.warn("Only support to convert IP address type");
break;
}
return null;
}
/**
* Converts LCAF address to extension mapping address.
*
* @param deviceService device service
* @param deviceId device identifier
* @param lcaf LCAF address
* @return extension mapping address
*/
private static MappingAddress lcaf2extension(DeviceService deviceService,
DeviceId deviceId,
LispLcafAddress lcaf) {
Device device = deviceService.getDevice(deviceId);
ExtensionMappingAddressInterpreter addressInterpreter;
ExtensionMappingAddress mappingAddress = null;
if (device.is(ExtensionMappingAddressInterpreter.class)) {
addressInterpreter = device.as(ExtensionMappingAddressInterpreter.class);
} else {
addressInterpreter = null;
}
switch (lcaf.getType()) {
case LIST:
if (addressInterpreter != null &&
addressInterpreter.supported(LIST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case SEGMENT:
if (addressInterpreter != null &&
addressInterpreter.supported(SEGMENT_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case AS:
if (addressInterpreter != null &&
addressInterpreter.supported(AS_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case APPLICATION_DATA:
if (addressInterpreter != null &&
addressInterpreter.supported(APPLICATION_DATA_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case GEO_COORDINATE:
if (addressInterpreter != null &&
addressInterpreter.supported(GEO_COORDINATE_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case NAT:
if (addressInterpreter != null &&
addressInterpreter.supported(NAT_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case NONCE:
if (addressInterpreter != null &&
addressInterpreter.supported(NONCE_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case MULTICAST:
if (addressInterpreter != null &&
addressInterpreter.supported(MULTICAST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case TRAFFIC_ENGINEERING:
if (addressInterpreter != null &&
addressInterpreter.supported(TRAFFIC_ENGINEERING_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case SOURCE_DEST:
if (addressInterpreter != null &&
addressInterpreter.supported(SOURCE_DEST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
default:
log.warn("Unsupported extension mapping address type {}", lcaf.getType());
break;
}
return mappingAddress != null ?
MappingAddresses.extensionMappingAddressWrapper(mappingAddress, deviceId) : null;
}
}
|
LorenzReinhart/ONOSnew
|
providers/lisp/mapping/src/main/java/org/onosproject/provider/lisp/mapping/util/MappingAddressBuilder.java
|
Java
|
apache-2.0
| 8,703 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.transport.nhttp.util;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.builder.Builder;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisBindingOperation;
import org.apache.axis2.description.AxisEndpoint;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.WSDL20DefaultValueHolder;
import org.apache.axis2.description.WSDL2Constants;
import org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher;
import org.apache.axis2.dispatchers.RequestURIBasedDispatcher;
import org.apache.axis2.dispatchers.RequestURIOperationDispatcher;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.util.URIEncoderDecoder;
import org.apache.http.Header;
import org.apache.synapse.transport.nhttp.NHttpConfiguration;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
/**
* This class provides a set of utility methods to manage the REST invocation calls
* going out from the nhttp transport in the HTTP GET method
*/
public class RESTUtil {
/**
* This method will return the URI part for the GET HTTPRequest by converting
* the SOAP infoset to the URL-encoded GET format
*
* @param messageContext - from which the SOAP infoset will be extracted to encode
* @param address - address of the actual service
* @return uri - ERI of the GET request
* @throws AxisFault - if the SOAP infoset cannot be converted in to the GET URL-encoded format
*/
public static String getURI(MessageContext messageContext, String address) throws AxisFault {
OMElement firstElement;
address = address.substring(address.indexOf("//") + 2);
address = address.substring(address.indexOf("/"));
String queryParameterSeparator = (String) messageContext
.getProperty(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR);
// In case queryParameterSeparator is null we better use the default value
if (queryParameterSeparator == null) {
queryParameterSeparator = WSDL20DefaultValueHolder
.getDefaultValue(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR);
}
firstElement = messageContext.getEnvelope().getBody().getFirstElement();
String params = "";
if (firstElement != null) {
// first element corresponds to the operation name
address = address + "/" + firstElement.getLocalName();
} else {
firstElement = messageContext.getEnvelope().getBody();
}
Iterator iter = firstElement.getChildElements();
String legalCharacters = WSDL2Constants
.LEGAL_CHARACTERS_IN_QUERY.replaceAll(queryParameterSeparator, "");
StringBuffer buff = new StringBuffer(params);
// iterate through the child elements and find the request parameters
while (iter.hasNext()) {
OMElement element = (OMElement) iter.next();
try {
buff.append(URIEncoderDecoder.quoteIllegal(element.getLocalName(),
legalCharacters)).append("=").append(URIEncoderDecoder.quoteIllegal(element.getText(),
legalCharacters)).append(queryParameterSeparator);
} catch (UnsupportedEncodingException e) {
throw new AxisFault("URI Encoding error : " + element.getLocalName()
+ "=" + element.getText(), e);
}
}
params = buff.toString();
if (params.trim().length() != 0) {
int index = address.indexOf("?");
if (index == -1) {
address = address + "?" + params.substring(0, params.length() - 1);
} else if (index == address.length() - 1) {
address = address + params.substring(0, params.length() - 1);
} else {
address = address
+ queryParameterSeparator + params.substring(0, params.length() - 1);
}
}
return address;
}
/**
* Processes the HTTP GET / DELETE request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param httpMethod The http method of the request
* @param dispatching Weather we should do service dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processGetAndDeleteRequest(MessageContext msgContext, OutputStream out,
String requestURI, Header contentTypeHeader,
String httpMethod, boolean dispatching)
throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, httpMethod, out, contentType, dispatching);
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
org.apache.axis2.transport.http.util.RESTUtil.processURLRequest(msgContext, out,
contentType);
}
/**
* Processes the HTTP GET / DELETE request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param builder The message builder to use
* @param httpMethod The http method of the request
* @param dispatching Weather we should do service dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processGetAndDeleteRequest(MessageContext msgContext, OutputStream out,
String requestURI, Header contentTypeHeader,
Builder builder, String httpMethod,
boolean dispatching)
throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, httpMethod, out, contentType, dispatching);
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
org.apache.axis2.transport.http.util.RESTUtil.processURLRequest(msgContext, out,
contentType, builder);
}
/**
* Processes the HTTP GET request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param soapAction SoapAction of the request
* @param requestURI The URL that the request came to
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processURLRequest(MessageContext msgContext, OutputStream out,
String soapAction, String requestURI) throws AxisFault {
if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) {
soapAction = soapAction.substring(1, soapAction.length() - 1);
}
msgContext.setSoapAction(soapAction);
msgContext.setTo(new EndpointReference(requestURI));
msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
msgContext.setServerSide(true);
msgContext.setDoingREST(true);
msgContext.setEnvelope(OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope());
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
AxisEngine.receive(msgContext);
}
/**
* Processes the HTTP POST request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param is The input stream of the request
* @param os The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param dispatching Weather we should do dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processPOSTRequest(MessageContext msgContext, InputStream is,
OutputStream os, String requestURI,
Header contentTypeHeader,
boolean dispatching) throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, HTTPConstants.HTTP_METHOD_POST,
os, contentType, dispatching);
org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(msgContext, is, os,
contentType);
}
/**
* Processes the HTTP POST request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param is The input stream of the request
* @param os The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param builder The message builder to use
* @param dispatching Weather we should do dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processPOSTRequest(MessageContext msgContext, InputStream is,
OutputStream os, String requestURI,
Header contentTypeHeader, Builder builder,
boolean dispatching) throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, HTTPConstants.HTTP_METHOD_POST,
os, contentType, dispatching);
org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(msgContext, is, os,
contentType, builder);
}
/**
* prepare message context prior to call axis2 RestUtils
*
* @param msgContext The MessageContext of the Request Message
* @param requestURI The URL that the request came to
* @param httpMethod The http method of the request
* @param out The output stream of the response
* @param contentType The content type of the request
* @param dispatching weather we should do dispatching
* @throws AxisFault Thrown in case a fault occurs
*/
private static void prepareMessageContext(MessageContext msgContext,
String requestURI,
String httpMethod,
OutputStream out,
String contentType,
boolean dispatching) throws AxisFault {
msgContext.setTo(new EndpointReference(requestURI));
msgContext.setProperty(HTTPConstants.HTTP_METHOD, httpMethod);
msgContext.setServerSide(true);
msgContext.setDoingREST(true);
msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
msgContext.setProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE, contentType);
// workaround to get REST working in the case of
// 1) Based on the request URI , it is possible to find a service name and operation.
// However, there is no actual service deployed in the synapse ( no i.e proxy or other)
// e.g http://localhost:8280/services/StudentService/students where there is no proxy
// service with name StudentService.This is a senario where StudentService is in an external
// server and it is needed to call it from synapse using the main sequence
// 2) request is to be injected into the main sequence .i.e. http://localhost:8280
// This method does not cause any performance issue ...
// Proper fix should be refractoring axis2 RestUtil in a proper way
if (dispatching) {
RequestURIBasedDispatcher requestDispatcher = new RequestURIBasedDispatcher();
AxisService axisService = requestDispatcher.findService(msgContext);
if (axisService == null) {
String defaultSvcName = NHttpConfiguration.getInstance().getStringProperty(
"nhttp.default.service", "__SynapseService");
axisService = msgContext.getConfigurationContext()
.getAxisConfiguration().getService(defaultSvcName);
}
msgContext.setAxisService(axisService);
}
}
public static void dispatchAndVerify(MessageContext msgContext) throws AxisFault {
RequestURIBasedDispatcher requestDispatcher = new RequestURIBasedDispatcher();
requestDispatcher.invoke(msgContext);
AxisService axisService = msgContext.getAxisService();
if (axisService != null) {
HTTPLocationBasedDispatcher httpLocationBasedDispatcher =
new HTTPLocationBasedDispatcher();
httpLocationBasedDispatcher.invoke(msgContext);
if (msgContext.getAxisOperation() == null) {
RequestURIOperationDispatcher requestURIOperationDispatcher =
new RequestURIOperationDispatcher();
requestURIOperationDispatcher.invoke(msgContext);
}
AxisOperation axisOperation;
if ((axisOperation = msgContext.getAxisOperation()) != null) {
AxisEndpoint axisEndpoint =
(AxisEndpoint) msgContext.getProperty(WSDL2Constants.ENDPOINT_LOCAL_NAME);
if (axisEndpoint != null) {
AxisBindingOperation axisBindingOperation = (AxisBindingOperation) axisEndpoint
.getBinding().getChild(axisOperation.getName());
msgContext.setProperty(Constants.AXIS_BINDING_OPERATION, axisBindingOperation);
}
msgContext.setAxisOperation(axisOperation);
}
}
}
}
|
asanka88/apache-synapse
|
modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/util/RESTUtil.java
|
Java
|
apache-2.0
| 16,005 |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.firestore.model.mutation;
import static com.google.firebase.firestore.model.Values.isDouble;
import static com.google.firebase.firestore.model.Values.isInteger;
import static com.google.firebase.firestore.util.Assert.fail;
import static com.google.firebase.firestore.util.Assert.hardAssert;
import androidx.annotation.Nullable;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.model.Values;
import com.google.firestore.v1.Value;
/**
* Implements the backend semantics for locally computed NUMERIC_ADD (increment) transforms.
* Converts all field values to longs or doubles and resolves overflows to
* Long.MAX_VALUE/Long.MIN_VALUE.
*/
public class NumericIncrementTransformOperation implements TransformOperation {
private Value operand;
public NumericIncrementTransformOperation(Value operand) {
hardAssert(
Values.isNumber(operand),
"NumericIncrementTransformOperation expects a NumberValue operand");
this.operand = operand;
}
@Override
public Value applyToLocalView(@Nullable Value previousValue, Timestamp localWriteTime) {
Value baseValue = computeBaseValue(previousValue);
// Return an integer value only if the previous value and the operand is an integer.
if (isInteger(baseValue) && isInteger(operand)) {
long sum = safeIncrement(baseValue.getIntegerValue(), operandAsLong());
return Value.newBuilder().setIntegerValue(sum).build();
} else if (isInteger(baseValue)) {
double sum = baseValue.getIntegerValue() + operandAsDouble();
return Value.newBuilder().setDoubleValue(sum).build();
} else {
hardAssert(
isDouble(baseValue),
"Expected NumberValue to be of type DoubleValue, but was ",
previousValue.getClass().getCanonicalName());
double sum = baseValue.getDoubleValue() + operandAsDouble();
return Value.newBuilder().setDoubleValue(sum).build();
}
}
@Override
public Value applyToRemoteDocument(@Nullable Value previousValue, Value transformResult) {
return transformResult;
}
public Value getOperand() {
return operand;
}
/**
* Inspects the provided value, returning the provided value if it is already a NumberValue,
* otherwise returning a coerced IntegerValue of 0.
*/
@Override
public Value computeBaseValue(@Nullable Value previousValue) {
return Values.isNumber(previousValue)
? previousValue
: Value.newBuilder().setIntegerValue(0).build();
}
/**
* Implementation of Java 8's `addExact()` that resolves positive and negative numeric overflows
* to Long.MAX_VALUE or Long.MIN_VALUE respectively (instead of throwing an ArithmeticException).
*/
private long safeIncrement(long x, long y) {
long r = x + y;
// See "Hacker's Delight" 2-12: Overflow if both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) >= 0) {
return r;
}
if (r >= 0L) {
return Long.MIN_VALUE;
} else {
return Long.MAX_VALUE;
}
}
private double operandAsDouble() {
if (isDouble(operand)) {
return operand.getDoubleValue();
} else if (isInteger(operand)) {
return operand.getIntegerValue();
} else {
throw fail(
"Expected 'operand' to be of Number type, but was "
+ operand.getClass().getCanonicalName());
}
}
private long operandAsLong() {
if (isDouble(operand)) {
return (long) operand.getDoubleValue();
} else if (isInteger(operand)) {
return operand.getIntegerValue();
} else {
throw fail(
"Expected 'operand' to be of Number type, but was "
+ operand.getClass().getCanonicalName());
}
}
}
|
firebase/firebase-android-sdk
|
firebase-firestore/src/main/java/com/google/firebase/firestore/model/mutation/NumericIncrementTransformOperation.java
|
Java
|
apache-2.0
| 4,335 |
/*
* Copyright (C) 2013,2014 Brett Wooldridge
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zaxxer.hikari.pool;
import static com.zaxxer.hikari.pool.HikariMBeanElf.registerMBeans;
import static com.zaxxer.hikari.pool.HikariMBeanElf.unregisterMBeans;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_IN_USE;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_NOT_IN_USE;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_REMOVED;
import static com.zaxxer.hikari.util.UtilityElf.createInstance;
import static com.zaxxer.hikari.util.UtilityElf.createThreadPoolExecutor;
import static com.zaxxer.hikari.util.UtilityElf.elapsedTimeMs;
import static com.zaxxer.hikari.util.UtilityElf.getTransactionIsolation;
import static com.zaxxer.hikari.util.UtilityElf.setRemoveOnCancelPolicy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.IConnectionCustomizer;
import com.zaxxer.hikari.metrics.CodaHaleMetricsTracker;
import com.zaxxer.hikari.metrics.MetricsTracker;
import com.zaxxer.hikari.metrics.MetricsTracker.MetricsContext;
import com.zaxxer.hikari.proxy.IHikariConnectionProxy;
import com.zaxxer.hikari.proxy.ProxyFactory;
import com.zaxxer.hikari.util.ConcurrentBag;
import com.zaxxer.hikari.util.IBagStateListener;
import com.zaxxer.hikari.util.DefaultThreadFactory;
import com.zaxxer.hikari.util.GlobalPoolLock;
import com.zaxxer.hikari.util.LeakTask;
import com.zaxxer.hikari.util.PoolUtilities;
/**
* This is the primary connection pool class that provides the basic
* pooling behavior for HikariCP.
*
* @author Brett Wooldridge
*/
public abstract class BaseHikariPool implements HikariPoolMBean, IBagStateListener
{
protected static final Logger LOGGER = LoggerFactory.getLogger("HikariPool");
private static final long ALIVE_BYPASS_WINDOW = Long.getLong("com.zaxxer.hikari.aliveBypassWindow", 1000L);
public final String catalog;
public final boolean isReadOnly;
public final boolean isAutoCommit;
public int transactionIsolation;
protected final PoolUtilities poolUtils;
protected final HikariConfig configuration;
protected final AtomicInteger totalConnections;
protected final ConcurrentBag<PoolBagEntry> connectionBag;
protected final ThreadPoolExecutor addConnectionExecutor;
protected final ThreadPoolExecutor closeConnectionExecutor;
protected final ScheduledThreadPoolExecutor houseKeepingExecutorService;
protected final boolean isUseJdbc4Validation;
protected final boolean isIsolateInternalQueries;
protected volatile boolean isShutdown;
protected volatile long connectionTimeout;
protected volatile boolean isPoolSuspended;
private final LeakTask leakTask;
private final DataSource dataSource;
private final MetricsTracker metricsTracker;
private final GlobalPoolLock suspendResumeLock;
private final IConnectionCustomizer connectionCustomizer;
private final AtomicReference<Throwable> lastConnectionFailure;
private final String username;
private final String password;
private final boolean isRecordMetrics;
/**
* Construct a HikariPool with the specified configuration.
*
* @param configuration a HikariConfig instance
*/
public BaseHikariPool(HikariConfig configuration)
{
this(configuration, configuration.getUsername(), configuration.getPassword());
}
/**
* Construct a HikariPool with the specified configuration. We cache lots of configuration
* items in class-local final members for speed.
*
* @param configuration a HikariConfig instance
* @param username authentication username
* @param password authentication password
*/
public BaseHikariPool(HikariConfig configuration, String username, String password)
{
this.username = username;
this.password = password;
this.configuration = configuration;
this.poolUtils = new PoolUtilities();
this.connectionBag = createConcurrentBag(this);
this.totalConnections = new AtomicInteger();
this.connectionTimeout = configuration.getConnectionTimeout();
this.lastConnectionFailure = new AtomicReference<Throwable>();
this.isReadOnly = configuration.isReadOnly();
this.isAutoCommit = configuration.isAutoCommit();
this.suspendResumeLock = configuration.isAllowPoolSuspension() ? GlobalPoolLock.SUSPEND_RESUME_LOCK : GlobalPoolLock.FAUX_LOCK;
this.catalog = configuration.getCatalog();
this.connectionCustomizer = initializeCustomizer();
this.transactionIsolation = getTransactionIsolation(configuration.getTransactionIsolation());
this.isIsolateInternalQueries = configuration.isIsolateInternalQueries();
this.isUseJdbc4Validation = configuration.getConnectionTestQuery() == null;
this.isRecordMetrics = configuration.getMetricRegistry() != null;
this.metricsTracker = (isRecordMetrics ? new CodaHaleMetricsTracker(this, (MetricRegistry) configuration.getMetricRegistry()) : new MetricsTracker(this));
this.dataSource = poolUtils.initializeDataSource(configuration.getDataSourceClassName(), configuration.getDataSource(), configuration.getDataSourceProperties(), configuration.getJdbcUrl(), username, password);
this.addConnectionExecutor = createThreadPoolExecutor(configuration.getMaximumPoolSize(), "HikariCP connection filler (pool " + configuration.getPoolName() + ")", configuration.getThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());
this.closeConnectionExecutor = createThreadPoolExecutor(4, "HikariCP connection closer (pool " + configuration.getPoolName() + ")", configuration.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
long delayPeriod = Long.getLong("com.zaxxer.hikari.housekeeping.periodMs", TimeUnit.SECONDS.toMillis(30L));
ThreadFactory threadFactory = configuration.getThreadFactory() != null ? configuration.getThreadFactory() : new DefaultThreadFactory("Hikari Housekeeping Timer (pool " + configuration.getPoolName() + ")", true);
this.houseKeepingExecutorService = new ScheduledThreadPoolExecutor(1, threadFactory, new ThreadPoolExecutor.DiscardPolicy());
this.houseKeepingExecutorService.scheduleAtFixedRate(getHouseKeeper(), delayPeriod, delayPeriod, TimeUnit.MILLISECONDS);
this.leakTask = (configuration.getLeakDetectionThreshold() == 0) ? LeakTask.NO_LEAK : new LeakTask(configuration.getLeakDetectionThreshold(), houseKeepingExecutorService);
setRemoveOnCancelPolicy(houseKeepingExecutorService);
poolUtils.setLoginTimeout(dataSource, connectionTimeout, LOGGER);
registerMBeans(configuration, this);
fillPool();
}
/**
* Get a connection from the pool, or timeout trying.
*
* @return a java.sql.Connection instance
* @throws SQLException thrown if a timeout occurs trying to obtain a connection
*/
public final Connection getConnection() throws SQLException
{
suspendResumeLock.acquire();
long timeout = connectionTimeout;
final long start = System.currentTimeMillis();
final MetricsContext metricsContext = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now - bagEntry.lastAccess > ALIVE_BYPASS_WINDOW && !isConnectionAlive(bagEntry.connection, timeout)) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
}
else {
metricsContext.setConnectionLastOpen(bagEntry, now);
return ProxyFactory.getProxyConnection((HikariPool) this, bagEntry, leakTask.start());
}
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
suspendResumeLock.release();
metricsContext.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout after %dms of waiting for a connection.", elapsedTimeMs(start)), lastConnectionFailure.getAndSet(null));
}
/**
* Release a connection back to the pool, or permanently close it if it is broken.
*
* @param bagEntry the PoolBagEntry to release back to the pool
*/
public final void releaseConnection(final PoolBagEntry bagEntry)
{
metricsTracker.recordConnectionUsage(bagEntry);
if (bagEntry.evicted) {
LOGGER.debug("Connection returned to pool {} is broken or evicted. Closing connection.", configuration.getPoolName());
closeConnection(bagEntry);
}
else {
bagEntry.lastAccess = System.currentTimeMillis();
connectionBag.requite(bagEntry);
}
}
/**
* Shutdown the pool, closing all idle connections and aborting or closing
* active connections.
*
* @throws InterruptedException thrown if the thread is interrupted during shutdown
*/
public final void shutdown() throws InterruptedException
{
if (!isShutdown) {
isShutdown = true;
LOGGER.info("HikariCP pool {} is shutting down.", configuration.getPoolName());
logPoolState("Before shutdown ");
connectionBag.close();
softEvictConnections();
houseKeepingExecutorService.shutdownNow();
addConnectionExecutor.shutdown();
addConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS);
final long start = System.currentTimeMillis();
do {
softEvictConnections();
abortActiveConnections();
}
while ((getIdleConnections() > 0 || getActiveConnections() > 0) && elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5));
closeConnectionExecutor.shutdown();
closeConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS);
logPoolState("After shutdown ");
unregisterMBeans(configuration, this);
metricsTracker.close();
}
}
/**
* Evict a connection from the pool.
*
* @param proxyConnection the connection to evict
*/
public final void evictConnection(IHikariConnectionProxy proxyConnection)
{
closeConnection(proxyConnection.getPoolBagEntry());
}
/**
* Get the wrapped DataSource.
*
* @return the wrapped DataSource
*/
public final DataSource getDataSource()
{
return dataSource;
}
/**
* Get the pool configuration object.
*
* @return the {@link HikariConfig} for this pool
*/
public final HikariConfig getConfiguration()
{
return configuration;
}
@Override
public String toString()
{
return configuration.getPoolName();
}
// ***********************************************************************
// HikariPoolMBean methods
// ***********************************************************************
/** {@inheritDoc} */
@Override
public final int getActiveConnections()
{
return connectionBag.getCount(STATE_IN_USE);
}
/** {@inheritDoc} */
@Override
public final int getIdleConnections()
{
return connectionBag.getCount(STATE_NOT_IN_USE);
}
/** {@inheritDoc} */
@Override
public final int getTotalConnections()
{
return connectionBag.size() - connectionBag.getCount(STATE_REMOVED);
}
/** {@inheritDoc} */
@Override
public final int getThreadsAwaitingConnection()
{
return connectionBag.getPendingQueue();
}
/** {@inheritDoc} */
@Override
public final void suspendPool()
{
if (!isPoolSuspended) {
suspendResumeLock.suspend();
isPoolSuspended = true;
}
}
/** {@inheritDoc} */
@Override
public final void resumePool()
{
if (isPoolSuspended) {
isPoolSuspended = false;
addBagItem(); // re-populate the pool
suspendResumeLock.resume();
}
}
// ***********************************************************************
// Protected methods
// ***********************************************************************
/**
* Create and add a single connection to the pool.
*/
protected final boolean addConnection()
{
// Speculative increment of totalConnections with expectation of success
if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize()) {
totalConnections.decrementAndGet();
return true;
}
Connection connection = null;
try {
connection = (username == null && password == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);
if (isUseJdbc4Validation && !poolUtils.isJdbc40Compliant(connection)) {
throw new SQLException("JDBC4 Connection.isValid() method not supported, connection test query must be configured");
}
final boolean timeoutEnabled = (connectionTimeout != Integer.MAX_VALUE);
final long timeoutMs = timeoutEnabled ? Math.max(250L, connectionTimeout) : 0L;
final int originalTimeout = poolUtils.setNetworkTimeout(houseKeepingExecutorService, connection, timeoutMs, timeoutEnabled);
transactionIsolation = (transactionIsolation < 0 ? connection.getTransactionIsolation() : transactionIsolation);
poolUtils.setupConnection(connection, isAutoCommit, isReadOnly, transactionIsolation, catalog);
connectionCustomizer.customize(connection);
poolUtils.executeSql(connection, configuration.getConnectionInitSql(), isAutoCommit);
poolUtils.setNetworkTimeout(houseKeepingExecutorService, connection, originalTimeout, timeoutEnabled);
connectionBag.add(new PoolBagEntry(connection, this));
lastConnectionFailure.set(null);
return true;
}
catch (Exception e) {
totalConnections.decrementAndGet(); // We failed, so undo speculative increment of totalConnections
lastConnectionFailure.set(e);
poolUtils.quietlyCloseConnection(connection);
LOGGER.debug("Connection attempt to database {} failed: {}", configuration.getPoolName(), e.getMessage(), e);
return false;
}
}
// ***********************************************************************
// Abstract methods
// ***********************************************************************
/**
* Permanently close the real (underlying) connection (eat any exception).
*
* @param connectionProxy the connection to actually close
*/
protected abstract void closeConnection(final PoolBagEntry bagEntry);
/**
* Check whether the connection is alive or not.
*
* @param connection the connection to test
* @param timeoutMs the timeout before we consider the test a failure
* @return true if the connection is alive, false if it is not alive or we timed out
*/
protected abstract boolean isConnectionAlive(final Connection connection, final long timeoutMs);
/**
* Attempt to abort() active connections on Java7+, or close() them on Java6.
*
* @throws InterruptedException
*/
protected abstract void abortActiveConnections() throws InterruptedException;
/**
* Create the JVM version-specific ConcurrentBag instance used by the pool.
*
* @param listener the IBagStateListener instance
* @return a ConcurrentBag instance
*/
protected abstract ConcurrentBag<PoolBagEntry> createConcurrentBag(IBagStateListener listener);
/**
* Create the JVM version-specific Housekeeping runnable instance used by the pool.
* @return the HouseKeeper instance
*/
protected abstract Runnable getHouseKeeper();
// ***********************************************************************
// Private methods
// ***********************************************************************
/**
* Fill the pool up to the minimum size.
*/
private void fillPool()
{
if (configuration.getMinimumIdle() > 0) {
if (configuration.isInitializationFailFast() && !addConnection()) {
throw new RuntimeException("Fail-fast during pool initialization", lastConnectionFailure.getAndSet(null));
}
addBagItem();
}
}
/**
* Construct the user's connection customizer, if specified.
*
* @return an IConnectionCustomizer instance
*/
private IConnectionCustomizer initializeCustomizer()
{
if (configuration.getConnectionCustomizerClassName() != null) {
return createInstance(configuration.getConnectionCustomizerClassName(), IConnectionCustomizer.class);
}
return configuration.getConnectionCustomizer();
}
public final void logPoolState(String... prefix)
{
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})",
(prefix.length > 0 ? prefix[0] : ""), configuration.getPoolName(),
getTotalConnections(), getActiveConnections(), getIdleConnections(), getThreadsAwaitingConnection());
}
}
}
|
bobwenx/HikariCP
|
hikaricp-common/src/main/java/com/zaxxer/hikari/pool/BaseHikariPool.java
|
Java
|
apache-2.0
| 18,562 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/domains/v1beta1/domains.proto
package com.google.cloud.domains.v1beta1;
/**
*
*
* <pre>
* Request for the `RetrieveRegisterParameters` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest}
*/
public final class RetrieveRegisterParametersRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
RetrieveRegisterParametersRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use RetrieveRegisterParametersRequest.newBuilder() to construct.
private RetrieveRegisterParametersRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RetrieveRegisterParametersRequest() {
domainName_ = "";
location_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RetrieveRegisterParametersRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private RetrieveRegisterParametersRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
domainName_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
location_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.class,
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.Builder.class);
}
public static final int DOMAIN_NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object domainName_;
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The domainName.
*/
@java.lang.Override
public java.lang.String getDomainName() {
java.lang.Object ref = domainName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
domainName_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for domainName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDomainNameBytes() {
java.lang.Object ref = domainName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
domainName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int LOCATION_FIELD_NUMBER = 2;
private volatile java.lang.Object location_;
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The location.
*/
@java.lang.Override
public java.lang.String getLocation() {
java.lang.Object ref = location_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
location_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for location.
*/
@java.lang.Override
public com.google.protobuf.ByteString getLocationBytes() {
java.lang.Object ref = location_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
location_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(domainName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, domainName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(location_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, location_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(domainName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, domainName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(location_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, location_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)) {
return super.equals(obj);
}
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest other =
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) obj;
if (!getDomainName().equals(other.getDomainName())) return false;
if (!getLocation().equals(other.getLocation())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + DOMAIN_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDomainName().hashCode();
hash = (37 * hash) + LOCATION_FIELD_NUMBER;
hash = (53 * hash) + getLocation().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `RetrieveRegisterParameters` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.class,
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.Builder.class);
}
// Construct using
// com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
domainName_ = "";
location_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstanceForType() {
return com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest build() {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest buildPartial() {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest result =
new com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest(this);
result.domainName_ = domainName_;
result.location_ = location_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) {
return mergeFrom(
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest other) {
if (other
== com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
.getDefaultInstance()) return this;
if (!other.getDomainName().isEmpty()) {
domainName_ = other.domainName_;
onChanged();
}
if (!other.getLocation().isEmpty()) {
location_ = other.location_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object domainName_ = "";
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The domainName.
*/
public java.lang.String getDomainName() {
java.lang.Object ref = domainName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
domainName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for domainName.
*/
public com.google.protobuf.ByteString getDomainNameBytes() {
java.lang.Object ref = domainName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
domainName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The domainName to set.
* @return This builder for chaining.
*/
public Builder setDomainName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
domainName_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearDomainName() {
domainName_ = getDefaultInstance().getDomainName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for domainName to set.
* @return This builder for chaining.
*/
public Builder setDomainNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
domainName_ = value;
onChanged();
return this;
}
private java.lang.Object location_ = "";
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The location.
*/
public java.lang.String getLocation() {
java.lang.Object ref = location_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
location_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for location.
*/
public com.google.protobuf.ByteString getLocationBytes() {
java.lang.Object ref = location_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
location_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The location to set.
* @return This builder for chaining.
*/
public Builder setLocation(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
location_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearLocation() {
location_ = getDefaultInstance().getLocation();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for location to set.
* @return This builder for chaining.
*/
public Builder setLocationBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
location_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
private static final com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest();
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RetrieveRegisterParametersRequest> PARSER =
new com.google.protobuf.AbstractParser<RetrieveRegisterParametersRequest>() {
@java.lang.Override
public RetrieveRegisterParametersRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new RetrieveRegisterParametersRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<RetrieveRegisterParametersRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RetrieveRegisterParametersRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/java-domains
|
proto-google-cloud-domains-v1beta1/src/main/java/com/google/cloud/domains/v1beta1/RetrieveRegisterParametersRequest.java
|
Java
|
apache-2.0
| 27,978 |
package com.sequenceiq.datalake.flow.diagnostics.event;
import static com.sequenceiq.datalake.flow.diagnostics.SdxCmDiagnosticsEvent.SDX_CM_DIAGNOSTICS_COLLECTION_FAILED_EVENT;
import java.util.Map;
import com.sequenceiq.datalake.flow.SdxFailedEvent;
public class SdxCmDiagnosticsFailedEvent extends SdxFailedEvent {
private final Map<String, Object> properties;
public SdxCmDiagnosticsFailedEvent(Long sdxId, String userId, Map<String, Object> properties, Exception exception) {
super(sdxId, userId, exception);
this.properties = properties;
}
public static SdxDiagnosticsFailedEvent from(BaseSdxCmDiagnosticsEvent event, Exception exception) {
return new SdxDiagnosticsFailedEvent(event.getResourceId(), event.getUserId(), event.getProperties(), exception);
}
@Override
public String selector() {
return SDX_CM_DIAGNOSTICS_COLLECTION_FAILED_EVENT.event();
}
}
|
hortonworks/cloudbreak
|
datalake/src/main/java/com/sequenceiq/datalake/flow/diagnostics/event/SdxCmDiagnosticsFailedEvent.java
|
Java
|
apache-2.0
| 934 |
package com.vint.iblog.web.servlet;
import com.vint.iblog.datastore.define.SequenceManagerDAO;
import com.vint.iblog.datastore.define.StaticDataDAO;
import org.apache.commons.lang3.StringUtils;
import org.vintsie.jcobweb.proxy.ServiceFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* Created by Vin on 14-2-17.
*/
public class ConfigurationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cfgType = req.getParameter("cfgType");
PrintWriter pw = resp.getWriter();
// 配置静态数据
if (StringUtils.equals(cfgType, "sd")) {
String operation = req.getParameter("operation");
// 新增配置数据
if (StringUtils.equals("add", operation)) {
String dataType = req.getParameter("dataType");
String dataValue = req.getParameter("dataValue");
String sort = req.getParameter("sort");
if (StringUtils.isEmpty(dataType) || StringUtils.isEmpty(dataValue)) {
pw.write("When creating new static data, neither dataType or dataValue can not be null.");
} else {
try {
StaticDataDAO sdd = ServiceFactory.getService(StaticDataDAO.class);
sdd.newStaticData(dataType, dataValue, Integer.parseInt(sort));
pw.write("success");
} catch (Exception e) {
pw.write(e.getMessage());
e.printStackTrace();
}
}
}
} else if (StringUtils.equals(cfgType, "seq")) {
/**
* 序列的操作分为两种,read和write.如果传入的operation是read,则只查询
* 对应Type的序列值。当传入的操作时write时,则会清理对应Type的序列数据,
* 并使用新的16进制字符串代替。
*
* Url实例:
* http://localhost:8080/cfg?cfgType=seq&operation=read&type=BLOG&hex=101c0701
* http://localhost:8080/cfg?cfgType=seq&operation=wirte&type=BLOG&hex=101c0701
*/
String type = req.getParameter("type");
String hex = req.getParameter("hex");
String operation = req.getParameter("operation");
try {
SequenceManagerDAO sequenceManagerDAO = ServiceFactory.getService(SequenceManagerDAO.class);
if (StringUtils.equals("read", operation)) {
pw.write(type + "'s current Sequence is " + sequenceManagerDAO.getCurrentSeq(type));
} else if (StringUtils.equals("write", operation)) {
sequenceManagerDAO.createSequence(type, hex);
pw.write("Success!!");
}
} catch (Exception e) {
pw.write(e.getMessage());
e.printStackTrace();
}
} else {
pw.write("No mapping operation found according to " + cfgType);
}
pw.flush();
pw.close();
}
}
|
vintsie/iblog
|
src/main/java/com/vint/iblog/web/servlet/ConfigurationServlet.java
|
Java
|
apache-2.0
| 3,565 |
package rest
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"time"
"github.com/datacratic/aws-sdk-go/aws"
)
// RFC822 returns an RFC822 formatted timestamp for AWS protocols
const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
func Build(r *aws.Request) {
if r.ParamsFilled() {
v := reflect.ValueOf(r.Params).Elem()
buildLocationElements(r, v)
buildBody(r, v)
}
}
func buildLocationElements(r *aws.Request, v reflect.Value) {
query := r.HTTPRequest.URL.Query()
for i := 0; i < v.NumField(); i++ {
m := v.Field(i)
if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
continue
}
if m.IsValid() {
field := v.Type().Field(i)
name := field.Tag.Get("locationName")
if name == "" {
name = field.Name
}
if m.Kind() == reflect.Ptr {
m = m.Elem()
}
if !m.IsValid() {
continue
}
switch field.Tag.Get("location") {
case "headers": // header maps
buildHeaderMap(r, m, field.Tag.Get("locationName"))
case "header":
buildHeader(r, m, name)
case "uri":
buildURI(r, m, name)
case "querystring":
buildQueryString(r, m, name, query)
}
}
if r.Error != nil {
return
}
}
r.HTTPRequest.URL.RawQuery = query.Encode()
updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
}
func buildBody(r *aws.Request, v reflect.Value) {
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" {
pfield, _ := v.Type().FieldByName(payloadName)
if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
payload := reflect.Indirect(v.FieldByName(payloadName))
if payload.IsValid() && payload.Interface() != nil {
switch reader := payload.Interface().(type) {
case io.ReadSeeker:
r.SetReaderBody(reader)
case []byte:
r.SetBufferBody(reader)
case string:
r.SetBufferBody([]byte(reader))
default:
r.Error = fmt.Errorf("unknown payload type %s", payload.Type())
}
}
}
}
}
}
func buildHeader(r *aws.Request, v reflect.Value, name string) {
str, err := convertType(v)
if err != nil {
r.Error = err
} else if str != nil {
r.HTTPRequest.Header.Add(name, *str)
}
}
func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) {
for _, key := range v.MapKeys() {
str, err := convertType(v.MapIndex(key))
if err != nil {
r.Error = err
} else if str != nil {
r.HTTPRequest.Header.Add(prefix+key.String(), *str)
}
}
}
func buildURI(r *aws.Request, v reflect.Value, name string) {
value, err := convertType(v)
if err != nil {
r.Error = err
} else if value != nil {
uri := r.HTTPRequest.URL.Path
uri = strings.Replace(uri, "{"+name+"}", escapePath(*value, true), -1)
uri = strings.Replace(uri, "{"+name+"+}", escapePath(*value, false), -1)
r.HTTPRequest.URL.Path = uri
}
}
func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) {
str, err := convertType(v)
if err != nil {
r.Error = err
} else if str != nil {
query.Set(name, *str)
}
}
func updatePath(url *url.URL, urlPath string) {
scheme, query := url.Scheme, url.RawQuery
// clean up path
urlPath = path.Clean(urlPath)
// get formatted URL minus scheme so we can build this into Opaque
url.Scheme, url.Path, url.RawQuery = "", "", ""
s := url.String()
url.Scheme = scheme
url.RawQuery = query
// build opaque URI
url.Opaque = s + urlPath
}
// Whether the byte value can be sent without escaping in AWS URLs
var noEscape [256]bool
var noEscapeInitialized = false
// initialise noEscape
func initNoEscape() {
for i := range noEscape {
// Amazon expects every character except these escaped
noEscape[i] = (i >= 'A' && i <= 'Z') ||
(i >= 'a' && i <= 'z') ||
(i >= '0' && i <= '9') ||
i == '-' ||
i == '.' ||
i == '_' ||
i == '~'
}
}
// escapePath escapes part of a URL path in Amazon style
func escapePath(path string, encodeSep bool) string {
if !noEscapeInitialized {
initNoEscape()
noEscapeInitialized = true
}
var buf bytes.Buffer
for i := 0; i < len(path); i++ {
c := path[i]
if noEscape[c] || (c == '/' && !encodeSep) {
buf.WriteByte(c)
} else {
buf.WriteByte('%')
buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16)))
}
}
return buf.String()
}
func convertType(v reflect.Value) (*string, error) {
v = reflect.Indirect(v)
if !v.IsValid() {
return nil, nil
}
var str string
switch value := v.Interface().(type) {
case string:
str = value
case []byte:
str = base64.StdEncoding.EncodeToString(value)
case bool:
str = strconv.FormatBool(value)
case int64:
str = strconv.FormatInt(value, 10)
case float64:
str = strconv.FormatFloat(value, 'f', -1, 64)
case time.Time:
str = value.UTC().Format(RFC822)
default:
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
return nil, err
}
return &str, nil
}
|
datacratic/aws-sdk-go
|
internal/protocol/rest/build.go
|
GO
|
apache-2.0
| 4,968 |
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE\-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openengsb.drools;
import org.openengsb.drools.model.Notification;
public interface NotificationDomain extends Domain {
void notify(Notification notification);
}
|
tobster/openengsb
|
core/workflow/domains/src/main/java/org/openengsb/drools/NotificationDomain.java
|
Java
|
apache-2.0
| 784 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.txn.compactor;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.ServerUtils;
import org.apache.hadoop.hive.common.ValidCompactorWriteIdList;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.common.ValidWriteIdList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.TransactionalValidationListener;
import org.apache.hadoop.hive.metastore.api.AbortTxnRequest;
import org.apache.hadoop.hive.metastore.api.AllocateTableWriteIdsRequest;
import org.apache.hadoop.hive.metastore.api.AllocateTableWriteIdsResponse;
import org.apache.hadoop.hive.metastore.api.CommitTxnRequest;
import org.apache.hadoop.hive.metastore.api.CompactionRequest;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.GetValidWriteIdsRequest;
import org.apache.hadoop.hive.metastore.api.LockRequest;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchTxnException;
import org.apache.hadoop.hive.metastore.api.OpenTxnRequest;
import org.apache.hadoop.hive.metastore.api.OpenTxnsResponse;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.TxnAbortedException;
import org.apache.hadoop.hive.metastore.api.TxnType;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.metrics.AcidMetricService;
import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
import org.apache.hadoop.hive.metastore.txn.TxnCommonUtils;
import org.apache.hadoop.hive.metastore.utils.TestTxnDbUtil;
import org.apache.hadoop.hive.metastore.txn.TxnStore;
import org.apache.hadoop.hive.metastore.txn.TxnUtils;
import org.apache.hadoop.hive.ql.io.AcidInputFormat;
import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.RecordIdentifier;
import org.apache.hadoop.hive.ql.io.RecordUpdater;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
import org.apache.thrift.TException;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.hadoop.hive.ql.txn.compactor.CompactorTestUtilities.CompactorThreadType;
/**
* Super class for all of the compactor test modules.
*/
public abstract class CompactorTest {
static final private String CLASS_NAME = CompactorTest.class.getName();
static final private Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
public static final String WORKER_VERSION = "4.0.0";
protected TxnStore txnHandler;
protected IMetaStoreClient ms;
protected HiveConf conf;
private final AtomicBoolean stop = new AtomicBoolean();
protected File tmpdir;
@Before
public void setup() throws Exception {
conf = new HiveConf();
TestTxnDbUtil.setConfValues(conf);
TestTxnDbUtil.cleanDb(conf);
TestTxnDbUtil.prepDb(conf);
ms = new HiveMetaStoreClient(conf);
txnHandler = TxnUtils.getTxnStore(conf);
tmpdir = new File(Files.createTempDirectory("compactor_test_table_").toString());
}
protected void compactorTestCleanup() throws IOException {
FileUtils.deleteDirectory(tmpdir);
}
protected void startInitiator() throws Exception {
startThread(CompactorThreadType.INITIATOR, true);
}
protected void startWorker() throws Exception {
startThread(CompactorThreadType.WORKER, true);
}
protected void startCleaner() throws Exception {
startThread(CompactorThreadType.CLEANER, true);
}
protected void runAcidMetricService() throws Exception {
TestTxnDbUtil.setConfValues(conf);
AcidMetricService t = new AcidMetricService();
t.setConf(conf);
t.run();
}
protected Table newTable(String dbName, String tableName, boolean partitioned) throws TException {
return newTable(dbName, tableName, partitioned, new HashMap<String, String>(), null, false);
}
protected Table newTable(String dbName, String tableName, boolean partitioned,
Map<String, String> parameters) throws TException {
return newTable(dbName, tableName, partitioned, parameters, null, false);
}
protected Table newTable(String dbName, String tableName, boolean partitioned,
Map<String, String> parameters, List<Order> sortCols,
boolean isTemporary)
throws TException {
Table table = new Table();
table.setTableType(TableType.MANAGED_TABLE.name());
table.setTableName(tableName);
table.setDbName(dbName);
table.setOwner("me");
table.setSd(newStorageDescriptor(getLocation(tableName, null), sortCols));
List<FieldSchema> partKeys = new ArrayList<FieldSchema>(1);
if (partitioned) {
partKeys.add(new FieldSchema("ds", "string", "no comment"));
table.setPartitionKeys(partKeys);
}
// Set the table as transactional for compaction to work
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL, "true");
if (sortCols != null) {
// Sort columns are not allowed for full ACID table. So, change it to insert-only table
parameters.put(hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES,
TransactionalValidationListener.INSERTONLY_TRANSACTIONAL_PROPERTY);
}
table.setParameters(parameters);
if (isTemporary) table.setTemporary(true);
// drop the table first, in case some previous test created it
ms.dropTable(dbName, tableName);
ms.createTable(table);
return table;
}
protected Partition newPartition(Table t, String value) throws Exception {
return newPartition(t, value, null);
}
protected Partition newPartition(Table t, String value, List<Order> sortCols) throws Exception {
Partition part = new Partition();
part.addToValues(value);
part.setDbName(t.getDbName());
part.setTableName(t.getTableName());
part.setSd(newStorageDescriptor(getLocation(t.getTableName(), value), sortCols));
part.setParameters(new HashMap<String, String>());
ms.add_partition(part);
return part;
}
protected long openTxn() throws MetaException {
return openTxn(TxnType.DEFAULT);
}
protected long openTxn(TxnType txnType) throws MetaException {
OpenTxnRequest rqst = new OpenTxnRequest(1, System.getProperty("user.name"), ServerUtils.hostname());
rqst.setTxn_type(txnType);
if (txnType == TxnType.REPL_CREATED) {
rqst.setReplPolicy("default.*");
rqst.setReplSrcTxnIds(Arrays.asList(1L));
}
List<Long> txns = txnHandler.openTxns(rqst).getTxn_ids();
return txns.get(0);
}
protected long allocateWriteId(String dbName, String tblName, long txnid)
throws MetaException, TxnAbortedException, NoSuchTxnException {
AllocateTableWriteIdsRequest awiRqst
= new AllocateTableWriteIdsRequest(dbName, tblName);
awiRqst.setTxnIds(Collections.singletonList(txnid));
AllocateTableWriteIdsResponse awiResp = txnHandler.allocateTableWriteIds(awiRqst);
return awiResp.getTxnToWriteIds().get(0).getWriteId();
}
protected void addDeltaFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords)
throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.DELTA, 2, true);
}
protected void addLengthFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords)
throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.LENGTH_FILE, 2, true);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, 2, true);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords, long visibilityId) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, 2, true, visibilityId);
}
protected void addLegacyFile(Table t, Partition p, int numRecords) throws Exception {
addFile(t, p, 0, 0, numRecords, FileType.LEGACY, 2, true);
}
protected void addDeltaFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords,
int numBuckets, boolean allBucketsPresent) throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.DELTA, numBuckets, allBucketsPresent);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords, int numBuckets,
boolean allBucketsPresent) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, numBuckets, allBucketsPresent);
}
protected List<Path> getDirectories(HiveConf conf, Table t, Partition p) throws Exception {
String partValue = (p == null) ? null : p.getValues().get(0);
String location = getLocation(t.getTableName(), partValue);
Path dir = new Path(location);
FileSystem fs = FileSystem.get(conf);
FileStatus[] stats = fs.listStatus(dir);
List<Path> paths = new ArrayList<Path>(stats.length);
for (int i = 0; i < stats.length; i++) paths.add(stats[i].getPath());
return paths;
}
protected void burnThroughTransactions(String dbName, String tblName, int num)
throws MetaException, NoSuchTxnException, TxnAbortedException {
burnThroughTransactions(dbName, tblName, num, null, null);
}
protected void burnThroughTransactions(String dbName, String tblName, int num, Set<Long> open, Set<Long> aborted)
throws NoSuchTxnException, TxnAbortedException, MetaException {
burnThroughTransactions(dbName, tblName, num, open, aborted, null);
}
protected void burnThroughTransactions(String dbName, String tblName, int num, Set<Long> open, Set<Long> aborted, LockRequest lockReq)
throws MetaException, NoSuchTxnException, TxnAbortedException {
OpenTxnsResponse rsp = txnHandler.openTxns(new OpenTxnRequest(num, "me", "localhost"));
AllocateTableWriteIdsRequest awiRqst = new AllocateTableWriteIdsRequest(dbName, tblName);
awiRqst.setTxnIds(rsp.getTxn_ids());
AllocateTableWriteIdsResponse awiResp = txnHandler.allocateTableWriteIds(awiRqst);
int i = 0;
for (long tid : rsp.getTxn_ids()) {
assert(awiResp.getTxnToWriteIds().get(i++).getTxnId() == tid);
if(lockReq != null) {
lockReq.setTxnid(tid);
txnHandler.lock(lockReq);
}
if (aborted != null && aborted.contains(tid)) {
txnHandler.abortTxn(new AbortTxnRequest(tid));
} else if (open == null || (open != null && !open.contains(tid))) {
txnHandler.commitTxn(new CommitTxnRequest(tid));
}
}
}
protected void stopThread() {
stop.set(true);
}
private StorageDescriptor newStorageDescriptor(String location, List<Order> sortCols) {
StorageDescriptor sd = new StorageDescriptor();
List<FieldSchema> cols = new ArrayList<FieldSchema>(2);
cols.add(new FieldSchema("a", "varchar(25)", "still no comment"));
cols.add(new FieldSchema("b", "int", "comment"));
sd.setCols(cols);
sd.setLocation(location);
sd.setInputFormat(MockInputFormat.class.getName());
sd.setOutputFormat(MockOutputFormat.class.getName());
sd.setNumBuckets(1);
SerDeInfo serde = new SerDeInfo();
serde.setSerializationLib(LazySimpleSerDe.class.getName());
sd.setSerdeInfo(serde);
List<String> bucketCols = new ArrayList<String>(1);
bucketCols.add("a");
sd.setBucketCols(bucketCols);
if (sortCols != null) {
sd.setSortCols(sortCols);
}
return sd;
}
// I can't do this with @Before because I want to be able to control when the thread starts
private void startThread(CompactorThreadType type, boolean stopAfterOne) throws Exception {
TestTxnDbUtil.setConfValues(conf);
CompactorThread t;
switch (type) {
case INITIATOR: t = new Initiator(); break;
case WORKER: t = new Worker(); break;
case CLEANER: t = new Cleaner(); break;
default: throw new RuntimeException("Huh? Unknown thread type.");
}
t.setThreadId((int) t.getId());
t.setConf(conf);
stop.set(stopAfterOne);
t.init(stop);
if (stopAfterOne) t.run();
else t.start();
}
private String getLocation(String tableName, String partValue) {
String location = tmpdir.getAbsolutePath() +
System.getProperty("file.separator") + tableName;
if (partValue != null) {
location += System.getProperty("file.separator") + "ds=" + partValue;
}
return location;
}
private enum FileType {BASE, DELTA, LEGACY, LENGTH_FILE}
private void addFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords, FileType type, int numBuckets,
boolean allBucketsPresent) throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, type, numBuckets, allBucketsPresent, 0);
}
private void addFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords, FileType type, int numBuckets,
boolean allBucketsPresent, long visibilityId) throws Exception {
String partValue = (p == null) ? null : p.getValues().get(0);
Path location = new Path(getLocation(t.getTableName(), partValue));
String filename = null;
switch (type) {
case BASE: filename = AcidUtils.BASE_PREFIX + maxTxn + (visibilityId > 0 ? AcidUtils.VISIBILITY_PREFIX + visibilityId : ""); break;
case LENGTH_FILE: // Fall through to delta
case DELTA: filename = makeDeltaDirName(minTxn, maxTxn); break;
case LEGACY: break; // handled below
}
FileSystem fs = FileSystem.get(conf);
for (int bucket = 0; bucket < numBuckets; bucket++) {
if (bucket == 0 && !allBucketsPresent) continue; // skip one
Path partFile = null;
if (type == FileType.LEGACY) {
partFile = new Path(location, String.format(AcidUtils.LEGACY_FILE_BUCKET_DIGITS, bucket) + "_0");
} else {
Path dir = new Path(location, filename);
fs.mkdirs(dir);
partFile = AcidUtils.createBucketFile(dir, bucket);
if (type == FileType.LENGTH_FILE) {
partFile = new Path(partFile.toString() + AcidUtils.DELTA_SIDE_FILE_SUFFIX);
}
}
FSDataOutputStream out = fs.create(partFile);
if (type == FileType.LENGTH_FILE) {
out.writeInt(numRecords);//hmm - length files should store length in bytes...
} else {
for (int i = 0; i < numRecords; i++) {
RecordIdentifier ri = new RecordIdentifier(maxTxn - 1, bucket, i);
ri.write(out);
out.writeBytes("mary had a little lamb its fleece was white as snow\n");
}
}
out.close();
}
}
static class MockInputFormat implements AcidInputFormat<WritableComparable,Text> {
@Override
public AcidInputFormat.RowReader<Text> getReader(InputSplit split,
Options options) throws
IOException {
return null;
}
@Override
public RawReader<Text> getRawReader(Configuration conf, boolean collapseEvents, int bucket,
ValidWriteIdList validWriteIdList,
Path baseDirectory, Path[] deltaDirectory, Map<String, Integer> deltaToAttemptId) throws IOException {
List<Path> filesToRead = new ArrayList<Path>();
if (baseDirectory != null) {
if (baseDirectory.getName().startsWith(AcidUtils.BASE_PREFIX)) {
Path p = AcidUtils.createBucketFile(baseDirectory, bucket);
FileSystem fs = p.getFileSystem(conf);
if (fs.exists(p)) filesToRead.add(p);
} else {
filesToRead.add(new Path(baseDirectory, "000000_0"));
}
}
for (int i = 0; i < deltaDirectory.length; i++) {
Path p = AcidUtils.createBucketFile(deltaDirectory[i], bucket);
FileSystem fs = p.getFileSystem(conf);
if (fs.exists(p)) filesToRead.add(p);
}
return new MockRawReader(conf, filesToRead);
}
@Override
public InputSplit[] getSplits(JobConf entries, int i) throws IOException {
return new InputSplit[0];
}
@Override
public RecordReader<WritableComparable, Text> getRecordReader(InputSplit inputSplit, JobConf entries,
Reporter reporter) throws IOException {
return null;
}
@Override
public boolean validateInput(FileSystem fs, HiveConf conf, List<FileStatus> files) throws
IOException {
return false;
}
}
static class MockRawReader implements AcidInputFormat.RawReader<Text> {
private final Stack<Path> filesToRead;
private final Configuration conf;
private FSDataInputStream is = null;
private final FileSystem fs;
private boolean lastWasDelete = true;
MockRawReader(Configuration conf, List<Path> files) throws IOException {
filesToRead = new Stack<Path>();
for (Path file : files) filesToRead.push(file);
this.conf = conf;
fs = FileSystem.get(conf);
}
@Override
public ObjectInspector getObjectInspector() {
return null;
}
/**
* This is bogus especially with split update acid tables. This causes compaction to create
* delete_delta_x_y where none existed before. Makes the data layout such as would never be
* created by 'real' code path.
*/
@Override
public boolean isDelete(Text value) {
// Alternate between returning deleted and not. This is easier than actually
// tracking operations. We test that this is getting properly called by checking that only
// half the records show up in base files after major compactions.
lastWasDelete = !lastWasDelete;
return lastWasDelete;
}
@Override
public boolean next(RecordIdentifier identifier, Text text) throws IOException {
if (is == null) {
// Open the next file
if (filesToRead.empty()) return false;
Path p = filesToRead.pop();
LOG.debug("Reading records from " + p.toString());
is = fs.open(p);
}
String line = null;
try {
identifier.readFields(is);
line = is.readLine();
} catch (EOFException e) {
}
if (line == null) {
// Set our current entry to null (since it's done) and try again.
is = null;
return next(identifier, text);
}
text.set(line);
return true;
}
@Override
public RecordIdentifier createKey() {
return new RecordIdentifier();
}
@Override
public Text createValue() {
return new Text();
}
@Override
public long getPos() throws IOException {
return 0;
}
@Override
public void close() throws IOException {
}
@Override
public float getProgress() throws IOException {
return 0;
}
}
// This class isn't used and I suspect does totally the wrong thing. It's only here so that I
// can provide some output format to the tables and partitions I create. I actually write to
// those tables directory.
static class MockOutputFormat implements AcidOutputFormat<WritableComparable, Text> {
@Override
public RecordUpdater getRecordUpdater(Path path, Options options) throws
IOException {
return null;
}
@Override
public org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter getRawRecordWriter(Path path, Options options) throws IOException {
return new MockRecordWriter(path, options);
}
@Override
public org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter getHiveRecordWriter(JobConf jc, Path finalOutPath,
Class<? extends Writable> valueClass,
boolean isCompressed, Properties tableProperties,
Progressable progress) throws IOException {
return null;
}
@Override
public RecordWriter<WritableComparable, Text> getRecordWriter(FileSystem fileSystem, JobConf entries,
String s,
Progressable progressable) throws
IOException {
return null;
}
@Override
public void checkOutputSpecs(FileSystem fileSystem, JobConf entries) throws IOException {
}
}
// This class isn't used and I suspect does totally the wrong thing. It's only here so that I
// can provide some output format to the tables and partitions I create. I actually write to
// those tables directory.
static class MockRecordWriter implements org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter {
private final FSDataOutputStream os;
MockRecordWriter(Path basedir, AcidOutputFormat.Options options) throws IOException {
FileSystem fs = FileSystem.get(options.getConfiguration());
Path p = AcidUtils.createFilename(basedir, options);
os = fs.create(p);
}
@Override
public void write(Writable w) throws IOException {
Text t = (Text)w;
os.writeBytes(t.toString());
os.writeBytes("\n");
}
@Override
public void close(boolean abort) throws IOException {
os.close();
}
}
/**
* in Hive 1.3.0 delta file names changed to delta_xxxx_yyyy_zzzz; prior to that
* the name was delta_xxxx_yyyy. We want to run compaction tests such that both formats
* are used since new (1.3) code has to be able to read old files.
*/
abstract boolean useHive130DeltaDirName();
String makeDeltaDirName(long minTxnId, long maxTxnId) {
if(minTxnId != maxTxnId) {
//covers both streaming api and post compaction style.
return makeDeltaDirNameCompacted(minTxnId, maxTxnId);
}
return useHive130DeltaDirName() ?
AcidUtils.deltaSubdir(minTxnId, maxTxnId, 0) : AcidUtils.deltaSubdir(minTxnId, maxTxnId);
}
/**
* delta dir name after compaction
*/
String makeDeltaDirNameCompacted(long minTxnId, long maxTxnId) {
return AcidUtils.deltaSubdir(minTxnId, maxTxnId);
}
String makeDeleteDeltaDirNameCompacted(long minTxnId, long maxTxnId) {
return AcidUtils.deleteDeltaSubdir(minTxnId, maxTxnId);
}
protected long compactInTxn(CompactionRequest rqst) throws Exception {
txnHandler.compact(rqst);
CompactionInfo ci = txnHandler.findNextToCompact("fred", WORKER_VERSION);
ci.runAs = System.getProperty("user.name");
long compactorTxnId = openTxn(TxnType.COMPACTION);
// Need to create a valid writeIdList to set the highestWriteId in ci
ValidTxnList validTxnList = TxnCommonUtils.createValidReadTxnList(txnHandler.getOpenTxns(), compactorTxnId);
GetValidWriteIdsRequest writeIdsRequest = new GetValidWriteIdsRequest();
writeIdsRequest.setValidTxnList(validTxnList.writeToString());
writeIdsRequest
.setFullTableNames(Collections.singletonList(TxnUtils.getFullTableName(rqst.getDbname(), rqst.getTablename())));
// with this ValidWriteIdList is capped at whatever HWM validTxnList has
ValidCompactorWriteIdList tblValidWriteIds = TxnUtils
.createValidCompactWriteIdList(txnHandler.getValidWriteIds(writeIdsRequest).getTblValidWriteIds().get(0));
ci.highestWriteId = tblValidWriteIds.getHighWatermark();
txnHandler.updateCompactorState(ci, compactorTxnId);
txnHandler.markCompacted(ci);
txnHandler.commitTxn(new CommitTxnRequest(compactorTxnId));
Thread.sleep(MetastoreConf.getTimeVar(conf, MetastoreConf.ConfVars.TXN_OPENTXN_TIMEOUT, TimeUnit.MILLISECONDS));
return compactorTxnId;
}
}
|
jcamachor/hive
|
ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/CompactorTest.java
|
Java
|
apache-2.0
| 26,009 |
'use strict';
var app = angular.module('app', [
'ngAnimate',
'ngCookies',
'ui.router',
'ui.bootstrap'
]);
app.config(['$stateProvider', '$httpProvider',
function ($stateProvider, $httpProvider) {
$stateProvider.state('home', {
url: '',
templateUrl: 'App/partials/home.html',
controller: 'HomeCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('play', {
url: '/play',
templateUrl: 'App/partials/play.html',
controller: 'PlayCtrl',
data: {
requireLogin: true
}
});
$stateProvider.state('match', {
url: '/match',
templateUrl: 'App/partials/match.html',
controller: 'MatchCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('team', {
url: '/team',
templateUrl: 'App/partials/team.html',
controller: 'TeamCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('player', {
url: '/player',
templateUrl: 'App/partials/player.html',
controller: 'PlayerCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('about', {
url: '/about',
templateUrl: 'App/partials/about.html',
data: {
requireLogin: false
}
});
$stateProvider.state('preferences', {
url: '/preferences',
templateUrl: 'App/partials/preferences.html',
controller: 'PreferencesCtrl',
data: {
requireLogin: true
}
});
$httpProvider.interceptors.push(function ($timeout, $q, $injector) {
var authModal, $http, $state;
// this trick must be done so that we don't receive
// `Uncaught Error: [$injector:cdep] Circular dependency found`
$timeout(function () {
authModal = $injector.get('authModal');
$http = $injector.get('$http');
$state = $injector.get('$state');
});
return {
responseError: function (rejection) {
return rejection;//may want to force modal on 401 auth failure, but not at this time
if (rejection.status !== 401) {
return rejection;
}
var deferred = $q.defer();
authModal()
.then(function () {
deferred.resolve($http(rejection.config));
})
.catch(function () {
$state.go('home');
deferred.reject(rejection);
});
return deferred.promise;
}
};
});
}
]);
app.run(['$rootScope', '$state', 'authModal', 'authService', 'versionService',
function ($rootScope, $state, authModal, authService, versionService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
versionService.getVersionInfo(
function (version) {
if (version.isOutOfDate) {
$rootScope.$broadcast('alert', { type: 'warning', msg: 'Client version is out of date. Please refresh your browser.' });
}
},
function () {
$rootScope.$broadcast({ type: 'danger', msg: 'Server could not be reached. Please try again later.' });
});
if (toState.data.requireLogin && !authService.user.isAuthenticated) {
event.preventDefault();
authModal()
.then(function(data) {
return $state.go(toState.name, toParams);
})
.catch(function() {
return $state.go('home');
});
}
});
}]);
|
trentdm/Foos
|
src/Foos/App/app.js
|
JavaScript
|
apache-2.0
| 4,265 |
/*
* Copyright 2019 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.binder.jetty;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.component.LifeCycle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JettyConnectionMetricsTest {
private SimpleMeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
private Server server = new Server(0);
private ServerConnector connector = new ServerConnector(server);
private CloseableHttpClient client = HttpClients.createDefault();
void setup() throws Exception {
connector.addBean(new JettyConnectionMetrics(registry));
server.setConnectors(new Connector[]{connector});
server.start();
}
@AfterEach
void teardown() throws Exception {
if (server.isRunning()) {
server.stop();
}
}
@Test
void contributesServerConnectorMetrics() throws Exception {
setup();
HttpPost post = new HttpPost("http://localhost:" + connector.getLocalPort());
post.setEntity(new StringEntity("123456"));
try (CloseableHttpResponse ignored = client.execute(post)) {
try (CloseableHttpResponse ignored2 = client.execute(post)) {
assertThat(registry.get("jetty.connections.current").gauge().value()).isEqualTo(2.0);
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
}
}
CountDownLatch latch = new CountDownLatch(1);
connector.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(LifeCycle event) {
latch.countDown();
}
});
// Convenient way to get Jetty to flush its connections, which is required to update the sent/received bytes metrics
server.stop();
assertTrue(latch.await(10, SECONDS));
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
assertThat(registry.get("jetty.connections.request").tag("type", "server").timer().count())
.isEqualTo(2);
assertThat(registry.get("jetty.connections.bytes.in").summary().totalAmount()).isGreaterThan(1);
}
@Test
void contributesClientConnectorMetrics() throws Exception {
setup();
HttpClient httpClient = new HttpClient();
httpClient.setFollowRedirects(false);
httpClient.addBean(new JettyConnectionMetrics(registry));
CountDownLatch latch = new CountDownLatch(1);
httpClient.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(LifeCycle event) {
latch.countDown();
}
});
httpClient.start();
Request post = httpClient.POST("http://localhost:" + connector.getLocalPort());
post.content(new StringContentProvider("123456"));
post.send();
httpClient.stop();
assertTrue(latch.await(10, SECONDS));
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(1.0);
assertThat(registry.get("jetty.connections.request").tag("type", "client").timer().count())
.isEqualTo(1);
assertThat(registry.get("jetty.connections.bytes.out").summary().totalAmount()).isGreaterThan(1);
}
@Test
void passingConnectorAddsConnectorNameTag() {
new JettyConnectionMetrics(registry, connector);
assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
.isEqualTo("unnamed");
}
@Test
void namedConnectorsGetTaggedWithName() {
connector.setName("super-fast-connector");
new JettyConnectionMetrics(registry, connector);
assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
.isEqualTo("super-fast-connector");
}
}
|
micrometer-metrics/micrometer
|
micrometer-binders/src/test/java/io/micrometer/binder/jetty/JettyConnectionMetricsTest.java
|
Java
|
apache-2.0
| 5,449 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.resource.impl;
import org.onosproject.net.resource.DiscreteResource;
import org.onosproject.net.resource.DiscreteResourceId;
import java.util.List;
import java.util.Optional;
import java.util.Set;
interface DiscreteResources {
static DiscreteResources empty() {
return NonEncodableDiscreteResources.empty();
}
Optional<DiscreteResource> lookup(DiscreteResourceId id);
DiscreteResources difference(DiscreteResources other);
boolean isEmpty();
boolean containsAny(List<DiscreteResource> other);
// returns a new instance, not mutate the current instance
DiscreteResources add(DiscreteResources other);
// returns a new instance, not mutate the current instance
DiscreteResources remove(List<DiscreteResource> removed);
Set<DiscreteResource> values();
}
|
lsinfo3/onos
|
core/store/dist/src/main/java/org/onosproject/store/resource/impl/DiscreteResources.java
|
Java
|
apache-2.0
| 1,461 |
<?php
namespace OpenConext\Value\Saml\Metadata;
use OpenConext\Value\Assert\Assertion;
use OpenConext\Value\RegularExpression;
use OpenConext\Value\Serializable;
final class ShibbolethMetadataScope implements Serializable
{
/**
* @var string
*/
private $scope;
/**
* @var bool
*/
private $isRegexp;
/**
* @param string $literal
* @return ShibbolethMetadataScope
*/
public static function literal($literal)
{
Assertion::nonEmptyString($literal, 'literal');
return new self($literal);
}
/**
* @param string $regexp
* @return ShibbolethMetadataScope
*/
public static function regexp($regexp)
{
Assertion::nonEmptyString($regexp, 'regexp');
return new self($regexp, true);
}
/**
* @param string $scope the scope as defined
* @param bool $isRegexp whether or not the scope is a regular expression as identified by the regexp attribute
*/
public function __construct($scope, $isRegexp = false)
{
Assertion::nonEmptyString($scope, 'scope');
Assertion::boolean($isRegexp);
if ($isRegexp) {
Assertion::validRegularExpression('#' . $scope . '#i', 'scope');
}
$this->scope = $scope;
$this->isRegexp = $isRegexp;
}
/**
* @param string $string
* @return bool
*/
public function allows($string)
{
Assertion::string($string, 'Scope to check should be a string, "%s" given');
if (!$this->isRegexp) {
return strcasecmp($this->scope, $string) === 0;
}
$regexp = new RegularExpression('#' . $this->scope . '#i');
return $regexp->matches($string);
}
/**
* @param ShibbolethMetadataScope $other
* @return bool
*/
public function equals(ShibbolethMetadataScope $other)
{
return (strcasecmp($this->scope, $other->scope) === 0 && $this->isRegexp === $other->isRegexp);
}
public static function deserialize($data)
{
Assertion::isArray($data);
Assertion::keysExist($data, array('is_regexp', 'scope'));
return new self($data['scope'], $data['is_regexp']);
}
public function serialize()
{
return array(
'scope' => $this->scope,
'is_regexp' => $this->isRegexp
);
}
public function __toString()
{
return sprintf(
'ShibbolethMetadataScope(scope=%s, regexp=%s)',
$this->scope,
$this->isRegexp ? 'true' : 'false'
);
}
}
|
OpenConext/SamlValueObject
|
src/OpenConext/Value/Saml/Metadata/ShibbolethMetadataScope.php
|
PHP
|
apache-2.0
| 2,613 |
/*jshint camelcase: false */
var common = require('../../lib/common');
var msRestRequest = require('../../lib/common/msRestRequest');
var chai = require('chai');
var should = chai.should();
var util = require('util');
exports.clean = function(provisioningParameters, done) {
var resourceGroupName = provisioningParameters.resourceGroup;
if (!resourceGroupName) {
return done();
}
var environmentName = process.env['ENVIRONMENT'];
var subscriptionId = process.env['SUBSCRIPTION_ID'];
var API_VERSIONS = common.API_VERSION[environmentName];
var environment = common.getEnvironment(environmentName);
var resourceManagerEndpointUrl = environment.resourceManagerEndpointUrl;
var resourceGroupUrl = util.format('%s/subscriptions/%s/resourcegroups/%s',
resourceManagerEndpointUrl,
subscriptionId,
resourceGroupName);
var headers = common.mergeCommonHeaders('Delete resource group for integration test', {});
msRestRequest.DELETE(resourceGroupUrl, headers, API_VERSIONS.RESOURCE_GROUP, function (err, res, body) {
should.not.exist(err);
res.statusCode.should.equal(202);
done();
});
};
|
zhongyi-zhang/meta-azure-service-broker
|
test/integration/cleaner.js
|
JavaScript
|
apache-2.0
| 1,244 |
/*
* Copyright 2014 FIZ Karlsruhe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ROLE_ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.escidocng;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* @author mih
*/
public class WebInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(EscidocngServerConfiguration.class, EscidocngServerSecurityConfiguration.class,
OAuth2ServerConfiguration.class);
}
}
|
escidoc-ng/escidoc-ng
|
escidocng-backend/src/main/java/de/escidocng/WebInitializer.java
|
Java
|
apache-2.0
| 1,132 |
using System;
namespace DotKafka.Prototype.Common.Errors
{
public class UnknownServerException : ApiException
{
public UnknownServerException() { }
public UnknownServerException(string message) : base(message) { }
public UnknownServerException(string message, Exception inner) : base(message, inner) { }
}
}
|
rudygt/dot-kafka
|
DotKafka.Prototype/Common/Errors/UnknownServerException.cs
|
C#
|
apache-2.0
| 346 |
#!/usr/bin/python
import sys
# try to import from the default place Munki installs it
try:
from munkilib import FoundationPlist, munkicommon
except:
sys.path.append('/usr/local/munki')
from munkilib import FoundationPlist, munkicommon
import os
from datetime import datetime
FILE_LOCATION = "/Users/Shared/.msc-dnd.plist"
# Does the file exist?
if not os.path.isfile(FILE_LOCATION):
# File isn't here, set the Munki pref to False
munkicommon.set_pref('SuppressUserNotification', False)
sys.exit(0)
# If it does, get the current date?
else:
plist = FoundationPlist.readPlist(FILE_LOCATION)
if 'DNDEndDate' not in plist:
# The key we need isn't in there, remove the file, set pref and exit
os.remove(FILE_LOCATION)
munkicommon.set_pref('SuppressUserNotification', False)
sys.exit(0)
else:
# Is the current date greater than the DND date?
saved_time = datetime.strptime(str(plist['DNDEndDate']), "%Y-%m-%d %H:%M:%S +0000")
current_time = datetime.now()
if saved_time < current_time:
# print "Current time is greater"
# If yes, remove the file and set the Munki pref for suppress notifications to False
os.remove(FILE_LOCATION)
munkicommon.set_pref('SuppressUserNotification', False)
sys.exit(0)
else:
# print "Saved Time is greater"
munkicommon.set_pref('SuppressUserNotification', True)
sys.exit(0)
# If no, make sure suppress notifications is True
|
grahamgilbert/munki-dnd
|
munki-dnd.py
|
Python
|
apache-2.0
| 1,572 |
package com.nitorcreations.willow.metrics;
import javax.inject.Named;
@Named("/types")
public class MessageTypesMetric extends TagListMetric {
public MessageTypesMetric() {
super("category");
}
}
|
NitorCreations/willow
|
willow-servers/src/main/java/com/nitorcreations/willow/metrics/MessageTypesMetric.java
|
Java
|
apache-2.0
| 206 |
package model
// Pool .
type Pool struct {
Id int64 `json:"id"`
CoinId int64 `json:"coin_id"`
Title string `json:"title"`
Description string `json:"description"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
Status int64 `json:"status"`
IsBottom int64 `json:"is_bottom"`
}
// Coin .
type Coin struct {
Id int64 `json:"id"`
Title string `json:"title"`
GiftType int64 `json:"gift_type"`
ChangeNum int64 `json:"change_num"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
Status int64 `json:"status"`
}
// UserInfo .
type UserInfo struct {
Uid int64 `json:"uid"`
NormalScore int64 `json:"normal_score"`
ColorfulScore int64 `json:"colorful_score"`
}
// GiftMsg .
type GiftMsg struct {
// by notify
MsgContent string `form:"msg_content"`
}
// CoinConfig .
type CoinConfig struct {
CoinId int64 `json:"coin_id"`
Type int64 `json:"type"`
AreaV2ParentId int64 `json:"area_v2_parent_id"`
AreaV2Id int64 `json:"area_v2_id"`
GiftId int64 `json:"gift_id"`
IsAll int64 `json:"is_all"`
}
// PoolPrize .
type PoolPrize struct {
Id int64 `json:"id"`
PoolId int64 `json:"pool_id"`
Type int64 `json:"type"`
Num int64 `json:"num"`
ObjectId int64 `json:"object_id"`
Expire int64 `json:"expire"`
WebUrl string `json:"web_url"`
MobileUrl string `json:"mobile_url"`
Description string `json:"description"`
JumpUrl string `json:"jump_url"`
ProType int64 `json:"pro_type"`
Chance int64 `json:"chance"`
LoopNum int64 `json:"loop_num"`
LimitNum int64 `json:"limit_num"`
Weight int64 `json:"weight"`
}
// AddCapsule AddCapsule
type AddCapsule struct {
Uid int64 `json:"uid"`
Type string `json:"type"`
CoinId int64 `json:"coin_id"`
Num int64 `json:"num"`
Source string `json:"source"`
MsgId string `json:"msg_id"`
}
// ExtraData .
type ExtraData struct {
Id int64 `json:"id"`
Uid int64 `json:"uid"`
Type string `json:"type"`
ItemValue int64 `json:"item_value"`
ItemExtra string `json:"item_extra"`
}
|
LQJJ/demo
|
126-go-common-master/app/job/live/xlottery/internal/model/model.go
|
GO
|
apache-2.0
| 2,202 |
/*
* Copyright to the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.resolver.aether.util;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.sonatype.aether.transfer.AbstractTransferListener;
import org.sonatype.aether.transfer.TransferEvent;
import org.sonatype.aether.transfer.TransferResource;
/**
* A simplistic transfer listener that logs uploads/downloads to the console.
*/
public class ConsoleTransferListener extends AbstractTransferListener {
private PrintStream out;
private Map<TransferResource, Long> downloads = new ConcurrentHashMap<TransferResource, Long>();
private int lastLength;
public ConsoleTransferListener() {
this(null);
}
public ConsoleTransferListener(PrintStream out) {
this.out = (out != null) ? out : System.out;
}
@Override
public void transferProgressed(TransferEvent event) {
TransferResource resource = event.getResource();
downloads.put(resource, event.getTransferredBytes());
StringBuilder buffer = new StringBuilder(64);
for (Map.Entry<TransferResource, Long> entry : downloads.entrySet()) {
long total = entry.getKey().getContentLength();
long complete = entry.getValue();
buffer.append(getStatus(complete, total)).append(" ");
}
int pad = lastLength - buffer.length();
lastLength = buffer.length();
pad(buffer, pad);
buffer.append('\r');
out.print(buffer);
}
private String getStatus(long complete, long total) {
if (total >= 1024) {
return toKB(complete) + "/" + toKB(total) + " KB ";
} else if (total >= 0) {
return complete + "/" + total + " B ";
} else if (complete >= 1024) {
return toKB(complete) + " KB ";
} else {
return complete + " B ";
}
}
private void pad(StringBuilder buffer, final int spaces) {
int spaceCountDown = spaces;
String block = " ";
while (spaceCountDown > 0) {
int n = Math.min(spaces, block.length());
buffer.append(block, 0, n);
spaceCountDown -= n;
}
}
@Override
public void transferSucceeded(TransferEvent event) {
transferCompleted(event);
TransferResource resource = event.getResource();
long contentLength = event.getTransferredBytes();
if (contentLength >= 0) {
String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
String throughput = "";
long duration = System.currentTimeMillis() - resource.getTransferStartTime();
if (duration > 0) {
DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
throughput = " at " + format.format(kbPerSec) + " KB/sec";
}
out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
+ throughput + ")");
}
}
@Override
public void transferFailed(TransferEvent event) {
transferCompleted(event);
//out.println("[WARNING] "+event.getException().getLocalizedMessage());
}
private void transferCompleted(TransferEvent event) {
downloads.remove(event.getResource());
if (event.getDataLength() > 0) {
StringBuilder buffer = new StringBuilder(64);
pad(buffer, lastLength);
buffer.append('\r');
out.print(buffer);
}
}
public void transferCorrupted(TransferEvent event) {
TransferResource resource = event.getResource();
out.println("[WARNING] " + event.getException().getMessage() + " for " +
resource.getRepositoryUrl() + resource.getResourceName());
}
protected long toKB(long bytes) {
return (bytes + 1023) / 1024;
}
}
|
khartig/assimilator
|
rio-resolver/resolver-aether/src/main/java/org/rioproject/resolver/aether/util/ConsoleTransferListener.java
|
Java
|
apache-2.0
| 4,898 |
var Canvas = require('canvas');
var Image = Canvas.Image;
// Constants
var canvasWidth = 350;
var canvasHeight = 150;
var cellSize = 30;
var colorMap = {
0: 'rgba(0, 0, 0, 0)',
1: '#F7F6EA',
2: '#E6E6E1',
3: '#EBC000'
};
module.exports = generate;
function generate(title, accuracy) {
var canvas = new Canvas(canvasWidth, canvasHeight);
var ctx = canvas.getContext('2d');
drawTitle(ctx, title);
drawAccuracy(ctx, accuracy);
drawAccuracySub(ctx);
drawHeatMap(ctx);
return canvas.toBuffer();
};
function drawHeatMap(ctx) {
var grid = [
[ 1, 3, 3, 2 ],
[ 0, 1, 2, 1 ],
[ 0, 2, 3, 1 ]
];
var y = 60;
grid.forEach(function(r) {
var x = canvasWidth - cellSize;
r.reverse().forEach(function(c, j) {
drawCell(ctx, x - (j * 2), y, colorMap[c]);
x -= cellSize;
});
y += cellSize;
});
}
function drawCell(ctx, x, y, fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(x, y, cellSize, cellSize);
}
function drawTitle(ctx, title) {
//var title = 'Profit and Discount drives sales with a';
ctx.font = '14px Kozuka Gothic Pro';
ctx.fillText(title, 20, 30);
}
function drawAccuracy(ctx, accuracy) {
accuracy += '%';
ctx.font = '60px Kozuka Gothic Pro';
ctx.fillText(accuracy, 20, 100);
}
function drawAccuracySub(ctx) {
var sub = 'driver strength';
ctx.font = '14px Kozuka Gothic Pro';
ctx.fillText(sub, 20, 125);
}
|
gw1018/imageservice
|
images/heatmap.js
|
JavaScript
|
apache-2.0
| 1,415 |
package com.cyou.cpush.apns.notification;
import java.util.concurrent.atomic.AtomicInteger;
public class DefaultNotification implements Notification {
private static AtomicInteger IDENTIFIER_GENERATOR = new AtomicInteger(Integer.MAX_VALUE-1);
private int identifier;
private Device device;
private Payload payload;
public DefaultNotification(Device device, Payload payload) {
this(IDENTIFIER_GENERATOR.incrementAndGet(), device, payload);
}
public DefaultNotification(int identifier, Device device, Payload payload) {
this.identifier = identifier;
this.device = device;
this.payload = payload;
}
/*
* (non-Javadoc)
*
* @see com.cyou.cpush.apns.Notification#getDevice()
*/
@Override
public Device getDevice() {
return device;
}
/*
* (non-Javadoc)
*
* @see com.cyou.cpush.apns.Notification#getPayload()
*/
@Override
public Payload getPayload() {
return payload;
}
public void setDevice(Device device) {
this.device = device;
}
public void setPayload(Payload payload) {
this.payload = payload;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
@Override
public int getIdentifier() {
return identifier;
}
}
|
beforeeight/cpush-apns
|
src/main/java/com/cyou/cpush/apns/notification/DefaultNotification.java
|
Java
|
apache-2.0
| 1,207 |
package com.craftmend.openaudiomc.spigot.modules.proxy.service;
import com.craftmend.openaudiomc.generic.networking.DefaultNetworkingService;
import com.craftmend.openaudiomc.generic.networking.abstracts.AbstractPacket;
import com.craftmend.openaudiomc.generic.networking.client.objects.player.ClientConnection;
import com.craftmend.openaudiomc.generic.networking.interfaces.Authenticatable;
import com.craftmend.openaudiomc.generic.networking.interfaces.INetworkingEvents;
import com.craftmend.openaudiomc.generic.networking.interfaces.NetworkingService;
import com.craftmend.openaudiomc.generic.node.packets.ForwardSocketPacket;
import com.craftmend.openaudiomc.generic.player.SpigotPlayerAdapter;
import com.craftmend.openaudiomc.spigot.OpenAudioMcSpigot;
import com.craftmend.openaudiomc.spigot.modules.proxy.listeners.BungeePacketListener;
import com.craftmend.openaudiomc.api.velocitypluginmessageframework.PacketPlayer;
import com.craftmend.openaudiomc.api.velocitypluginmessageframework.implementations.BukkitPacketManager;
import lombok.Getter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import org.bukkit.entity.Player;
import java.util.*;
public class ProxyNetworkingService extends NetworkingService {
@Getter private final Set<INetworkingEvents> eventHandlers = new HashSet<>();
private final DefaultNetworkingService realService = new DefaultNetworkingService();
private final BukkitPacketManager packetManager;
public ProxyNetworkingService() {
packetManager = new BukkitPacketManager(OpenAudioMcSpigot.getInstance(), "openaudiomc:node");
packetManager.registerListener(new BungeePacketListener());
}
@Override
public void connectIfDown() {
// unused in fake system
}
@Override
public void send(Authenticatable client, AbstractPacket packet) {
// handle packet if it should be passed to bungee
// forward every packet starting with PacketClient
if (!(client instanceof ClientConnection)) throw new UnsupportedOperationException("The bungee adapter for the networking service only supports client connections");
if (packet.getClass().getSimpleName().startsWith("PacketClient")) {
packet.setClient(client.getOwnerUUID());
Player player = ((SpigotPlayerAdapter) ((ClientConnection) client).getPlayer()).getPlayer();
packetManager.sendPacket(new PacketPlayer(player), new ForwardSocketPacket(packet));
}
}
@Override
public void triggerPacket(AbstractPacket abstractPacket) {
// unused in fake system
}
@Override
public ClientConnection getClient(UUID uuid) {
return realService.getClient(uuid);
}
@Override
public Collection<ClientConnection> getClients() {
return realService.getClients();
}
@Override
public void remove(UUID player) {
realService.remove(player);
}
@Override
public ClientConnection register(Player player) {
return realService.register(player);
}
@Override
public ClientConnection register(ProxiedPlayer player) {
return realService.register(player);
}
public ClientConnection register(com.velocitypowered.api.proxy.Player player) {
return realService.register(player);
}
@Override
public void stop() {
// unused in fake system
}
@Override
public Set<INetworkingEvents> getEvents() {
return eventHandlers;
}
@Override
public void addEventHandler(INetworkingEvents events) {
eventHandlers.add(events);
}
}
|
ApocalypsjeNL/OpenAudioMc
|
plugin/src/main/java/com/craftmend/openaudiomc/spigot/modules/proxy/service/ProxyNetworkingService.java
|
Java
|
apache-2.0
| 3,602 |
package fr.excilys.computerdatabase.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import fr.excilys.computerdatabase.model.Description;
import fr.excilys.computerdatabase.model.Role;
import fr.excilys.computerdatabase.model.User;
import fr.excilys.computerdatabase.persistence.UserDao;
import fr.excilys.computerdatabase.validator.DescriptionDTO;
import fr.excilys.computerdatabase.validator.UserDTO;
@Service
public class UserServices implements UserDetailsService {
@Autowired
UserDao userDao;
@Autowired
CompanyServices companyServices;
public User findUserByUsername(String username) {
return userDao.findUserByUsername(username);
}
public List<Description> findAllUsers() {
return userDao.findAllDescriptions();
}
public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {
User user = userDao.findUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(" Username not found ! ");
}
List<Role> roles = userDao.findRolesForUser(username);
List<GrantedAuthority> grantList = new ArrayList<>();
if (roles != null) {
for (Role role : roles) {
GrantedAuthority authority = new SimpleGrantedAuthority(role.getRole());
grantList.add(authority);
}
}
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(), grantList);
return userDetails;
}
public boolean createUser(UserDTO user) {
User userToInsert = new User(user.getUsername(), user.getPassword());
userDao.createUser(userToInsert);
return true;
}
public boolean userNotExist(String username) {
return userDao.usernameNotExist(username);
}
public boolean modifyDescription(DescriptionDTO descriptionDTO) {
Description description = new Description.Builder()
.id(descriptionDTO.getId())
.email(descriptionDTO.getEmail())
.firstname(descriptionDTO.getFirstname())
.lastname(descriptionDTO.getLastname())
.information(descriptionDTO.getInformation())
.user(userDao.findUserById(descriptionDTO.getUser_id()))
.company(descriptionDTO.getCompany()!= null && !descriptionDTO.getCompany().isEmpty() ? companyServices.getOrCreateCompany(descriptionDTO.getCompany()) : null)
.build();
userDao.modifyDescription(description);
return true;
}
public DescriptionDTO getDescription(String username) {
Description description = userDao.findDescription(username);
if (description == null) {
return null;
}
DescriptionDTO dDto = new DescriptionDTO.Builder()
.id(description.getId())
.email(description.getEmail())
.firstname(description.getFirstname())
.lastname(description.getLastname())
.information(description.getInformation())
.user_id(description.getUser().getId())
.company_id(description.getCompany() != null ? description.getCompany().getId() : -1)
.company(description.getCompany()!= null ? description.getCompany().getName() : "")
.build();
return dDto;
}
}
|
krmmlsh/Java_Training
|
service/src/main/java/fr/excilys/computerdatabase/service/UserServices.java
|
Java
|
apache-2.0
| 3,492 |
package com.wecan.xhin.studio;
import android.app.Application;
import android.content.Context;
import com.avos.avoscloud.AVOSCloud;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import com.wecan.xhin.baselib.net.LoggingInterceptor;
import com.wecan.xhin.studio.api.Api;
import java.io.IOException;
import java.util.HashMap;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
public class App extends Application {
public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5";
public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj";
public static final String KEY_PREFERENCE_USER = "user";
public static final String KEY_PREFERENCE_PHONE = "phone";
public static final String KEY_BUILD_VERSION = "build_version";
public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private final HashMap<Class, Object> apis = new HashMap<>();
private Retrofit retrofit;
//返回当前单例的静态方法,判断是否是当前的App调用
public static App from(Context context) {
Context application = context.getApplicationContext();
if (application instanceof App)
return (App) application;
throw new IllegalArgumentException("Context must be from Studio");
}
@Override
public void onCreate() {
super.onCreate();
AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY);
OkHttpClient okHttpClient = new OkHttpClient();
//OKHttp的使用
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request().newBuilder()
.header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME)
.build());
}
});
if (BuildConfig.DEBUG) {
okHttpClient.networkInterceptors().add(new LoggingInterceptor());
}
//初始化Gson
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat(DATE_FORMAT_PATTERN)
.create();
//初始化Retrofit
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Api.BASE_URL)
.build();
}
//返回Retrofit的API
public <T> T createApi(Class<T> service) {
if (!apis.containsKey(service)) {
T instance = retrofit.create(service);
apis.put(service, instance);
}
//noinspection unchecked
return (T) apis.get(service);
}
public OkHttpClient getHttpClient() {
return retrofit.client();
}
}
|
XhinLiang/Studio
|
app/src/main/java/com/wecan/xhin/studio/App.java
|
Java
|
apache-2.0
| 3,181 |
package com.cantinho.spoonacularexample.retrofit_models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by samirtf on 14/02/17.
*/
public class Recipe {
@SerializedName("id")
private Integer id;
@SerializedName("image")
private String image;
@SerializedName("usedIngredientCount")
private Integer usedIngredientCount;
@SerializedName("missedIngredientCount")
private Integer missedIngredientCount;
@SerializedName("likes")
private Integer likes;
@Override
public String toString() {
return "Recipe{" +
"id=" + id +
", image='" + image + '\'' +
", usedIngredientCount=" + usedIngredientCount +
", missedIngredientCount=" + missedIngredientCount +
", likes=" + likes +
'}';
}
}
|
Cantinho/spoonaculator-android-example
|
SpoonacularExample/app/src/main/java/com/cantinho/spoonacularexample/retrofit_models/Recipe.java
|
Java
|
apache-2.0
| 923 |
#pragma once
#include <map>
#include "..\..\Defines.hpp"
namespace te
{
class DynamicLibrary;
class TE_EXPORT DynamicLibraryManager
{
protected:
std::map<string, DynamicLibrary*> m_loadedLibraries;
public:
DynamicLibraryManager();
~DynamicLibraryManager();
/*
Loads the library with the specified name. The file extension can be omitted.
Returns a pointer to the loaded library.
*/
DynamicLibrary* load(const string& name);
/*
Unloads the specified DynLib.
*/
void unload(DynamicLibrary* dynLib);
};
}
|
unpause/TeazelEngine
|
TeazelEngine/TeazelEngine/core/dynlib/DynamicLibraryManager.hpp
|
C++
|
apache-2.0
| 543 |
/*
* The University of Wales, Cardiff Triana Project Software License (Based
* on the Apache Software License Version 1.1)
*
* Copyright (c) 2007 University of Wales, Cardiff. All rights reserved.
*
* Redistribution and use of the software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowledgment: "This product includes
* software developed by the University of Wales, Cardiff for the Triana
* Project (http://www.trianacode.org)." Alternately, this
* acknowledgment may appear in the software itself, if and wherever
* such third-party acknowledgments normally appear.
*
* 4. The names "Triana" and "University of Wales, Cardiff" must not be
* used to endorse or promote products derived from this software
* without prior written permission. For written permission, please
* contact triana@trianacode.org.
*
* 5. Products derived from this software may not be called "Triana," nor
* may Triana appear in their name, without prior written permission of
* the University of Wales, Cardiff.
*
* 6. This software may not be sold, used or incorporated into any product
* for sale to third parties.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL UNIVERSITY OF WALES, CARDIFF OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* ------------------------------------------------------------------------
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Triana Project. For more information on the
* Triana Project, please see. http://www.trianacode.org.
*
* This license is based on the BSD license as adopted by the Apache
* Foundation and is governed by the laws of England and Wales.
*
*/
package org.trianacode.gui.main.imp;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.AbstractButton;
import org.trianacode.gui.main.TrianaLayoutConstants;
/**
* A class that displays a little plus minus icon
*
* @author Ian Wang
* @version $Revision: 4048 $
*/
public class PlusMinusIcon extends AbstractButton implements MouseListener {
/**
* Variable representing the PlusMinusIcon default preferred size
*/
private Dimension DEFAULT_SIZE = TrianaLayoutConstants.DEFAULT_PLUS_MINUS_SIZE;
private boolean input = true;
private boolean plus = true;
public PlusMinusIcon(boolean plus) {
this.plus = plus;
addMouseListener(this);
setPreferredSize(DEFAULT_SIZE);
}
public PlusMinusIcon(boolean plus, boolean input) {
this.input = input;
this.plus = plus;
addMouseListener(this);
setPreferredSize(DEFAULT_SIZE);
}
protected void paintComponent(Graphics graphs) {
super.paintComponent(graphs);
Dimension size = getSize();
Color col = graphs.getColor();
int left = 0;
int top = 0;
int width = size.width;
int height = size.height;
if (size.width % 2 == 0) {
width = size.width - 1;
if (!input) {
left = 1;
}
}
if (size.height % 2 == 0) {
height = size.height - 1;
if (plus) {
top = 1;
}
}
graphs.setColor(getForeground());
graphs.drawLine(left, top + (height / 2), left + width, top + (height / 2));
if (plus) {
graphs.drawLine(left + (width / 2), top, left + (width / 2), top + height);
}
graphs.setColor(col);
}
/**
* Invoked when the mouse button has been clicked (pressed and released) on a component.
*/
public void mouseClicked(MouseEvent event) {
String command;
if (plus) {
command = "+";
} else {
command = "-";
}
fireActionPerformed(new ActionEvent(this, event.getID(), command));
}
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent e) {
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent e) {
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(MouseEvent e) {
}
}
|
CSCSI/Triana
|
triana-gui/src/main/java/org/trianacode/gui/main/imp/PlusMinusIcon.java
|
Java
|
apache-2.0
| 5,724 |
package ru.job4j.profession;
/**
* This class describes student with no parameters and operations.
*
* @author Kucykh Vasily (mailto:basil135@mail.ru)
* @version $Id$
* @since 12.04.2017
*/
public class Student extends Human {
/**
* constructor of Student class.
*
* @param name is name of a student
*/
public Student(String name) {
super(name);
}
}
|
Basil135/vkucyh
|
chapter_002/src/main/java/ru/job4j/profession/Student.java
|
Java
|
apache-2.0
| 399 |
package io.datakernel.di.impl;
import java.util.concurrent.atomic.AtomicReferenceArray;
@SuppressWarnings("rawtypes")
public abstract class AbstractUnsyncCompiledBinding<R> implements CompiledBinding<R> {
protected final int scope;
protected final int index;
protected AbstractUnsyncCompiledBinding(int scope, int index) {
this.scope = scope;
this.index = index;
}
@SuppressWarnings("unchecked")
@Override
public final R getInstance(AtomicReferenceArray[] scopedInstances, int synchronizedScope) {
AtomicReferenceArray array = scopedInstances[scope];
R instance = (R) array.get(index);
if (instance != null) return instance;
instance = doCreateInstance(scopedInstances, synchronizedScope);
array.lazySet(index, instance);
return instance;
}
protected abstract R doCreateInstance(AtomicReferenceArray[] scopedInstances, int synchronizedScope);
}
|
softindex/datakernel
|
core-di/src/main/java/io/datakernel/di/impl/AbstractUnsyncCompiledBinding.java
|
Java
|
apache-2.0
| 875 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.api.java.io.jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.types.Row;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
public class JDBCOutputFormatTest extends JDBCTestBase {
private JDBCOutputFormat jdbcOutputFormat;
private Tuple5<Integer, String, String, Double, String> tuple5 = new Tuple5<>();
@After
public void tearDown() throws IOException {
if (jdbcOutputFormat != null) {
jdbcOutputFormat.close();
}
jdbcOutputFormat = null;
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidDriver() throws IOException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername("org.apache.derby.jdbc.idontexist")
.setDBUrl(DB_URL)
.setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE))
.finish();
jdbcOutputFormat.open(0, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidURL() throws IOException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(DRIVER_CLASS)
.setDBUrl("jdbc:der:iamanerror:mory:ebookshop")
.setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE))
.finish();
jdbcOutputFormat.open(0, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidQuery() throws IOException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(DRIVER_CLASS)
.setDBUrl(DB_URL)
.setQuery("iamnotsql")
.finish();
jdbcOutputFormat.open(0, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testIncompleteConfiguration() throws IOException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(DRIVER_CLASS)
.setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE))
.finish();
}
@Test(expected = IllegalArgumentException.class)
public void testIncompatibleTypes() throws IOException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(DRIVER_CLASS)
.setDBUrl(DB_URL)
.setQuery(String.format(INSERT_TEMPLATE, INPUT_TABLE))
.finish();
jdbcOutputFormat.open(0, 1);
tuple5.setField(4, 0);
tuple5.setField("hello", 1);
tuple5.setField("world", 2);
tuple5.setField(0.99, 3);
tuple5.setField("imthewrongtype", 4);
Row row = new Row(tuple5.getArity());
for (int i = 0; i < tuple5.getArity(); i++) {
row.setField(i, tuple5.getField(i));
}
jdbcOutputFormat.writeRecord(row);
jdbcOutputFormat.close();
}
@Test
public void testJDBCOutputFormat() throws IOException, InstantiationException, IllegalAccessException {
jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(DRIVER_CLASS)
.setDBUrl(DB_URL)
.setQuery(String.format(INSERT_TEMPLATE, OUTPUT_TABLE))
.finish();
jdbcOutputFormat.open(0, 1);
for (int i = 0; i < testData.length; i++) {
Row row = new Row(testData[i].length);
for (int j = 0; j < testData[i].length; j++) {
row.setField(j, testData[i][j]);
}
jdbcOutputFormat.writeRecord(row);
}
jdbcOutputFormat.close();
try (
Connection dbConn = DriverManager.getConnection(JDBCTestBase.DB_URL);
PreparedStatement statement = dbConn.prepareStatement(JDBCTestBase.SELECT_ALL_NEWBOOKS);
ResultSet resultSet = statement.executeQuery()
) {
int recordCount = 0;
while (resultSet.next()) {
Row row = new Row(tuple5.getArity());
for (int i = 0; i < tuple5.getArity(); i++) {
row.setField(i, resultSet.getObject(i + 1));
}
if (row.getField(0) != null) {
Assert.assertEquals("Field 0 should be int", Integer.class, row.getField(0).getClass());
}
if (row.getField(1) != null) {
Assert.assertEquals("Field 1 should be String", String.class, row.getField(1).getClass());
}
if (row.getField(2) != null) {
Assert.assertEquals("Field 2 should be String", String.class, row.getField(2).getClass());
}
if (row.getField(3) != null) {
Assert.assertEquals("Field 3 should be float", Double.class, row.getField(3).getClass());
}
if (row.getField(4) != null) {
Assert.assertEquals("Field 4 should be int", Integer.class, row.getField(4).getClass());
}
for (int x = 0; x < tuple5.getArity(); x++) {
if (JDBCTestBase.testData[recordCount][x] != null) {
Assert.assertEquals(JDBCTestBase.testData[recordCount][x], row.getField(x));
}
}
recordCount++;
}
Assert.assertEquals(JDBCTestBase.testData.length, recordCount);
} catch (SQLException e) {
Assert.fail("JDBC OutputFormat test failed. " + e.getMessage());
}
}
}
|
DieBauer/flink
|
flink-connectors/flink-jdbc/src/test/java/org/apache/flink/api/java/io/jdbc/JDBCOutputFormatTest.java
|
Java
|
apache-2.0
| 5,607 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import java.util.List;
public class AndroidSenseManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return AndroidSenseConstants.DEVICE_TYPE;
}
@Override
public String getProviderTenantDomain() {
return AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN;
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager=new AndroidSenseManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException {
}
@Override public void installApplicationForUsers(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override public void installApplicationForUserRoles(Operation operation, List<String> list)
throws ApplicationManagementException {
}
}
|
NuwanSameera/carbon-device-mgt-plugins
|
components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/plugin/impl/AndroidSenseManagerService.java
|
Java
|
apache-2.0
| 3,097 |
package com.bestxty.designpattern.decorator;
/**
* @author jiangtaiyang
* Created by jiangtaiyang on 2017/6/29.
*/
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("real operation.");
}
}
|
swjjxyxty/Study
|
studyjavase/studyjavasedesignpattern/src/main/java/com/bestxty/designpattern/decorator/ConcreteComponent.java
|
Java
|
apache-2.0
| 281 |
/*
* Copyright 2003 - 2014 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
/**
* The dojo package. includes all js from dojo 1.7.2.
*/
package org.efaps.ui.wicket.behaviors.dojo;
|
eFaps/eFaps-WebApp
|
src/main/java/org/efaps/ui/wicket/behaviors/dojo/package-info.java
|
Java
|
apache-2.0
| 797 |
/*******************************************************************************
* Copyright 2007-2013 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package xworker.swt.xworker;
import org.eclipse.swt.widgets.Control;
import org.xmeta.ActionContext;
import org.xmeta.Bindings;
import org.xmeta.Thing;
import org.xmeta.World;
import xworker.swt.design.Designer;
public class ExtendWidgetCreator {
public static Object create(ActionContext actionContext){
//World world = World.getInstance();
Thing self = (Thing) actionContext.get("self");
Thing widgetThing = self.doAction("getExtendWidget", actionContext);
if(widgetThing != null){
Object acObj = self.doAction("getActionContext", actionContext);
ActionContext ac = null;
if(acObj instanceof String){
acObj = actionContext.get(acObj.toString());
}
if(acObj == null || !(acObj instanceof ActionContext)){
ac = null;
}else{
ac = (ActionContext) acObj;
}
if(ac == null){
String actionContextName = self.getStringBlankAsNull("actionContext");
if(actionContextName != null){
Boolean createActionContextIfNotExists = self.doAction("isCreateActionContextIfNotExists", actionContext);
if(createActionContextIfNotExists != null && createActionContextIfNotExists){
ac = new ActionContext();
ac.put("parentContext", actionContext);
ac.put("parent", actionContext.get("parent"));
ac.put("parentThing", self);
actionContext.getScope(0).put(actionContextName, ac);
}
}else{
//旧的已过时的属性
if(self.getBoolean("newActionContext")){
ac = new ActionContext();
ac.put("parentContext", actionContext);
ac.put("parentThing", self);
ac.put("parent", actionContext.get("parent"));
String newActionContextName = self.getStringBlankAsNull("newActionContextName");
if(newActionContextName != null){
actionContext.getScope(0).put(newActionContextName, ac);
}
}else{
ac = actionContext;
}
}
}
ac.peek().put("parent", actionContext.getObject("parent"));
Object control = null;
Designer.pushCreator(self);
try{
control = widgetThing.doAction("create", ac);
}finally{
Designer.popCreator();
}
Bindings bindings = actionContext.push();
bindings.put("parent", control);
try{
for(Thing child : self.getChilds()){
child.doAction("create", actionContext);
}
}finally{
actionContext.pop();
}
if(control instanceof Control) {
Designer.attachCreator((Control) control, self.getMetadata().getPath(), actionContext);
}
actionContext.getScope(0).put(self.getMetadata().getName(), control);
return control;
} else {
return null;
}
}
}
|
x-meta/xworker
|
xworker_swt/src/main/java/xworker/swt/xworker/ExtendWidgetCreator.java
|
Java
|
apache-2.0
| 3,602 |
package com.psc.vote.vote.domain;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public class Anchor {
String anchorName;
BigDecimal anchorPrice;
Date creationDate;
String status;
String clientId;
String clientName;
String clientWebsiteAddress;
String clientInfo;
List<Campaign> campaigns;
public String getAnchorName() {
return anchorName;
}
public void setAnchorName(String anchorName) {
this.anchorName = anchorName;
}
public BigDecimal getAnchorPrice() {
return anchorPrice;
}
public void setAnchorPrice(BigDecimal anchorPrice) {
this.anchorPrice = anchorPrice;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientWebsiteAddress() {
return clientWebsiteAddress;
}
public void setClientWebsiteAddress(String clientWebsiteAddress) {
this.clientWebsiteAddress = clientWebsiteAddress;
}
public String getClientInfo() {
return clientInfo;
}
public void setClientInfo(String clientInfo) {
this.clientInfo = clientInfo;
}
public List<Campaign> getCampaigns() {
return campaigns;
}
public void setCampaigns(List<Campaign> campaigns) {
this.campaigns = campaigns;
}
@Override
public String toString() {
return "Anchor{" +
"anchorName='" + anchorName + '\'' +
", anchorPrice=" + anchorPrice +
", creationDate=" + creationDate +
", status='" + status + '\'' +
", clientId='" + clientId + '\'' +
", clientName='" + clientName + '\'' +
", clientWebsiteAddress='" + clientWebsiteAddress + '\'' +
", clientInfo='" + clientInfo + '\'' +
", campaigns=" + campaigns +
'}';
}
}
|
sgudupat/psc-vote-server
|
src/main/java/com/psc/vote/vote/domain/Anchor.java
|
Java
|
apache-2.0
| 2,490 |
package ar.com.larreta.stepper.controllers;
import javax.servlet.ServletContext;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ar.com.larreta.annotations.PerformanceMonitor;
import ar.com.larreta.stepper.Step;
import ar.com.larreta.stepper.StepElement;
import ar.com.larreta.stepper.messages.Body;
import ar.com.larreta.stepper.messages.JSONable;
import ar.com.larreta.stepper.messages.LoadBody;
import ar.com.larreta.stepper.messages.Request;
import ar.com.larreta.stepper.messages.Response;
import ar.com.larreta.stepper.messages.TargetedBody;
public abstract class ParentController<UpdateBodyRequest extends Body, LoadBodyRequest extends Body> extends StepElement {
public static final String LOAD = "/load";
public static final String DELETE = "/delete";
public static final String UPDATE = "/update";
public static final String CREATE = "/create";
@Autowired
protected ServletContext servletContext;
protected Step createBusiness;
protected Step updateBusiness;
protected Step deleteBusiness;
protected Step loadBusiness;
public abstract void setCreateBusiness(Step createBusiness);
public abstract void setUpdateBusiness(Step updateBusiness);
public abstract void setDeleteBusiness(Step deleteBusiness);
public abstract void setLoadBusiness(Step loadBusiness);
@PerformanceMonitor
@RequestMapping(value = CREATE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<TargetedBody> createPost(@Valid @RequestBody Request<UpdateBodyRequest> request, Errors errors) throws Exception{
return executeBusiness(request, createBusiness);
}
@PerformanceMonitor
@RequestMapping(value = UPDATE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<TargetedBody> updatePost(@Valid @RequestBody Request<UpdateBodyRequest> request, Errors errors) throws Exception{
return executeBusiness(request, updateBusiness);
}
private Response<TargetedBody> executeBusiness(Request<UpdateBodyRequest> request, Step business) throws Exception{
Response<TargetedBody> response = applicationContext.getBean(Response.class);
Long target = (Long) business.execute(request.getBody(), null, null);
TargetedBody responseBody = new TargetedBody();
responseBody.setTarget(target);
response.setBody(responseBody);
return response;
}
@PerformanceMonitor
@RequestMapping(value = DELETE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<TargetedBody> deletePost(@Valid @RequestBody Request<TargetedBody> request, Errors errors) throws Exception{
Response<TargetedBody> response = applicationContext.getBean(Response.class);
TargetedBody responseBody = new TargetedBody();
responseBody.setTarget(request.getBody().getTarget());
response.setBody(responseBody);
deleteBusiness.execute(request.getBody().getTarget(), null, null);
return response;
}
@PerformanceMonitor
@RequestMapping(value = LOAD, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<LoadBody<JSONable>> loadPost(@Valid @RequestBody Request<LoadBodyRequest> request, Errors errors) throws Exception{
Response<LoadBody<JSONable>> response = applicationContext.getBean(Response.class);;
LoadBody body = (LoadBody) loadBusiness.execute(request.getBody(), null, null);
response.setBody(body);
return response;
}
}
|
llarreta/larretasources
|
Stepper/src/main/java/ar/com/larreta/stepper/controllers/ParentController.java
|
Java
|
apache-2.0
| 3,717 |