diff --git a/.github/workflows/java-examples-test.yml b/.github/workflows/java-examples-test.yml new file mode 100644 index 0000000..72345ac --- /dev/null +++ b/.github/workflows/java-examples-test.yml @@ -0,0 +1,69 @@ +name: Java Examples CI + +on: + push: + paths: + - 'python/**' + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - ubuntu-latest + java-version: + - 1.8 + splunk-version: + - "8.2" + - "latest" + fail-fast: false + + services: + splunk: + image: splunk/splunk:${{matrix.splunk-version}} + env: + SPLUNK_START_ARGS: --accept-license + SPLUNK_PASSWORD: changed! + SPLUNK_HEC_TOKEN: 11111111-1111-1111-1111-1111111111113 + TEST_TCP_PORT: 10667 + TEST_UDP_PORT: 10668 + SPLUNK_HOME: "/opt/splunk" + SPLUNK_APPS_URL: https://github.com/splunk/sdk-app-collection/releases/download/v1.1.0/sdkappcollection.tgz + ports: + - 8000:8000 + - 8089:8089 + - 8088:8088 + - 10667:10667 + - 10668:10668/udp + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Cache local Maven repository + working-directory: ./java + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-maven- + - name: Create .splunkrc file + working-directory: ./java + run: | + cd ~ + echo host=localhost >> .splunkrc + echo port=8089 >> .splunkrc + echo username=admin >> .splunkrc + echo password=changed! >> .splunkrc + echo scheme=https >> .splunkrc + echo version=${{ matrix.splunk }} >> .splunkrc + - name: Test using maven + working-directory: ./java + run: make test + env: + SPLUNK_HOME: "/opt/splunk" + TEST_TCP_PORT: 10667 + TEST_UDP_PORT: 10668 diff --git a/java/Makefile b/java/Makefile new file mode 100644 index 0000000..669cff1 --- /dev/null +++ b/java/Makefile @@ -0,0 +1,19 @@ +# ifeq ($(OS), Windows_NT) +# SEPERATOR=; +# else +# SEPERATOR=: +# endif +clean: + mvn clean + +package: + mvn package + +test: + mvn test -fae + +run: + java -classpath './target/classes:./target/lib/*' com.splunk.examples.$(TARGET).Program $(ARGUMENTS) + +test_specific: + @sh ./scripts/test_specific.sh \ No newline at end of file diff --git a/java/pom.xml b/java/pom.xml new file mode 100644 index 0000000..254c42f --- /dev/null +++ b/java/pom.xml @@ -0,0 +1,61 @@ + + 4.0.0 + + com.splunk + examples + 1.0 + + + + com.splunk + splunk + 1.9.4 + + + org.netbeans.api + org-openide-nodes + RELEASE124 + + + org.netbeans.api + org-openide-explorer + RELEASE124 + + + junit + junit + 4.13.1 + test + + + + + + splunk-artifactory + Splunk Releases + https://splunk.jfrog.io/splunk/ext-releases-local + + + + + + + maven-dependency-plugin + + + generate-sources + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + \ No newline at end of file diff --git a/java/scripts/test_specific.sh b/java/scripts/test_specific.sh new file mode 100644 index 0000000..370a239 --- /dev/null +++ b/java/scripts/test_specific.sh @@ -0,0 +1,4 @@ +echo "To run a specific example:" +echo " make run TARGET=[example_name] ARGUMENTS=\"[cli arguments to pass for examples]\"" +echo "For Instance, To run example for searching a particular index execute:" +echo " make run TARGET=search ARGUMENTS=\"'search index=_audit source=audittrail'\"" \ No newline at end of file diff --git a/java/src/main/java/com/splunk/examples/conf/Program.java b/java/src/main/java/com/splunk/examples/conf/Program.java new file mode 100644 index 0000000..858b5df --- /dev/null +++ b/java/src/main/java/com/splunk/examples/conf/Program.java @@ -0,0 +1,48 @@ +package com.splunk.examples.conf; + +import com.splunk.*; + +public class Program { + + private static void list(Service service) { + ConfCollection confs = service.getConfs(); + int count = 0; + for (EntityCollection conf : confs.values()){ + + System.out.println(count++ + " " + conf.getName()); + } + } + + private static void create(Service service, String name){ + ConfCollection confs = service.getConfs(); + if(confs.containsKey(name)){ + Command.error("Conf " + name + " already exists"); + } + confs.create(name); + } + + public static void main(String[] args){ + Command command = Command.splunk("conf").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + if(command.args.length == 0){ + list(service); + return; + } + + if(command.args.length != 2){ + Command.error("Action and conf-name required"); + } + + String action = command.args[0]; + String name = command.args[1]; + + if(action.equals("create")){ + create(service,name); + return; + } + + Command.error("Please enter a valid action"); + } +} diff --git a/java/src/main/java/com/splunk/examples/endpoint_instantiation/Program.java b/java/src/main/java/com/splunk/examples/endpoint_instantiation/Program.java new file mode 100644 index 0000000..58c57c6 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/endpoint_instantiation/Program.java @@ -0,0 +1,62 @@ +/* + * Copyright 2015 Splunk, 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.splunk.examples.endpoint_instantiation; + +import com.splunk.*; + +/** + * This example shows how to access any Splunk REST API endpoint. + * Here, we are just getting an EntityCollection of Entity objects representing + * apps on the Splunk server. + * + * You can also write a class which inherits from the Entity class. + * A minimal example of this is: + * + * public class MyEntity extends Entity { + * MyEntity(Service service, String path) { + * super(service, path); + * } + * } + * + * Then, you can write a class which inherits from the EntityCollection class. + * A minimal example of this is: + * + * public class MyEntityCollection extends EntityCollection { + * MyEntityCollection(Service service) { + * super(service, "path/hardcoded", MyEntity.class, new Args()); + * } + * } + */ + +public class Program { + public static void main(String[] args) { + Command command = Command.splunk("info").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + String mySplunkRESTPath = "apps/local"; + + EntityCollection myCollection = new EntityCollection(service, mySplunkRESTPath, Entity.class, new Args()); + + System.out.println("Found " + myCollection.size() + " Splunk apps:"); + + for (Object myEntity : myCollection.values()) { + Entity entity = (Entity) myEntity; + System.out.println("\t" + entity.getName()); + } + } +} \ No newline at end of file diff --git a/java/src/main/java/com/splunk/examples/explorer/AppNode.java b/java/src/main/java/com/splunk/examples/explorer/AppNode.java new file mode 100644 index 0000000..1d201ad --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/AppNode.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Application; +import com.splunk.Entity; + +class AppNode extends EntityNode { + public AppNode(Entity value) { + super(value); + Application app = (Application)value; + String displayName = app.getLabel(); + if (displayName == null) displayName = app.getName(); + setDisplayName(displayName); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "getCheckForUpdates"); + list.add(String.class, "getLabel"); + list.add(String.class, "getVersion"); + list.add(boolean.class, "isConfigured"); + list.add(boolean.class, "isManageable"); + list.add(boolean.class, "isVisible"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ConfCollectionKids.java b/java/src/main/java/com/splunk/examples/explorer/ConfCollectionKids.java new file mode 100644 index 0000000..7477447 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ConfCollectionKids.java @@ -0,0 +1,44 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.ConfCollection; +import com.splunk.Entity; +import com.splunk.EntityCollection; + +import java.util.Collection; +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +class ConfCollectionKids extends Children.Keys { + ConfCollection confs; + + ConfCollectionKids(ConfCollection confs) { + this.confs = confs; + } + + @Override protected void addNotify() { + Collection> values = confs.values(); + setKeys(values); + } + + @Override protected Node[] createNodes(EntityCollection conf) { + return new Node[] { + new EntityCollectionNode(conf.getTitle(), conf, StanzaNode.class) + }; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ConfCollectionNode.java b/java/src/main/java/com/splunk/examples/explorer/ConfCollectionNode.java new file mode 100644 index 0000000..1224184 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ConfCollectionNode.java @@ -0,0 +1,35 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.ConfCollection; + +// UNDONE: Some duplication of EntityConnectionNode below, eg: title count +// and size property - could probably be refactored into a shared +// CollectionNode base class. +class ConfCollectionNode extends ResourceNode { + ConfCollectionNode(ConfCollection value) { + super(value, new ConfCollectionKids(value)); + setDisplayName(String.format("Configuration (%d)", value.size())); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(int.class, "size"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/DatePropertyEditor.java b/java/src/main/java/com/splunk/examples/explorer/DatePropertyEditor.java new file mode 100644 index 0000000..5011529 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DatePropertyEditor.java @@ -0,0 +1,43 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import java.beans.PropertyEditorSupport; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DatePropertyEditor extends PropertyEditorSupport { + static String datePattern = "MM/dd/yyyy HH:mm:ss"; + static SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); + + @Override public String getAsText() { + Date value = (Date)getValue(); + if (value == null) return "null"; + return dateFormat.format(value); + } + + @Override public void setAsText(String value) { + try { + setValue(dateFormat.parse(value)); + } + catch (ParseException e) { + throw new IllegalArgumentException("Invalid date format"); + } + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/DeploymentClientNode.java b/java/src/main/java/com/splunk/examples/explorer/DeploymentClientNode.java new file mode 100644 index 0000000..dd086b5 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DeploymentClientNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DeploymentClientNode extends EntityNode { + DeploymentClientNode(Entity value) { + super(value); + setDisplayName("Deployment Client"); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getTargetUri"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/DeploymentServerClassNode.java b/java/src/main/java/com/splunk/examples/explorer/DeploymentServerClassNode.java new file mode 100644 index 0000000..8dc4631 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DeploymentServerClassNode.java @@ -0,0 +1,61 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DeploymentServerClassNode extends EntityNode { + DeploymentServerClassNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getBlackList"); + list.add(String.class, "getBlackListDot"); + list.add(String.class, "getBlackList0"); + list.add(String.class, "getBlackList1"); + list.add(String.class, "getBlackList2"); + list.add(String.class, "getBlackList3"); + list.add(String.class, "getBlackList4"); + list.add(String.class, "getBlackList5"); + list.add(String.class, "getBlackList6"); + list.add(String.class, "getBlackList7"); + list.add(String.class, "getBlackList8"); + list.add(String.class, "getBlackList9"); + list.add(boolean.class, "getContinueMatching"); + list.add(String.class, "getEndpoint"); + list.add(String.class, "getFilterType"); + list.add(String.class, "getRepositoryLocation"); + list.add(String.class, "getTargetRepositoryLocation"); + list.add(String.class, "getTmpFolder"); + list.add(String.class, "getWhiteList"); + list.add(String.class, "getWhiteListDot"); + list.add(String.class, "getWhiteList0"); + list.add(String.class, "getWhiteList1"); + list.add(String.class, "getWhiteList2"); + list.add(String.class, "getWhiteList3"); + list.add(String.class, "getWhiteList4"); + list.add(String.class, "getWhiteList5"); + list.add(String.class, "getWhiteList6"); + list.add(String.class, "getWhiteList7"); + list.add(String.class, "getWhiteList8"); + list.add(String.class, "getWhiteList9"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/DeploymentServerNode.java b/java/src/main/java/com/splunk/examples/explorer/DeploymentServerNode.java new file mode 100644 index 0000000..01f0d1c --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DeploymentServerNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DeploymentServerNode extends EntityNode { + DeploymentServerNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "getCheckNew"); + list.add(String.class, "getWhiteList0"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/DeploymentTenantNode.java b/java/src/main/java/com/splunk/examples/explorer/DeploymentTenantNode.java new file mode 100644 index 0000000..3609ad2 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DeploymentTenantNode.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DeploymentTenantNode extends EntityNode { + DeploymentTenantNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + return new PropertyList() {{ + add(boolean.class, "getCheckNew"); + add(String.class, "getWhiteList0"); + }}; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/DistributedConfigurationNode.java b/java/src/main/java/com/splunk/examples/explorer/DistributedConfigurationNode.java new file mode 100644 index 0000000..f3f0a4f --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DistributedConfigurationNode.java @@ -0,0 +1,46 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DistributedConfigurationNode extends EntityNode { + DistributedConfigurationNode(Entity value) { + super(value); + setDisplayName("Distributed Configuration"); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "getAutoAddServers"); + list.add(String[].class, "getBlacklistNames"); + list.add(String[].class, "getBlacklistUrls"); + list.add(int.class, "getCheckTimedOutServersFrequency"); + list.add(int.class, "getHeartbeatFrequency"); + list.add(String.class, "getHeartbeatMcastAddress"); + list.add(int.class, "getHeartbeatPort"); + list.add(boolean.class, "getRemovedTimedOutServers"); + list.add(int.class, "getServerTimeout"); + list.add(String.class, "getServers"); + list.add(boolean.class, "getShareBundles"); + list.add(boolean.class, "getSkipOurselves"); + list.add(int.class, "getStatusTimeout"); + list.add(int.class, "getTtl"); + list.add(boolean.class, "isDisabled"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/DistributedPeerNode.java b/java/src/main/java/com/splunk/examples/explorer/DistributedPeerNode.java new file mode 100644 index 0000000..c2456c3 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/DistributedPeerNode.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class DistributedPeerNode extends EntityNode { + DistributedPeerNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String[].class, "getBundleVersions"); + list.add(String.class, "getGuid"); + list.add(String.class, "getLicenseSignature"); + list.add(String.class, "getPeerName"); + list.add(String.class, "getPeerType"); + list.add(String.class, "getReplicationStatus"); + list.add(String.class, "getStatus"); + list.add(String.class, "getVersion"); + list.add(boolean.class, "isDisabled"); + list.add(boolean.class, "isHttps"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/EntityCollectionNode.java b/java/src/main/java/com/splunk/examples/explorer/EntityCollectionNode.java new file mode 100644 index 0000000..d33fd94 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EntityCollectionNode.java @@ -0,0 +1,84 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; +import com.splunk.EntityCollection; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +// Abstract class that generalizes an explorer node for any EntityCollection +class EntityCollectionNode extends ResourceNode { + Class itemClass; + Constructor itemCtor = null; + + static EntityComparator comparator = new EntityComparator(); + + EntityCollectionNode(String title, EntityCollection value, Class itemClass) + { + super(value, Children.LEAF); + this.itemClass = itemClass; + setDisplayName(String.format("%s (%d)", title, value.size())); + setChildren(new EntityCollectionKids(this)); + } + + Node createKid(Entity entity) { + try { + if (itemCtor == null) + itemCtor = itemClass.getDeclaredConstructor(Entity.class); + return (Node)itemCtor.newInstance(entity); + } + catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + EntityCollection getCollection() { + return (EntityCollection)this.value; + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(int.class, "size"); + return list; + } + + class EntityCollectionKids extends Children.Keys { + EntityCollectionNode parent; + + EntityCollectionKids(EntityCollectionNode parent) { + this.parent = parent; + } + + @Override protected void addNotify() { + Collection values = parent.getCollection().values(); + List list = new ArrayList(values); + Collections.sort(list, comparator); + setKeys(list); + } + + @Override protected Node[] createNodes(Entity entity) { + return new Node[] { parent.createKid(entity) }; + } + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/EntityComparator.java b/java/src/main/java/com/splunk/examples/explorer/EntityComparator.java new file mode 100644 index 0000000..13b8871 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EntityComparator.java @@ -0,0 +1,27 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +import java.util.Comparator; + +class EntityComparator implements Comparator { + public int compare(Entity entity1, Entity entity2) { + return entity1.getName().compareTo(entity2.getName()); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/EntityKids.java b/java/src/main/java/com/splunk/examples/explorer/EntityKids.java new file mode 100644 index 0000000..a9a7623 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EntityKids.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; +import com.splunk.EntityMetadata; + +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +class EntityKids extends Children.Keys { + Entity entity; + + EntityKids(Entity entity) { + this.entity = entity; + } + + @Override protected void addNotify() { + EntityMetadata metadata = entity.getMetadata(); + if (metadata == null) return; + setKeys(new EntityMetadata[] { metadata }); + } + + @Override protected Node[] createNodes(EntityMetadata metadata) { + return new Node[] { new EntityMetadataNode(metadata) }; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/EntityMetadataNode.java b/java/src/main/java/com/splunk/examples/explorer/EntityMetadataNode.java new file mode 100644 index 0000000..9c422d9 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EntityMetadataNode.java @@ -0,0 +1,44 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.EntityMetadata; + +import java.util.Map; + +class EntityMetadataNode extends ExplorerNode { + EntityMetadataNode(EntityMetadata value) { + super(value); + setDisplayName("Metadata"); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "canChangePermissions"); + list.add(boolean.class, "canShareApp"); + list.add(boolean.class, "canShareGlobal"); + list.add(boolean.class, "canShareUser"); + list.add(boolean.class, "canWrite"); + list.add(String.class, "getApp"); + list.add(String.class, "getOwner"); + list.add(Map.class, "getPermissions"); + list.add(String.class, "getSharing"); + list.add(boolean.class, "isModifiable"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/EntityNode.java b/java/src/main/java/com/splunk/examples/explorer/EntityNode.java new file mode 100644 index 0000000..edb47f1 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EntityNode.java @@ -0,0 +1,25 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class EntityNode extends ResourceNode { + EntityNode(Entity value) { + super(value, new EntityKids(value)); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/EventTypeNode.java b/java/src/main/java/com/splunk/examples/explorer/EventTypeNode.java new file mode 100644 index 0000000..827f254 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/EventTypeNode.java @@ -0,0 +1,34 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class EventTypeNode extends EntityNode { + EventTypeNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getDescriptionLabel"); + list.add(int.class, "getPriority"); + list.add(String.class, "getSearch"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/Explorer.java b/java/src/main/java/com/splunk/examples/explorer/Explorer.java new file mode 100644 index 0000000..8e5b3fd --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/Explorer.java @@ -0,0 +1,101 @@ +/* + * Copyright 2011 Splunk, 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. + */ + +// +// The NetBeans tutorial on which this sample is based: +// +// http://blogs.oracle.com/geertjan/entry/netbeans_apis_outside_of_the +// + +package com.splunk.examples.explorer; + +import com.splunk.InputKind; +import com.splunk.Service; + +import java.awt.Dimension; +import java.awt.Toolkit; +import java.beans.PropertyEditorManager; +import java.util.Date; +import java.util.Map; +import javax.swing.JFrame; +import javax.swing.JSplitPane; +import org.openide.explorer.ExplorerManager; +import org.openide.explorer.propertysheet.PropertySheetView; +import org.openide.explorer.view.BeanTreeView; +import org.openide.nodes.AbstractNode; +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +public class Explorer extends JFrame implements ExplorerManager.Provider { + private ExplorerManager manager; + private Children.Array roots; + + static { + // Register property editors for types that dont have a default editor. + PropertyEditorManager.registerEditor( + Date.class, DatePropertyEditor.class); + PropertyEditorManager.registerEditor( + InputKind.class, InputKindPropertyEditor.class); + PropertyEditorManager.registerEditor( + Map.class, MapPropertyEditor.class); + PropertyEditorManager.registerEditor( + String[].class, StringArrayPropertyEditor.class); + } + + Explorer(Service service) { + this.roots = new Children.Array(); + roots.add(new Node[] { new ServiceNode(service) }); + Node root = new AbstractNode(roots); + root.setDisplayName("Root"); // Not visible + this.manager = new ExplorerManager(); + this.manager.setRootContext(root); + initialize(); + } + + public static Explorer create(Service service) { + return new Explorer(service); + } + + public ExplorerManager getExplorerManager() { + return this.manager; + } + + void initialize() { + BeanTreeView left; + left = new BeanTreeView(); + left.setRootVisible(false); + + PropertySheetView right; + right = new PropertySheetView(); + right.setDescriptionAreaVisible(false); + + JSplitPane splitPane; + splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right); + splitPane.setResizeWeight(0.4); + splitPane.setDividerSize(3); + + setTitle("Splunk Explorer"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + getContentPane().add(splitPane); + + // Place the window in a convenient position + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + int width = screenSize.width / 2; + int height = screenSize.height / 2; + setSize(width, height); + setLocation(width / 2, height / 2); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ExplorerNode.java b/java/src/main/java/com/splunk/examples/explorer/ExplorerNode.java new file mode 100644 index 0000000..e63f8d3 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ExplorerNode.java @@ -0,0 +1,45 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import org.openide.nodes.AbstractNode; +import org.openide.nodes.Children; +import org.openide.nodes.Sheet; + +// Abstract node that simplifies the creation of node metadata. +class ExplorerNode extends AbstractNode { + Object value; + + ExplorerNode(Object value) { + super(Children.LEAF); + this.value = value; + } + + ExplorerNode(Object value, Children kids) { + super(kids); + this.value = value; + } + + protected PropertyList getMetadata() { + return new PropertyList(); + } + + @Override protected Sheet createSheet() { + return getMetadata().createSheet(value); + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/GroupNode.java b/java/src/main/java/com/splunk/examples/explorer/GroupNode.java new file mode 100644 index 0000000..93edfd5 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/GroupNode.java @@ -0,0 +1,31 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import org.openide.nodes.AbstractNode; +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +// A simple named container node. +class GroupNode extends AbstractNode { + GroupNode(String name, final Node... kids) { + super(Children.LEAF); + setDisplayName(name); + setChildren(new Children.Array() {{ add(kids); }}); + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/IndexNode.java b/java/src/main/java/com/splunk/examples/explorer/IndexNode.java new file mode 100644 index 0000000..3dcf3c6 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/IndexNode.java @@ -0,0 +1,78 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +import java.util.Date; + +class IndexNode extends EntityNode { + IndexNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "getAssureUTF8"); + list.add(int.class, "getBlockSignSize"); + list.add(String.class, "getBlockSignatureDatabase"); + list.add(String.class, "getColdPath"); + list.add(String.class, "getColdPathExpanded"); + list.add(String.class, "getColdToFrozenDir"); + list.add(String.class, "getColdToFrozenScript"); + list.add(boolean.class, "getCompressRawdata"); + list.add(int.class, "getCurrentDBSizeMB"); + list.add(String.class, "getDefaultDatabase"); + list.add(boolean.class, "getEnableRealtimeSearch"); + list.add(int.class, "getFrozenTimePeriodInSecs"); + list.add(String.class, "getHomePath"); + list.add(String.class, "getHomePathExpanded"); + list.add(String.class, "getIndexThreads"); + list.add(String.class, "getLastInitTime"); + list.add(int.class, "getMaxConcurrentOptimizes"); + list.add(String.class, "getMaxDataSize"); + list.add(int.class, "getMaxHotBuckets"); + list.add(int.class, "getMaxHotIdleSecs"); + list.add(int.class, "getMaxHotIdleSecs"); + list.add(int.class, "getMaxHotSpanSecs"); + list.add(int.class, "getMaxMemMB"); + list.add(int.class, "getMaxMetaEntries"); + list.add(int.class, "getMaxRunningProcessGroups"); + list.add(Date.class, "getMaxTime"); + list.add(int.class, "getMaxTotalDataSizeMB"); + list.add(int.class, "getMaxWarmDBCount"); + list.add(int.class, "getMemPoolMB"); + list.add(String.class, "getMinRawFileSyncSecs"); + list.add(Date.class, "getMinTime"); + list.add(int.class, "getPartialServiceMetaPeriod"); + list.add(int.class, "getQuarantineFutureSecs"); + list.add(int.class, "getQuarantinePastSecs"); + list.add(int.class, "getRawChunkSizeBytes"); + list.add(int.class, "getRotatePeriodInSecs"); + list.add(int.class, "getServiceMetaPeriod"); + list.add(String.class, "getSuppressBannerList"); + list.add(boolean.class, "getSync"); + list.add(boolean.class, "getSyncMeta"); + list.add(String.class, "getThawedPath"); + list.add(String.class, "getThawedPathExpanded"); + list.add(int.class, "getThrottleCheckPeriod"); + list.add(int.class, "getTotalEventCount"); + list.add(boolean.class, "isDisabled"); + list.add(boolean.class, "isInternal"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/InputKindPropertyEditor.java b/java/src/main/java/com/splunk/examples/explorer/InputKindPropertyEditor.java new file mode 100644 index 0000000..3601109 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/InputKindPropertyEditor.java @@ -0,0 +1,28 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.InputKind; + +import java.beans.PropertyEditorSupport; + +public class InputKindPropertyEditor extends PropertyEditorSupport { + @Override public String getAsText() { + InputKind value = (InputKind)getValue(); + return value.toString(); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/InputNode.java b/java/src/main/java/com/splunk/examples/explorer/InputNode.java new file mode 100644 index 0000000..426c90e --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/InputNode.java @@ -0,0 +1,89 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; +import com.splunk.Input; +import com.splunk.InputKind; + +class InputNode extends EntityNode { + InputNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(InputKind.class, "getKind"); + Input input = (Input)value; + InputKind kind = input.getKind(); + if (kind == InputKind.Monitor) { + list.add(int.class, "getFileCount"); + list.add(String.class, "getHost"); + list.add(String.class, "getIndex"); + list.add(int.class, "getRcvBuf"); + } else if (kind == InputKind.Script) { + list.add(String.class, "getGroup"); + list.add(String.class, "getHost"); + list.add(String.class, "getIndex"); + list.add(int.class, "getInterval"); + list.add(int.class, "getRcvBuf"); + } else if (kind == InputKind.Tcp) { + list.add(String.class, "getGroup"); + list.add(String.class, "getHost"); + list.add(String.class, "getIndex"); + list.add(int.class, "getRcvBuf"); + list.add(String.class, "getRestrictToHost"); + } else if (kind == InputKind.TcpSplunk || kind == InputKind.Udp) { + list.add(String.class, "getGroup"); + list.add(String.class, "getHost"); + list.add(String.class, "getIndex"); + list.add(int.class, "getRcvBuf"); + } else if (kind == InputKind.WindowsActiveDirectory) { + list.add(String.class, "getIndex"); + list.add(boolean.class, "getMonitorSubtree"); + } else if (kind == InputKind.WindowsEventLog) { + list.add(String.class, "getHosts"); + list.add(String.class, "getIndex"); + list.add(String[].class, "getLogs"); + list.add(String.class, "getLocalName"); + list.add(String.class, "getLookupHost"); + } else if (kind == InputKind.WindowsPerfmon) { + list.add(String.class, "getIndex"); + list.add(String[].class, "getInstances"); + list.add(int.class, "getInterval"); + list.add(String.class, "getObject"); + } else if (kind == InputKind.WindowsRegistry) { + list.add(boolean.class, "getBaseline"); + list.add(String.class, "getProc"); + list.add(String.class, "getHive"); + list.add(String.class, "getIndex"); + list.add(boolean.class, "getMonitorSubnoes"); + list.add(String.class, "getType"); + } else if (kind == InputKind.WindowsWmi) { + list.add(String.class, "getClasses"); + list.add(String[].class, "getFields"); + list.add(String.class, "getIndex"); + list.add(String[].class, "getInstances"); + list.add(int.class, "getInterval"); + list.add(String.class, "getLookupHost"); + list.add(String.class, "getLocalName"); + list.add(String.class, "getServer"); + list.add(String.class, "getWq1"); + } + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/JobNode.java b/java/src/main/java/com/splunk/examples/explorer/JobNode.java new file mode 100644 index 0000000..5075138 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/JobNode.java @@ -0,0 +1,75 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; +import com.splunk.Job; + +import java.util.Date; + +class JobNode extends EntityNode { + JobNode(Entity value) { + super(value); + Job job = (Job)value; + setDisplayName(job.getTitle()); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(Date.class, "getCursorTime"); + list.add(String.class, "getDelegate"); + list.add(int.class, "getDiskUsage"); + list.add(String.class, "getDispatchState"); + list.add(float.class, "getDoneProgress"); + list.add(int.class, "getDropCount"); + list.add(Date.class, "getEarliestTime"); + list.add(int.class, "getEventAvailableCount"); + list.add(int.class, "getEventCount"); + list.add(int.class, "getEventFieldCount"); + list.add(boolean.class, "getEventIsStreaming"); + list.add(boolean.class, "getEventIsTruncated"); + list.add(String.class, "getEventSearch"); + list.add(String.class, "getEventSorting"); + list.add(String.class, "getKeywords"); + list.add(String.class, "getLabel"); + list.add(Date.class, "getLatestTime"); + list.add(int.class, "getNumPreviews"); + list.add(int.class, "getPriority"); + list.add(String.class, "getRemoteSearch"); + list.add(String.class, "getReportSearch"); + list.add(int.class, "getResultCount"); + list.add(boolean.class, "getResultIsStreaming"); + list.add(int.class, "getResultPreviewCount"); + list.add(float.class, "getRunDuration"); + list.add(int.class, "getScanCount"); + list.add(String.class, "getSearch"); + list.add(String.class, "getSearchLatestTime"); + list.add(String.class, "getSid"); + list.add(int.class, "getStatusBuckets"); + list.add(int.class, "getTtl"); + list.add(boolean.class, "isDone"); + list.add(boolean.class, "isFailed"); + list.add(boolean.class, "isFinalized"); + list.add(boolean.class, "isPaused"); + list.add(boolean.class, "isPreviewEnabled"); + list.add(boolean.class, "isRemoteTimeline"); + list.add(boolean.class, "isSaved"); + list.add(boolean.class, "isSavedSearch"); + list.add(boolean.class, "isZombie"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LicenseGroupNode.java b/java/src/main/java/com/splunk/examples/explorer/LicenseGroupNode.java new file mode 100644 index 0000000..e815bf7 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LicenseGroupNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class LicenseGroupNode extends EntityNode { + LicenseGroupNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String[].class, "getStackIds"); + list.add(boolean.class, "isActive"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LicenseNode.java b/java/src/main/java/com/splunk/examples/explorer/LicenseNode.java new file mode 100644 index 0000000..3f75b1c --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LicenseNode.java @@ -0,0 +1,50 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; +import com.splunk.License; + +import java.util.Date; + +class LicenseNode extends EntityNode { + LicenseNode(Entity value) { + super(value); + License license = (License)value; + String displayName = license.getLabel(); + if (displayName == null) displayName = license.getName(); + setDisplayName(displayName); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(Date.class, "getCreationTime"); + list.add(Date.class, "getExpirationTime"); + list.add(String[].class, "getFeatures"); + list.add(String.class, "getGroupId"); + list.add(String.class, "getLabel"); + list.add(String.class, "getLicenseHash"); + list.add(int.class, "getMaxViolations"); + list.add(long.class, "getQuota"); + list.add(String[].class, "getSourceTypes"); + list.add(String.class, "getStackId"); + list.add(String.class, "getStatus"); + list.add(String.class, "getType"); + list.add(int.class, "getWindowPeriod"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LicensePoolNode.java b/java/src/main/java/com/splunk/examples/explorer/LicensePoolNode.java new file mode 100644 index 0000000..8c3c547 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LicensePoolNode.java @@ -0,0 +1,36 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class LicensePoolNode extends EntityNode { + LicensePoolNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getDescriptionLabel"); + list.add(long.class, "getQuota"); + list.add(String[].class, "getSlaves"); + list.add(long.class, "getSlavesUsageBytes"); + list.add(String.class, "getStackId"); + list.add(long.class, "getUsedBytes"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LicenseSlaveNode.java b/java/src/main/java/com/splunk/examples/explorer/LicenseSlaveNode.java new file mode 100644 index 0000000..6ead584 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LicenseSlaveNode.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class LicenseSlaveNode extends EntityNode { + LicenseSlaveNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getLabel"); + list.add(String[].class, "getPoolIds"); + list.add(String[].class, "getStackIds"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LicenseStackNode.java b/java/src/main/java/com/splunk/examples/explorer/LicenseStackNode.java new file mode 100644 index 0000000..320d01e --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LicenseStackNode.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class LicenseStackNode extends EntityNode { + LicenseStackNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getLabel"); + list.add(long.class, "getQuota"); + list.add(String.class, "getType"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/LoggerNode.java b/java/src/main/java/com/splunk/examples/explorer/LoggerNode.java new file mode 100644 index 0000000..7b7a5a4 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/LoggerNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class LoggerNode extends EntityNode { + LoggerNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getLevel"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/MapPropertyEditor.java b/java/src/main/java/com/splunk/examples/explorer/MapPropertyEditor.java new file mode 100644 index 0000000..d9f8252 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/MapPropertyEditor.java @@ -0,0 +1,27 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import java.beans.PropertyEditorSupport; +import java.util.Map; + +public class MapPropertyEditor extends PropertyEditorSupport { + @Override public String getAsText() { + Map value = (Map)getValue(); + return value.toString(); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/MessageNode.java b/java/src/main/java/com/splunk/examples/explorer/MessageNode.java new file mode 100644 index 0000000..b8cf78b --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/MessageNode.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class MessageNode extends EntityNode { + MessageNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getKey"); + list.add(String.class, "getValue"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/NamespaceKids.java b/java/src/main/java/com/splunk/examples/explorer/NamespaceKids.java new file mode 100644 index 0000000..2126d87 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/NamespaceKids.java @@ -0,0 +1,69 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Service; + +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +class NamespaceKids extends Children.Keys { + Service service; + + NamespaceKids(Service service) { + this.service = service; + } + + @Override protected void addNotify() { + String[] kinds = new String[] { + "confs", + "eventtypes", + "searches", + "jobs", + }; + setKeys(kinds); + } + + private Node createNode(String kind) { + if (kind.equals("confs")) + return new ConfCollectionNode(service.getConfs()); + + if (kind.equals("eventtypes")) + return new EntityCollectionNode( + "EventTypes", + service.getEventTypes(), + EventTypeNode.class); + + if (kind.equals("jobs")) + return new EntityCollectionNode( + "Jobs", + service.getJobs(), + JobNode.class); + + if (kind.equals("searches")) + return new EntityCollectionNode( + "Saved Searches", + service.getSavedSearches(), + SavedSearchNode.class); + + return null; + } + + @Override protected Node[] createNodes(String kind) { + return new Node[] { createNode(kind) }; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/NamespacesKids.java b/java/src/main/java/com/splunk/examples/explorer/NamespacesKids.java new file mode 100644 index 0000000..2f38d14 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/NamespacesKids.java @@ -0,0 +1,91 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Args; +import com.splunk.Service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import org.openide.nodes.AbstractNode; +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +class NamespacesKids extends Children.Keys { + Service service; + + NamespacesKids(Service service) { + this.service = service; + } + + @Override protected void addNotify() { + Set names = service.getApplications().keySet(); + int count = 3 + names.size(); + List keys = new ArrayList(count); + keys.add(""); + keys.add(""); + keys.add(""); + keys.addAll(names); + Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); + setKeys(keys.toArray(new String[count])); + } + + private Node createNode(String name) { + + if (name.equals("")) + return createNode("", "-"); + + if (name.equals("")) + return createNode("", "-"); + // UNDONE: return new GLobalNamespaceNode() + + if (name.equals("")) + return createNode("", "system"); + + if (service.getApplications().get(name).isDisabled()) { + Node node = new AbstractNode(Children.LEAF); + node.setDisplayName(name); + return node; + } + + return createNode(name, name); + } + + private Node createNode(String displayName, String app) { + // Clone the root service, scoped to the requested namespace + Args args = new Args(); + args.put("host", service.getHost()); + args.put("port", service.getPort()); + args.put("scheme", service.getScheme()); + args.put("username", service.getUsername()); + args.put("password", service.getPassword()); + args.put("app", app); + args.put("owner", "-"); + Service scope = Service.connect(args); + + Node node = new ExplorerNode(scope, new NamespaceKids(scope)); + node.setDisplayName(displayName); + return node; + } + + @Override protected Node[] createNodes(String kind) { + return new Node[] { createNode(kind) }; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/NamespacesNode.java b/java/src/main/java/com/splunk/examples/explorer/NamespacesNode.java new file mode 100644 index 0000000..47a9d6a --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/NamespacesNode.java @@ -0,0 +1,26 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Service; + +class NamespacesNode extends ExplorerNode { + NamespacesNode(Service service) { + super(service, new NamespacesKids(service)); + setDisplayName("Namespaces"); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/OutputDefaultNode.java b/java/src/main/java/com/splunk/examples/explorer/OutputDefaultNode.java new file mode 100644 index 0000000..e3e1016 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/OutputDefaultNode.java @@ -0,0 +1,56 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class OutputDefaultNode extends EntityNode { + OutputDefaultNode(Entity value) { + super(value); + setDisplayName("Output Default"); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(boolean.class, "autoLb"); + list.add(boolean.class, "blockOnCloning"); + list.add(boolean.class, "blockOnQueueFull"); + list.add(int.class, "getAutoLbFrequency"); + list.add(int.class, "getConnectionTimeout"); + list.add(String.class, "getDefaultGroup"); + list.add(int.class, "getDropClonedEventsOnQueueFull"); + list.add(int.class, "getDropEventsOnQueueFull"); + list.add(String.class, "getForwardedIndex0Whitelist"); + list.add(String.class, "getForwardedIndex1Blacklist"); + list.add(String.class, "getForwardedIndex2Whitelist"); + list.add(int.class, "getHeartbeatFrequency"); + list.add(int.class, "getMaxConnectionsPerIndexer"); + list.add(int.class, "getMaxFailuresPerInterval"); + list.add(long.class, "getMaxQueueSize"); + list.add(int.class, "getReadTimeout"); + list.add(int.class, "getSecsInFailureInterval"); + list.add(int.class, "getWriteTimeout"); + list.add(boolean.class, "indexAndForward"); + list.add(boolean.class, "isCompressed"); + list.add(boolean.class, "isDisabled"); + list.add(boolean.class, "isForwardedIndexFilterDisable"); + list.add(boolean.class, "isIndexAndForward"); + list.add(boolean.class, "sendCookedData"); + list.add(boolean.class, "useAck"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/OutputGroupNode.java b/java/src/main/java/com/splunk/examples/explorer/OutputGroupNode.java new file mode 100644 index 0000000..b2f2fa3 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/OutputGroupNode.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class OutputGroupNode extends EntityNode { + OutputGroupNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getMethod"); + list.add(String[].class, "getServers"); + list.add(boolean.class, "isDisabled"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/OutputServerNode.java b/java/src/main/java/com/splunk/examples/explorer/OutputServerNode.java new file mode 100644 index 0000000..bcfe41b --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/OutputServerNode.java @@ -0,0 +1,31 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class OutputServerNode extends EntityNode { + OutputServerNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + // UNDONE list.add(Connections[], "allConnections"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/OutputSyslogNode.java b/java/src/main/java/com/splunk/examples/explorer/OutputSyslogNode.java new file mode 100644 index 0000000..792d75c --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/OutputSyslogNode.java @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class OutputSyslogNode extends EntityNode { + OutputSyslogNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getServer"); + list.add(String.class, "getType"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/PasswordNode.java b/java/src/main/java/com/splunk/examples/explorer/PasswordNode.java new file mode 100644 index 0000000..ceae2a8 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/PasswordNode.java @@ -0,0 +1,36 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class PasswordNode extends EntityNode { + PasswordNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getClearPassword"); + list.add(String.class, "getEncryptedPassword"); + list.add(String.class, "getPassword"); + list.add(String.class, "getRealm"); + list.add(String.class, "getUsername"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/Program.java b/java/src/main/java/com/splunk/examples/explorer/Program.java new file mode 100644 index 0000000..311d5a2 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/Program.java @@ -0,0 +1,35 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Service; +import com.splunk.Command; + +import javax.swing.SwingUtilities; + +public class Program { + public static void main(final String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + Command command = Command.splunk("explorer").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + Explorer.create(service).setVisible(true); + } + }); + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/PropertyInfo.java b/java/src/main/java/com/splunk/examples/explorer/PropertyInfo.java new file mode 100644 index 0000000..cc57672 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/PropertyInfo.java @@ -0,0 +1,30 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +public class PropertyInfo { + public Class datatype; + public String getter; + public String setter; + + public PropertyInfo(Class datatype, String getter, String setter) { + this.datatype = datatype; + this.getter = getter; + this.setter = setter; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/PropertyList.java b/java/src/main/java/com/splunk/examples/explorer/PropertyList.java new file mode 100644 index 0000000..c39cff0 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/PropertyList.java @@ -0,0 +1,47 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import java.util.ArrayList; +import org.openide.nodes.PropertySupport; +import org.openide.nodes.Sheet; + +public class PropertyList extends ArrayList { + public void add(Class datatype, String getter) { + add(datatype, getter, null); + } + + public void add(Class datatype, String getter, String setter) { + add(new PropertyInfo(datatype, getter, setter)); + } + + public Sheet createSheet(Object object) { + Sheet sheet = Sheet.createDefault(); + Sheet.Set props = Sheet.createPropertiesSet(); + try { + for (PropertyInfo info : this) { + props.put(new PropertySupport.Reflection( + object, info.datatype, info.getter, info.setter)); + } + } + catch (NoSuchMethodException e) { + throw new RuntimeException(e.getMessage(), e); + } + sheet.put(props); + return sheet; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ResourceNode.java b/java/src/main/java/com/splunk/examples/explorer/ResourceNode.java new file mode 100644 index 0000000..4e80e2a --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ResourceNode.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Resource; + +import org.openide.nodes.Children; + +class ResourceNode extends ExplorerNode { + ResourceNode(Resource value) { + super(value); + setDisplayName(value.getName()); + } + + ResourceNode(Resource value, Children kids) { + super(value, kids); + setDisplayName(value.getName()); + } + + @Override protected PropertyList getMetadata() { + return new PropertyList() {{ + add(String.class, "getPath"); + add(String.class, "getTitle"); + }}; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/RoleNode.java b/java/src/main/java/com/splunk/examples/explorer/RoleNode.java new file mode 100644 index 0000000..890c7c7 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/RoleNode.java @@ -0,0 +1,48 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class RoleNode extends EntityNode { + RoleNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String[].class, "getCapabilities"); + list.add(String.class, "getDefaultApp"); + list.add(String[].class, "getImportedCapabilities"); + list.add(String[].class, "getImportedRoles"); + list.add(int.class, "getImportedRtSearchJobsQuota"); + list.add(int.class, "getImportedSearchDiskQuota"); + list.add(String.class, "getImportedSearchFilter"); + list.add(String[].class, "getImportedIndexesAllowed"); + list.add(String[].class, "getImportedIndexesDefault"); + list.add(int.class, "getImportedSearchJobsQuota"); + list.add(int.class, "getRtSearchJobsQuota"); + list.add(int.class, "getSearchDiskQuota"); + list.add(String.class, "getSearchFilter"); + list.add(String[].class, "getSearchIndexesAllowed"); + list.add(String[].class, "getSearchIndexesDefault"); + list.add(int.class, "getSearchJobsQuota"); + list.add(int.class, "getSearchTimeWin"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/SavedSearchNode.java b/java/src/main/java/com/splunk/examples/explorer/SavedSearchNode.java new file mode 100644 index 0000000..ebff860 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/SavedSearchNode.java @@ -0,0 +1,73 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class SavedSearchNode extends EntityNode { + SavedSearchNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getActionEmailSendResults"); + list.add(String.class, "getActionEmailTo"); + list.add(String.class, "getAlertExpires"); + list.add(int.class, "getAlertSeverity"); + list.add(String.class, "getAlertSuppress"); + list.add(String.class, "getAlertSuppressPeriod"); + list.add(String.class, "getAlertTrack"); + list.add(String.class, "getAlertComparator"); + list.add(String.class, "getAlertCondition"); + list.add(String.class, "getAlertThreshold"); + list.add(String.class, "getAlertType"); + list.add(String.class, "getCronSchedule"); + list.add(String.class, "getDescriptionLabel"); + list.add(int.class, "getDispatchBuckets"); + list.add(String.class, "getDispatchEarliestTime"); + list.add(String.class, "getDispatchLatestTime"); + list.add(boolean.class, "getDispatchLookups"); + list.add(int.class, "getDispatchMaxCount"); + list.add(String.class, "getDispatchMaxTime"); + list.add(int.class, "getDispatchReduceFreq"); + list.add(boolean.class, "getDispatchSpawnProcess"); + list.add(String.class, "getDispatchTimeFormat"); + list.add(String.class, "getDispatchTtl"); + list.add(String.class, "getDisplayView"); + list.add(int.class, "getMaxConcurrent"); + list.add(String.class, "getNextScheduledTime"); + list.add(String.class, "getQualifiedSearch"); + list.add(boolean.class, "getRealtimeSchedule"); + list.add(String.class, "getRequestUiDispatchApp"); + list.add(String.class, "getRequestUiDispatchView"); + list.add(boolean.class, "getRestartOnSearchPeerAdd"); + list.add(boolean.class, "getRunOnStartup"); + list.add(String.class, "getSearch"); + list.add(String.class, "getVsid"); + list.add(boolean.class, "isActionEmail"); + list.add(boolean.class, "isActionPopulateLookup"); + list.add(boolean.class, "isActionRss"); + list.add(boolean.class, "isActionScript"); + list.add(boolean.class, "isActionSummaryIndex"); + list.add(boolean.class, "isDigestMode"); + list.add(boolean.class, "isDisabled"); + list.add(boolean.class, "isScheduled"); + list.add(boolean.class, "isVisible"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ServiceKids.java b/java/src/main/java/com/splunk/examples/explorer/ServiceKids.java new file mode 100644 index 0000000..87876d2 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ServiceKids.java @@ -0,0 +1,138 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Service; + +import org.openide.nodes.Children; +import org.openide.nodes.Node; + +class ServiceKids extends Children.Keys { + Service service; + + ServiceKids(Service service) { + this.service = service; + } + + @Override protected void addNotify() { + String[] kinds = new String[] { + "system", + "indexes", + "inputs", + "outputs", + "namespaces", + }; + setKeys(kinds); + } + + private Node createNode(String kind) { + if (kind.equals("indexes")) + return new EntityCollectionNode( + "Indexes", + service.getIndexes(), + IndexNode.class); + + if (kind.equals("inputs")) + return new EntityCollectionNode( + "Inputs", + service.getInputs(), + InputNode.class); + + if (kind.equals("namespaces")) + return new NamespacesNode(service); + + if (kind.equals("outputs")) + return new GroupNode( + "Outputs", + new OutputDefaultNode(service.getOutputDefault()), + new EntityCollectionNode( + "Output Groups", + service.getOutputGroups(), + OutputGroupNode.class), + new EntityCollectionNode( + "Output Servers", + service.getOutputServers(), + OutputServerNode.class), + new EntityCollectionNode( + "Output Syslogs", + service.getOutputSyslogs(), + OutputSyslogNode.class)); + + if (kind.equals("system")) + return new GroupNode( + "System", + new SettingsNode(service.getSettings()), + new EntityCollectionNode( + "Loggers", service.getLoggers(), LoggerNode.class), + new EntityCollectionNode( + "Messages", service.getMessages(), MessageNode.class), + new GroupNode( + "Deployment", + new DistributedConfigurationNode( + service.getDistributedConfiguration()), + new EntityCollectionNode( + "Distributed Peers", + service.getDistributedPeers(), + DistributedPeerNode.class), + new DeploymentClientNode( + service.getDeploymentClient()), + new EntityCollectionNode( + "Deployment Servers", + service.getDeploymentServers(), + DeploymentServerNode.class), + new EntityCollectionNode( + "Deployment Server Classes", + service.getDeploymentServerClasses(), + DeploymentServerClassNode.class), + new EntityCollectionNode( + "Deployment Tenants", + service.getDeploymentTenants(), + DeploymentTenantNode.class)), + new GroupNode( + "Licensing", + new EntityCollectionNode( + "Licenses", + service.getLicenses(), + LicenseNode.class), + new EntityCollectionNode( + "License Pools", + service.getLicensePools(), + LicensePoolNode.class), + new EntityCollectionNode( + "License Groups", + service.getLicenseGroups(), + LicenseGroupNode.class), + new EntityCollectionNode( + "License Slaves", + service.getLicenseSlaves(), + LicenseSlaveNode.class), + new EntityCollectionNode( + "License Stacks", + service.getLicenseStacks(), + LicenseStackNode.class)), + new EntityCollectionNode( + "Roles", service.getRoles(), RoleNode.class), + new EntityCollectionNode( + "Users", service.getUsers(), UserNode.class)); + + return null; + } + + @Override protected Node[] createNodes(String kind) { + return new Node[] { createNode(kind) }; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/ServiceNode.java b/java/src/main/java/com/splunk/examples/explorer/ServiceNode.java new file mode 100644 index 0000000..6d6aaa9 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/ServiceNode.java @@ -0,0 +1,44 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Service; + +class ServiceNode extends ExplorerNode { + ServiceNode(Service service) { + super(service.getInfo(), new ServiceKids(service)); + setDisplayName(service.getInfo().getServerName()); + } + + @Override protected PropertyList getMetadata() { + return new PropertyList() {{ + add(int.class, "getBuild"); + add(String.class, "getCpuArch"); + add(String[].class, "getLicenseKeys"); + add(String.class, "getLicenseSignature"); + add(String.class, "getLicenseState"); + add(String.class, "getMasterGuid"); + add(String.class, "getMode"); + add(String.class, "getOsBuild"); + add(String.class, "getOsVersion"); + add(String.class, "getServerName"); + add(String.class, "getVersion"); + add(boolean.class, "isFree"); + add(boolean.class, "isTrial"); + }}; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/SettingsNode.java b/java/src/main/java/com/splunk/examples/explorer/SettingsNode.java new file mode 100644 index 0000000..aaa0f79 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/SettingsNode.java @@ -0,0 +1,43 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class SettingsNode extends EntityNode { + SettingsNode(Entity value) { + super(value); + setDisplayName("Settings"); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getSplunkDB"); + list.add(String.class, "getSplunkHome"); + list.add(boolean.class, "getEnableSplunkWebSSL"); + list.add(String.class, "getHost"); + list.add(int.class, "getHttpPort"); + list.add(int.class, "getMgmtPort"); + list.add(int.class, "getMinFreeSpace"); + list.add(String.class, "getPass4SymmKey"); + list.add(String.class, "getServerName"); + list.add(String.class, "getSessionTimeout"); + list.add(boolean.class, "getStartWebServer"); + list.add(String.class, "getTrustedIP"); + return list; + } +} diff --git a/java/src/main/java/com/splunk/examples/explorer/StanzaNode.java b/java/src/main/java/com/splunk/examples/explorer/StanzaNode.java new file mode 100644 index 0000000..cf204e6 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/StanzaNode.java @@ -0,0 +1,65 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +import org.openide.nodes.PropertySupport; +import org.openide.nodes.Sheet; + +class StanzaNode extends EntityNode { + StanzaNode(Entity value) { + super(value); + setDisplayName(value.getName()); + } + + // Implement createSheet directly in order to dynamically construct + // based on the contents of the stanza. + @Override protected Sheet createSheet() { + Entity entity = (Entity)value; + Sheet.Set props = Sheet.createPropertiesSet(); + for (String key : entity.keySet()) { + if (key.equals("eai:acl") || key.equals("eai:attributes")) + continue; + props.put(new StanzaProperty(entity, key)); + } + Sheet sheet = Sheet.createDefault(); + sheet.put(props); + return sheet; + } + + // This should never be called because we implement createSheet directly. + @Override protected PropertyList getMetadata() { + throw new UnsupportedOperationException(); + } + + class StanzaProperty extends PropertySupport.ReadOnly { + private String key; + private Entity stanza; + + StanzaProperty(Entity stanza, String key) { + super(key, String.class, key, null); + this.key = key; + this.stanza = stanza; + } + + @Override public String getValue() { + return (String)stanza.get(key); + } + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/StringArrayPropertyEditor.java b/java/src/main/java/com/splunk/examples/explorer/StringArrayPropertyEditor.java new file mode 100644 index 0000000..9cf9cc8 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/StringArrayPropertyEditor.java @@ -0,0 +1,33 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import java.beans.PropertyEditorSupport; +import java.util.Arrays; + +public class StringArrayPropertyEditor extends PropertyEditorSupport { + @Override public String getAsText() { + String[] value = (String[])getValue(); + if (value == null) return "null"; + return Arrays.toString(value); + } + + @Override public void setAsText(String value) { + throw new UnsupportedOperationException(); + } +} + diff --git a/java/src/main/java/com/splunk/examples/explorer/UserNode.java b/java/src/main/java/com/splunk/examples/explorer/UserNode.java new file mode 100644 index 0000000..9801b9d --- /dev/null +++ b/java/src/main/java/com/splunk/examples/explorer/UserNode.java @@ -0,0 +1,38 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.explorer; + +import com.splunk.Entity; + +class UserNode extends EntityNode { + UserNode(Entity value) { + super(value); + } + + @Override protected PropertyList getMetadata() { + PropertyList list = super.getMetadata(); + list.add(String.class, "getDefaultApp"); + list.add(boolean.class, "getDefaultAppIsUserOverride"); + list.add(String.class, "getDefaultAppSourceRole"); + list.add(String.class, "getEmail"); + list.add(String.class, "getPassword"); + list.add(String.class, "getRealName"); + list.add(String[].class, "getRoles"); + return list; + } +} + diff --git a/java/src/main/java/com/splunk/examples/export/Program.java b/java/src/main/java/com/splunk/examples/export/Program.java new file mode 100644 index 0000000..81383a6 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/export/Program.java @@ -0,0 +1,348 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.export; + +import com.splunk.*; + +import java.nio.channels.FileChannel; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.RandomAccessFile; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; + +/** + * Export.java: export an splunk entire index in XML, CSV or JSON (4.3+). The + * return data is in strict descending time order. + */ + +// In recover mode, we will duplicate messages and meta data; however, +// this is not necessarily incorrect, just redundant information. + +public class Program { + + static String lastTime; + static int nextEventOffset; + + static public void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static Map getStartNextCSVEvent(int location, String str) { + + Map pair = new HashMap(); + pair.put("start", -1); + pair.put("end", -1); + + int eventStart = str.indexOf("\n", location) + 1; + int eventEnd = str.indexOf("\"\n", eventStart + 1); + + while (eventEnd > 0) { + String substring = str.substring(eventStart, eventEnd); + String [] parts = substring.split(","); + // Test parts 0 and 1 of the CSV, for and time.qqq stamp + try { + Integer.parseInt(parts[0]); + String timestamp = parts[1].replace("\"",""); + String [] timeparts = timestamp.split("\\."); + Integer.parseInt(timeparts[0]); + Integer.parseInt(timeparts[1]); + pair.put("start", eventStart); + pair.put("end", eventEnd); + return pair; + } + catch (Exception e) { + // If any of the fields accessed caused an exception, then + // we didn't have a valid start of event, so try again. + eventStart = str.indexOf("\n", eventEnd + 2); + eventEnd = str.indexOf("\"\n", eventStart + 1); + } + } + return pair; + } + + static int getCsvEventStart(String str) { + + Mappair = getStartNextCSVEvent(0, str); + if (pair.get("start")< 0) + return -1; + + lastTime = str.substring(pair.get("start")) + .split(",")[1] + .replace("\"",""); + nextEventOffset = pair.get("end"); + + // Walk through events until time changes. + while (pair.get("end") > 0) { + pair = getStartNextCSVEvent(pair.get("start"), str); + if (pair.get("end") < 0) + return -1; + String time = str.substring(pair.get("start"), pair.get("end")) + .split(",")[1] + .replace("\"", ""); + if (!time.equals(lastTime)) { + return pair.get("start"); + } + nextEventOffset = pair.get("end") + 1; + } + + return -1; + } + + static int getXmlEventStart(String str) { + String resultPattern = ""; + String timeStartPattern = ""; + String timeEndPattern = "<"; + String eventEndPattern = ""; + + // Get first event in this buffer. If no event end kick back + int eventStart = str.indexOf(resultPattern); + int eventEnd = str.indexOf(eventEndPattern, eventStart) + + eventEndPattern.length(); + if (eventEnd < 0) + return -1; + int timeKeyStart = str.indexOf(timeKeyPattern, eventStart); + int timeStart = str.indexOf(timeStartPattern, timeKeyStart) + + timeStartPattern.length(); + int timeEnd = str.indexOf(timeEndPattern, timeStart+1); + lastTime = str.substring(timeStart, timeEnd); + + nextEventOffset = eventEnd; + + // Walk through events until time changes + eventStart = eventEnd; + while (eventEnd > 0) { + eventStart = str.indexOf(resultPattern, eventStart+1); + eventEnd = str.indexOf(eventEndPattern, eventStart) + + eventEndPattern.length(); + if (eventEnd < 0) + return -1; + timeKeyStart = str.indexOf(timeKeyPattern, eventStart); + timeStart = str.indexOf(timeStartPattern, timeKeyStart); + timeEnd = str.indexOf(timeEndPattern, timeStart); + String time = str.substring(timeStart, timeEnd); + if (!time.equals(lastTime)) { + return eventStart; + } + nextEventOffset = eventEnd; + eventStart = eventEnd; + } + + return -1; + } + + static int getJsonEventStart(String str) { + + String timeKeyPattern = "\"_time\":\""; + String timeEndPattern = "\""; + String eventEndPattern = "\"},\n"; + String eventEndPattern2 = "\"}[]"; // Old json output format bug + + // Get first event in this buffer. If no event end kick back. + int eventStart = str.indexOf("{\"_cd\":\""); + int eventEnd = str.indexOf(eventEndPattern, eventStart) + + eventEndPattern.length(); + if (eventEnd < 0) + eventEnd = str.indexOf(eventEndPattern2, eventStart) + + eventEndPattern2.length(); + if (eventEnd < 0) + return -1; + + int timeStart = str.indexOf(timeKeyPattern, eventStart) + + timeKeyPattern.length(); + int timeEnd = str.indexOf(timeEndPattern, timeStart+1); + lastTime = str.substring(timeStart, timeEnd); + nextEventOffset = eventEnd; + + // Walk through events until time changes. + eventStart = eventEnd; + while (eventEnd > 0) { + eventStart = str.indexOf("{\"_cd\":\"", eventStart+1); + eventEnd = str.indexOf(eventEndPattern, eventStart) + + eventEndPattern.length(); + if (eventEnd < 0) + eventEnd = str.indexOf(eventEndPattern2, eventStart) + + eventEndPattern2.length(); + if (eventEnd < 0) + return -1; + + timeStart = str.indexOf(timeKeyPattern, eventStart) + + timeKeyPattern.length(); + timeEnd = str.indexOf(timeEndPattern, timeStart+1); + String time = str.substring(timeStart, timeEnd); + if (!time.equals(lastTime)) { + return eventStart; + } + nextEventOffset = eventEnd-2; + eventStart = eventEnd; + } + + return -1; + } + + static int getEventStart(byte[] buffer, String format) + throws Exception { + + String str = new String(buffer); + if (format.equals("csv")) + return getCsvEventStart(str); + else if (format.equals("xml")) + return getXmlEventStart(str); + else + return getJsonEventStart(str); + } + + static void cleanupTail(Writer out, String format) throws Exception { + if (format.equals("csv")) + out.write("\n"); + else if (format.equals("xml")) + out.write("\n\n"); + else + out.write("\n]\n"); + } + + static void run(String[] argv) throws Exception { + Command command = Command.splunk("export"); + command.addRule("search", String.class, "Search string to export"); + + command.parse(argv); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + Args args = new Args(); + final String outFilename = "export.out"; + boolean recover = false; + boolean addEndOfLine = false; + String format = "csv"; // default to csv + + // This example takes optional arguments: + // + // index-name [recover] [csv|xml|json] + // + // N.B. json output only valid with 4.3+ + + String indexName = null; + if (command.args.length == 0) { + System.out.println("Exporting main index"); + indexName = "main"; + } else + indexName = command.args[0]; + + if (command.args.length > 1) { + for (int index=1; index < command.args.length; index++) { + if (command.args[index].equals("recover")) + recover = true; + else if (command.args[index].equals("csv")) + format = "csv"; + else if (command.args[index].equals("xml")) + format = "xml"; + else if (command.args[index].equals("json")) + format = "json"; + else + throw new Error("Unknown option: " + command.args[index]); + } + } + + File file = new File(outFilename); + if (file.exists() && file.isFile() && !recover) + throw new Error("Export file exists, and no recover option"); + + if (recover && file.exists() && file.isFile()) { + // Chunk backwards through the file until we find valid + // start time. If we can't find one just start over. + final int bufferSize = (64*1024); + RandomAccessFile raf = new RandomAccessFile(file, "rw"); + long fptr = Math.max(file.length() - bufferSize, 0); + long fptrEof = 0; + + while (fptr > 0) { + byte [] buffer = new byte[bufferSize]; + raf.seek(fptr); + raf.read(buffer, 0, bufferSize); + int eventStart = getEventStart(buffer, format); + if (eventStart != -1) { + fptrEof = nextEventOffset + fptr; + break; + } + fptr = fptr - bufferSize; + } + + if (fptr < 0) + fptrEof = 0; // We didn't find a valid event, so start over. + else + args.put("latest_time", lastTime); + addEndOfLine = true; + + FileChannel fc = raf.getChannel(); + fc.truncate(fptrEof); + } else + if (!file.createNewFile()) + throw new Error("Failed to create output file"); + + // Search args + args.put("timeout", "60"); // Don't keep search around + args.put("output_mode", format); // Output in specific format + args.put("earliest_time", "0.000"); // Always to beginning of index + args.put("time_format", "%s.%Q"); // Epoch time plus fraction + String search = null; + + if (command.opts.containsKey("search")) { + search = (String)command.opts.get("search"); + } + else { + search = String.format("search index=%s *", indexName); + } + + InputStream is = service.export(search, args); + + // Use UTF8 sensitive reader/writers + InputStreamReader isr = new InputStreamReader(is, "UTF-8"); + FileOutputStream os = new FileOutputStream(file, true); + Writer out = new OutputStreamWriter(os, "UTF-8"); + + // Read/write 8k at a time if possible + char [] xferBuffer = new char[8192]; + boolean once = true; + + // If superfluous meta-data is not needed, or specifically + // wants to be removed, one would clean up the first read + // buffer on a format by format basis, + while (true) { + if (addEndOfLine && once) { + cleanupTail(out, format); + once = false; + } + int bytesRead = isr.read(xferBuffer); + if (bytesRead == -1) break; + out.write(xferBuffer, 0, bytesRead); + } + + isr.close(); + out.close(); + } +} diff --git a/java/src/main/java/com/splunk/examples/fluent_pivot/Program.java b/java/src/main/java/com/splunk/examples/fluent_pivot/Program.java new file mode 100644 index 0000000..5597137 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/fluent_pivot/Program.java @@ -0,0 +1,86 @@ +/* + * Copyright 2014 Splunk, 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.splunk.examples.fluent_pivot; + +import com.splunk.*; + +public class Program { + public static void main(String[] argv) { + try { + run(argv); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] argsIn) throws Exception { + Command command; + Service service; + Service.setValidateCertificates(false); + + command = Command.splunk("input"); + service = Service.connect(command.opts); + + + DataModel dataModel = service.getDataModels().get("internal_audit_logs"); + DataModelObject searches = dataModel.getObject("searches"); + + System.out.print("Working with object " + searches.getDisplayName()); + System.out.println(" in model " + dataModel.getDisplayName()); + System.out.print(" Lineage: "); + for (String name : searches.getLineage()) { + System.out.print(" -> " + name); + } + System.out.println(); + System.out.println(" Internal name: " + searches.getName()); + + Job firstFiveEntries = searches.runQuery("| head 5"); + while (!firstFiveEntries.isDone()) { + Thread.sleep(100); + } + + ResultsReaderXml results = new ResultsReaderXml(firstFiveEntries.getResults()); + for (Event event : results) { + System.out.println(event.toString()); + } + + System.out.println("~~~~~~~~~~~~~~~~~~~~"); + System.out.println("Pivoting on searches"); + + Pivot pivot = searches.createPivotSpecification(). + addRowSplit("user", "Executing user"). + addColumnSplit("exec_time", null, null, null, 4). + addCellValue("search", "Search Query", StatsFunction.DISTINCT_VALUES). + pivot(); + + System.out.println("Query for binning search queries by execution time and executing user:"); + System.out.println(" " + pivot.getPrettyQuery()); + + Job pivotJob = pivot.run(); + while (!pivotJob.isDone()) { + Thread.sleep(100); + } + + results = new ResultsReaderXml(pivotJob.getResults()); + for (Event event : results) { + System.out.println(event.toString()); + } + } +} + + diff --git a/java/src/main/java/com/splunk/examples/genevents/Program.java b/java/src/main/java/com/splunk/examples/genevents/Program.java new file mode 100644 index 0000000..b43923b --- /dev/null +++ b/java/src/main/java/com/splunk/examples/genevents/Program.java @@ -0,0 +1,166 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.genevents; + +import com.splunk.*; + +import java.io.*; +import java.net.Socket; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + * Generate events into an index using either stream, submit or raw tcp + * methods. + */ + +public class Program { + + static String indexName = + "Name of index to send events to. If unspecified, 'default' is used"; + static int ingestPort = 9002; + static String ingestMethod = + "Ingest events via method {stream, submit, tcp} (default: stream)"; + static String tcpPort = + String.format("Input port for tcp ingest (default: %d)", ingestPort); + static SimpleDateFormat dateFormat = + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static String makeEvent(String stamp, int i, int j) { + return String.format("%s: event bunch %d, number %d\n", stamp, i, j); + } + + static void buildRules(Command command, String[] argsIn) { + command.addRule("index", String.class, indexName); + command.addRule("itype", String.class, ingestMethod); + command.addRule("iport", String.class, tcpPort); + command.parse(argsIn); + } + + static void run(String[] argsIn) throws Exception { + + Command command; + int count; + Index index = null; + String ingest; + String iname; + List ingestTypes = Arrays.asList("submit", "stream", "tcp"); + OutputStream ostream; + Receiver receiver = null; + Service service; + Socket stream = null; + Writer writerOut = null; + + command = Command.splunk("genevents"); + buildRules(command, argsIn); + Service.setValidateCertificates(false); + service = Service.connect(command.opts); + + // Determine ingest method and other input arguments. + iname = null; + ingest = "stream"; + if (command.opts.containsKey("index")) { + iname = (String)command.opts.get("index"); + } + if (command.opts.containsKey("itype")) + ingest = (String)command.opts.get("itype"); + if (command.opts.containsKey("iport")) { + ingestPort = Integer.parseInt((String)command.opts.get("iport")); + } + + // Validate + if (!ingestTypes.contains(ingest)) { + Command.error("Method '"+ingest+"' must be in set: "+ingestTypes); + } + + if (iname != null) { + index = service.getIndexes().get(iname); + if (index == null) { + Command.error("Index '" + iname + "' was not found."); + } + } else { + receiver = service.getReceiver(); + } + + + // For stream and tcp, they both require a socket, though setup + // slightly differently. + if (ingest.equals("stream") || ingest.equals("tcp")) { + if (ingest.equals("stream")) + try { + // A specific index or not? + if (iname != null) + stream = index.attach(); + else + stream = receiver.attach(); + } + catch (NullPointerException e) { + System.out.println("Failed to attach to index."); + System.exit(3); + } + else { + // Create a tcp input if one does not already exist. + String inputName = String.valueOf(ingestPort); + TcpInput tcpInput = (TcpInput)service.getInputs().get(inputName); + if (tcpInput == null) { + tcpInput = (TcpInput)service.getInputs().create( + inputName, InputKind.Tcp); + } + stream = tcpInput.attach(); + } + ostream = stream.getOutputStream(); + writerOut = new OutputStreamWriter(ostream, "UTF-8"); + } + + // Generate 10 batches of 5000 events each. + count = 0; + for (int i=0; i<10; i++) { + for (int j=0; j<5000; j++) { + Date date = new Date(); + String lastEvent = makeEvent(dateFormat.format(date), i, j); + if (ingest.equals("stream") || ingest.equals("tcp")) + writerOut.write(lastEvent); + else + if (iname != null) + index.submit(lastEvent); + else + receiver.submit(lastEvent); + count++; + } + System.out.println("Submitted "+count+" events, using "+ingest); + } + + // Flush and close stream on completion + if (ingest.equals("stream") || ingest.equals("tcp")) { + writerOut.flush(); + writerOut.close(); + stream.close(); + } + } +} diff --git a/java/src/main/java/com/splunk/examples/get_job/Program.java b/java/src/main/java/com/splunk/examples/get_job/Program.java new file mode 100644 index 0000000..021266b --- /dev/null +++ b/java/src/main/java/com/splunk/examples/get_job/Program.java @@ -0,0 +1,54 @@ +/* + * Copyright 2015 Splunk, 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.splunk.examples.get_job; + +import com.splunk.*; + +/** + * This example shows a better way to retrieve a Job by its sid + * using the new getJob() method. + * + * Previously, the only way to do this would be the following: + * + * Job job = service.getJobs().get(sid); + * + * The above has a significant overhead of getting all search jobs from + * the Splunk REST API in order to get a single Job. + * + */ + +public class Program { + public static void main(String[] args) { + Command command = Command.splunk("info").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + String sid = service.search("search index=_internal | head 5").getSid(); + Job job = service.getJob(sid); + + while (!job.isDone()) { + job.refresh(); + try { + Thread.sleep(1000); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + + System.out.println("Number of events found: " + job.getEventCount()); + } +} \ No newline at end of file diff --git a/java/src/main/java/com/splunk/examples/index/Program.java b/java/src/main/java/com/splunk/examples/index/Program.java new file mode 100644 index 0000000..c5da269 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/index/Program.java @@ -0,0 +1,88 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.index; + +import com.splunk.EntityCollection; +import com.splunk.Index; +import com.splunk.Service; +import com.splunk.Command; +import com.splunk.SplunkException; + +public class Program { + private static void list(Service service) { + EntityCollection indexes = service.getIndexes(); + for (Index entity: indexes.values()) { + System.out.println( + entity.getTitle() + + " (" + entity.get("totalEventCount") + ")"); + } + } + + public static void main(String[] args) { + Command command = Command.splunk("index").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // This example takes optional arguments: + // [action index-name] + // + // without cli arguments, all indexes and their totalEventCount + // is displayed + + if (command.args.length == 0) { + list(service); + return; + } + + if (command.args.length != 2) + Command.error("Action and index-name required"); + + String action = command.args[0]; + String name = command.args[1]; + + EntityCollection indexes = service.getIndexes(); + if (action.equals("create")) { + if (indexes.containsKey(name)) + Command.error("Index " + name + " already exists"); + indexes.create(name); + return; + } + + Index index = indexes.get(name); + if (index == null) + Command.error("Index '" + name + "' does not exists"); + + if (action.equals("clean")) { + try { + index.clean(180); // Timeout after 3 minutes. + } catch (SplunkException e) { + if (e.getCode() == SplunkException.INTERRUPTED) { + // User pressed Ctrl-C + return; + } else { + throw e; + } + } + } + else if (action.equals("disable")) + index.disable(); + else if (action.equals("enable")) + index.enable(); + else + Command.error("Unknown action '" + action + "'"); + } +} diff --git a/java/src/main/java/com/splunk/examples/info/Program.java b/java/src/main/java/com/splunk/examples/info/Program.java new file mode 100644 index 0000000..57e0deb --- /dev/null +++ b/java/src/main/java/com/splunk/examples/info/Program.java @@ -0,0 +1,37 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.info; + +import com.splunk.*; + +public class Program { + public static void main(String[] args) { + Command command = Command.splunk("info").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + ServiceInfo info = service.getInfo(); + System.out.println("Info:"); + for (String key : info.keySet()) + System.out.println(" " + key + ": " + info.get(key)); + + Entity settings = service.getSettings(); + System.out.println("\nSettings:"); + for (String key : settings.keySet()) + System.out.println(" " + key + ": " + settings.get(key)); + } +} diff --git a/java/src/main/java/com/splunk/examples/input/Program.java b/java/src/main/java/com/splunk/examples/input/Program.java new file mode 100644 index 0000000..3ae0cfa --- /dev/null +++ b/java/src/main/java/com/splunk/examples/input/Program.java @@ -0,0 +1,263 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.input; + +import com.splunk.*; + +/** + * Generate events into an index using either stream, submit or raw tcp + * methods. + */ + +public class Program { + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void DisplaySpecificInput(Input input) { + InputKind inputKind = input.getKind(); + + System.out.println(" **type specific settings"); + + if (inputKind == InputKind.Monitor) { + MonitorInput monitorInput = (MonitorInput) input; + System.out.println( + " file count: " + monitorInput.getFileCount()); + System.out.println( + " host: " + monitorInput.getHost()); + System.out.println( + " index: " + monitorInput.getIndex()); + System.out.println( + " receive buffer: " + monitorInput.getRcvBuf()); + } else if (inputKind == InputKind.Script) { + ScriptInput scriptInput = (ScriptInput) input; + System.out.println( + " group: " + scriptInput.getGroup()); + System.out.println( + " host: " + scriptInput.getHost()); + System.out.println( + " index: " + scriptInput.getIndex()); + System.out.println( + " interval: " + scriptInput.getInterval()); + System.out.println( + " receive buffer: " + scriptInput.getRcvBuf()); + } else if (inputKind == InputKind.Tcp) { + TcpInput tcpInput = (TcpInput) input; + System.out.println( + " connection host: " + tcpInput.getConnectionHost()); + System.out.println( + " group: " + tcpInput.getGroup()); + System.out.println( + " host: " + tcpInput.getHost()); + System.out.println( + " index: " + tcpInput.getIndex()); + System.out.println( + " queue: " + tcpInput.getQueue()); + System.out.println( + " receive buffer: " + tcpInput.getRcvBuf()); + System.out.println( + " restrict to host:" + tcpInput.getRestrictToHost()); + System.out.println( + " source: " + tcpInput.getSource()); + System.out.println( + " source type: " + tcpInput.getSourceType()); + System.out.println( + " SSL: " + tcpInput.getSSL()); + } else if (inputKind == InputKind.TcpSplunk) { + TcpSplunkInput tcpSplunkInput = (TcpSplunkInput) input; + System.out.println( + " connection host: " + tcpSplunkInput.getConnectionHost()); + System.out.println( + " group: " + tcpSplunkInput.getGroup()); + System.out.println( + " host: " + tcpSplunkInput.getHost()); + System.out.println( + " index: " + tcpSplunkInput.getIndex()); + System.out.println( + " queue: " + tcpSplunkInput.getQueue()); + System.out.println( + " receive buffer: " + tcpSplunkInput.getRcvBuf()); + System.out.println( + " source: " + tcpSplunkInput.getSource()); + System.out.println( + " source type: " + tcpSplunkInput.getSourceType()); + System.out.println( + " SSL: " + tcpSplunkInput.getSSL()); + } else if (inputKind == InputKind.Udp) { + UdpInput udpInput = (UdpInput) input; + System.out.println( + " connection host: " + udpInput.getConnectionHost()); + System.out.println( + " group: " + udpInput.getGroup()); + System.out.println( + " host: " + udpInput.getHost()); + System.out.println( + " index: " + udpInput.getIndex()); + System.out.println( + " queue: " + udpInput.getQueue()); + System.out.println( + " receive buffer: " + udpInput.getRcvBuf()); + System.out.println( + " source: " + udpInput.getSource()); + System.out.println( + " source type: " + udpInput.getSourceType()); + System.out.println( + " no timestamp append:" + + udpInput.getNoAppendingTimeStamp()); + System.out.println( + " no priority stripping:" + + udpInput.getNoPriorityStripping()); + } else if (inputKind == InputKind.WindowsActiveDirectory) { + WindowsActiveDirectoryInput windowsActiveDirectoryInput = + (WindowsActiveDirectoryInput) input; + System.out.println( + " index: " + + windowsActiveDirectoryInput.getIndex()); + System.out.println( + " monitor subtree: " + + windowsActiveDirectoryInput.getMonitorSubtree()); + System.out.println( + " starting node: " + + windowsActiveDirectoryInput.getStartingNode()); + System.out.println( + " target DC: " + + windowsActiveDirectoryInput.getTargetDc()); + } else if (inputKind == InputKind.WindowsEventLog) { + WindowsEventLogInput windowsEventLogInput = + (WindowsEventLogInput) input; + System.out.println( + " hosts: " + + windowsEventLogInput.getHosts()); + System.out.println( + " index: " + + windowsEventLogInput.getIndex()); + System.out.println( + " local name: " + + windowsEventLogInput.getLocalName()); + String[] logs = windowsEventLogInput.getLogs(); + System.out.println(" logs:"); + if (logs != null) + for (String log: logs) { + System.out.println(" " + log); + } + System.out.println( + " lookup host: " + + windowsEventLogInput.getLookupHost()); + } else if (inputKind == InputKind.WindowsPerfmon) { + WindowsPerfmonInput windowsPerfmonInput = + (WindowsPerfmonInput) input; + System.out.println( + " counters: " + + windowsPerfmonInput.getCounters()); + System.out.println( + " index: " + + windowsPerfmonInput.getIndex()); + System.out.println( + " instances: " + + windowsPerfmonInput.getInstances()); + System.out.println( + " interval: " + + windowsPerfmonInput.getInterval()); + System.out.println( + " object: " + + windowsPerfmonInput.getObject()); + } else if (inputKind == InputKind.WindowsRegistry) { + WindowsRegistryInput windowsRegistryInput = + (WindowsRegistryInput) input; + System.out.println( + " baseline: " + + windowsRegistryInput.getBaseline()); + System.out.println( + " hive: " + + windowsRegistryInput.getHive()); + System.out.println( + " index: " + + windowsRegistryInput.getIndex()); + System.out.println( + " monitor subnodes:" + + windowsRegistryInput.getMonitorSubnodes()); + System.out.println( + " process: " + + windowsRegistryInput.getProc()); + System.out.println( + " type: " + + windowsRegistryInput.getType()); + } else if (inputKind == InputKind.WindowsWmi) { + WindowsWmiInput windowsWmiInput = (WindowsWmiInput) input; + System.out.println( + " WMI input: " + + windowsWmiInput.getClasses()); + String[] fields = windowsWmiInput.getFields(); + System.out.println(" fields:"); + for (String field: fields) { + System.out.println(" " + field); + } + System.out.println( + " index: " + + windowsWmiInput.getIndex()); + + String[] instances = windowsWmiInput.getInstances(); + System.out.println(" instances:"); + for (String instance: instances) { + System.out.println(" " + instance); + } + System.out.println( + " interval: " + + windowsWmiInput.getInterval()); + System.out.println( + " local name: " + + windowsWmiInput.getLocalName()); + System.out.println( + " lookup host: " + + windowsWmiInput.getLookupHost()); + System.out.println( + " server: " + + windowsWmiInput.getServers()); + System.out.println( + " WQL: " + windowsWmiInput.getWql()); + } + } + + static void run(String[] argsIn) throws Exception { + + Command command; + Service service; + Service.setValidateCertificates(false); + + command = Command.splunk("input"); + service = Service.connect(command.opts); + + InputCollection inputs = service.getInputs(); + + // Iterate inputs and make sure we can read them. + for (Input input : inputs.values()) { + System.out.println("Input name: " + input.getName()); + System.out.println(" title: " + input.getTitle()); + System.out.println(" path: " + input.getPath()); + System.out.println(" type: " + input.getKind()); + DisplaySpecificInput(input); + System.out.println("\n\n"); + } + } +} diff --git a/java/src/main/java/com/splunk/examples/pivot/Program.java b/java/src/main/java/com/splunk/examples/pivot/Program.java new file mode 100644 index 0000000..14d1487 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/pivot/Program.java @@ -0,0 +1,87 @@ +/* + * Copyright 2014 Splunk, 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.splunk.examples.pivot; + +import com.splunk.*; + +public class Program { + public static void main(String[] argv) { + try { + run(argv); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] argsIn) throws Exception { + Command command; + Service service; + Service.setValidateCertificates(false); + + command = Command.splunk("input"); + service = Service.connect(command.opts); + + DataModel dataModel = service.getDataModels().get("internal_audit_logs"); + DataModelObject searches = dataModel.getObject("searches"); + + System.out.print("Working with object " + searches.getDisplayName()); + System.out.println(" in model " + dataModel.getDisplayName()); + System.out.print(" Lineage: "); + for (String name : searches.getLineage()) { + System.out.print(" -> " + name); + } + System.out.println(); + System.out.println(" Internal name: " + searches.getName()); + + Job firstFiveEntries = searches.runQuery("| head 5"); + while (!firstFiveEntries.isDone()) { + Thread.sleep(100); + } + + ResultsReaderXml results = new ResultsReaderXml(firstFiveEntries.getResults()); + for (Event event : results) { + System.out.println(event.toString()); + } + + System.out.println("~~~~~~~~~~~~~~~~~~~~"); + System.out.println("Pivoting on searches"); + + PivotSpecification pivotSpecification = searches.createPivotSpecification(); + + pivotSpecification.addRowSplit("user", "Executing user"); + pivotSpecification.addColumnSplit("exec_time", null, null, null, 4); + pivotSpecification.addCellValue("search", "Search Query", StatsFunction.DISTINCT_VALUES); + + Pivot pivot = pivotSpecification.pivot(); + System.out.println("Query for binning search queries by execution time and executing user:"); + System.out.println(" " + pivot.getPrettyQuery()); + + Job pivotJob = pivot.run(); + while (!pivotJob.isDone()) { + Thread.sleep(100); + } + + results = new ResultsReaderXml(pivotJob.getResults()); + for (Event event : results) { + System.out.println(event.toString()); + } + + } +} + + diff --git a/java/src/main/java/com/splunk/examples/search/Program.java b/java/src/main/java/com/splunk/examples/search/Program.java new file mode 100644 index 0000000..22295f6 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search/Program.java @@ -0,0 +1,234 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search; + +import com.splunk.*; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.Arrays; +import java.util.HashMap; + +// Note: not all search parameters are exposed to the CLI for this example. +public class Program { + static String[] outputChoices = new String[] { + "events", "results", "preview", "searchlog", "summary", "timeline" + }; + + static String earliestTimeText = "Search earliest time"; + static String fieldListText = + "A comma-separated list of the fields to return"; + static String latestTimeText = "Search latest time"; + static String offset = + "The first result (inclusive) from which to begin returning data. " + + "(default: 0)"; + static String outputText = + "Which search results to output {events, results, preview, searchlog," + + " summary, timeline} (default: results)"; + static String outputModeText = + "Search output format {csv, raw, json, xml} (default: xml)"; + static String resultsCount = + "The maximum number of results to return (default: 100)"; + static String readerText = "Use ResultsReader"; + static String statusBucketsText = + "Number of status buckets to use for search (default: 0)"; + static String verboseString = "Display search progress"; + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws Exception { + Command command = Command.splunk("search"); + command.addRule("count", Integer.class, resultsCount); + command.addRule("earliest_time", String.class, earliestTimeText); + command.addRule("field_list", String.class, fieldListText); + command.addRule("latest_time", String.class, latestTimeText); + command.addRule("offset", Integer.class, offset); + command.addRule("output", String.class, outputText); + command.addRule("output_mode", String.class, outputModeText); + command.addRule("reader", readerText); + command.addRule("status_buckets", Integer.class, statusBucketsText); + command.addRule("verbose", verboseString); + command.parse(args); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + int resultsCount = 100; + if (command.opts.containsKey("count")) + resultsCount = (Integer)command.opts.get("count"); + + String earliestTime = null; + if (command.opts.containsKey("earliest_time")) + earliestTime = (String)command.opts.get("earliest_time"); + + String fieldList = null; + if (command.opts.containsKey("field_list")) + fieldList = (String)command.opts.get("field_list"); + + String latestTime = null; + if (command.opts.containsKey("latest_time")) + latestTime = (String)command.opts.get("latest_time"); + + int offset = 0; + if (command.opts.containsKey("offset")) + offset = (Integer)command.opts.get("offset"); + + String output = "results"; + if (command.opts.containsKey("output")) { + output = (String)command.opts.get("output"); + if (!Arrays.asList(outputChoices).contains(output)) + Command.error("Unsupported output: '%s'", output); + } + + String outputMode = "xml"; + if (command.opts.containsKey("output_mode")) + outputMode = (String)command.opts.get("output_mode"); + + int statusBuckets = 0; + if (command.opts.containsKey("status_buckets")) + statusBuckets = (Integer)command.opts.get("status_buckets"); + + boolean verbose = command.opts.containsKey("verbose"); + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // Check the syntax of the query. + try { + service.parse(query, new Args("parse_only", true)); + } + catch (HttpException e) { + Command.error("query '%s' is invalid: %s", query, e.getDetail()); + } + + // Create a search job for the given query & query arguments. + Args queryArgs = new Args(); + if (earliestTime != null) + queryArgs.put("earliest_time", earliestTime); + if (fieldList != null) + queryArgs.put("field_list", fieldList); + if (latestTime != null) + queryArgs.put("latest_time", latestTime); + if (statusBuckets > 0) + queryArgs.put("status_buckets", statusBuckets); + + Job job = service.getJobs().create(query, queryArgs); + + // Wait until results are available. + boolean didPrintAStatusLine = false; + while (!job.isDone()) { + // If no outputs are available, optionally print status + if (verbose && job.isReady()) { + float progress = job.getDoneProgress() * 100.0f; + int scanned = job.getScanCount(); + int matched = job.getEventCount(); + int results = job.getResultCount(); + System.out.format( + "\r%03.1f%% done -- %d scanned -- %d matched -- %d results", + progress, scanned, matched, results); + didPrintAStatusLine = true; + } + + Thread.sleep(1000); + } + if (didPrintAStatusLine) + System.out.println(""); + + Args outputArgs = new Args(); + outputArgs.put("count", resultsCount); + outputArgs.put("offset", offset); + outputArgs.put("output_mode", outputMode); + + InputStream stream; + if (output.equals("results")) + stream = job.getResults(outputArgs); + else if (output.equals("events")) + stream = job.getEvents(outputArgs); + else if (output.equals("preview")) + stream = job.getResultsPreview(outputArgs); + else if (output.equals("searchlog")) + stream = job.getSearchLog(outputArgs); + else if (output.equals("summary")) + stream = job.getSummary(outputArgs); + else if (output.equals("timeline")) + stream = job.getTimeline(outputArgs); + else + throw new IllegalArgumentException( + "Unrecognized output type: " + output); + + boolean useReader = command.opts.containsKey("reader"); + if (useReader) { + ResultsReader resultsReader; + if (outputMode.equals("xml")) + resultsReader = new ResultsReaderXml(stream); + else if (outputMode.equals("json")) + resultsReader = new ResultsReaderJson(stream); + else if (outputMode.equals("csv")) + resultsReader = new ResultsReaderCsv(stream); + else + throw new IllegalArgumentException( + "Unrecognized output mode: " + outputMode); + + try { + HashMap event; + while ((event = resultsReader.getNextEvent()) != null) { + System.out.println("EVENT:********"); + for (String key : event.keySet()) + System.out.println(" " + key + " --> " + event.get(key)); + } + } + finally { + resultsReader.close(); + } + } + else { + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + try { + OutputStreamWriter writer = new OutputStreamWriter(System.out); + try { + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + } + + writer.write("\n"); + } + finally { + writer.close(); + } + } + finally { + reader.close(); + } + } + + job.cancel(); + } +} \ No newline at end of file diff --git a/java/src/main/java/com/splunk/examples/search_blocking/Program.java b/java/src/main/java/com/splunk/examples/search_blocking/Program.java new file mode 100644 index 0000000..158ab7b --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search_blocking/Program.java @@ -0,0 +1,199 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search_blocking; + +import com.splunk.*; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.Arrays; +import java.util.HashMap; + +// Note: not all search parameters are exposed to the CLI for this example. +public class Program { + static String[] outputChoices = new String[] { + "events", "results", "preview", "searchlog", "summary", "timeline" + }; + + static String earliestTimeText = "Search earliest time"; + static String fieldListText = + "A comma-separated list of the fields to return"; + static String latestTimeText = "Search latest time"; + static String offset = + "The first result (inclusive) from which to begin returning data. " + + "(default: 0)"; + static String outputText = + "Which search results to output {events, results, preview, searchlog," + + " summary, timeline} (default: results)"; + static String outputModeText = + "Search output format {csv, raw, json, xml} (default: xml)"; + static String resultsCount = + "The maximum number of results to return (default: 100)"; + static String rawText = "Set to 1 if raw events are displayed (default 1)"; + static String statusBucketsText = + "Number of status buckets to use for search (default: 0)"; + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws IOException { + Command command = Command.splunk("search"); + command.addRule("count", Integer.class, resultsCount); + command.addRule("earliest_time", String.class, earliestTimeText); + command.addRule("field_list", String.class, fieldListText); + command.addRule("latest_time", String.class, latestTimeText); + command.addRule("offset", Integer.class, offset); + command.addRule("output", String.class, outputText); + command.addRule("output_mode", String.class, outputModeText); + command.addRule("raw", Integer.class, rawText); + command.addRule("status_buckets", Integer.class, statusBucketsText); + command.parse(args); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + int resultsCount = 100; + if (command.opts.containsKey("count")) + resultsCount = (Integer)command.opts.get("count"); + + String earliestTime = null; + if (command.opts.containsKey("earliest_time")) + earliestTime = (String)command.opts.get("earliest_time"); + + String fieldList = null; + if (command.opts.containsKey("field_list")) + fieldList = (String)command.opts.get("field_list"); + + String latestTime = null; + if (command.opts.containsKey("latest_time")) + latestTime = (String)command.opts.get("latest_time"); + + int offset = 0; + if (command.opts.containsKey("offset")) + offset = (Integer)command.opts.get("offset"); + + String output = "results"; + if (command.opts.containsKey("output")) { + output = (String)command.opts.get("output"); + if (!Arrays.asList(outputChoices).contains(output)) + Command.error("Unsupported output: '%s'", output); + } + + String outputMode = "xml"; + if (command.opts.containsKey("output_mode")) + outputMode = (String)command.opts.get("output_mode"); + + int statusBuckets = 0; + if (command.opts.containsKey("status_buckets")) + statusBuckets = (Integer)command.opts.get("status_buckets"); + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // Check the syntax of the query. + try { + Args parseArgs = new Args("parse_only", true); + service.parse(query, parseArgs); + } + catch (HttpException e) { + String detail = e.getDetail(); + Command.error("query '%s' is invalid: %s", query, detail); + } + + // Create a search job for the given query & query arguments. + Args queryArgs = new Args(); + if (earliestTime != null) + queryArgs.put("earliest_time", earliestTime); + if (fieldList != null) + queryArgs.put("field_list", fieldList); + if (latestTime != null) + queryArgs.put("latest_time", latestTime); + if (statusBuckets > 0) + queryArgs.put("status_buckets", statusBuckets); + + // Always block until results are ready. + queryArgs.put("exec_mode", "blocking"); + Job job = service.getJobs().create(query, queryArgs); + + InputStream stream = null; + + Args outputArgs = new Args(); + outputArgs.put("count", resultsCount); + outputArgs.put("offset", offset); + outputArgs.put("output_mode", outputMode); + + if (output.equals("results")) + stream = job.getResults(outputArgs); + else if (output.equals("events")) + stream = job.getEvents(outputArgs); + else if (output.equals("preview")) + stream = job.getResultsPreview(outputArgs); + else if (output.equals("searchlog")) + stream = job.getSearchLog(outputArgs); + else if (output.equals("summary")) + stream = job.getSummary(outputArgs); + else if (output.equals("timeline")) + stream = job.getTimeline(outputArgs); + else assert(false); + + boolean rawData = true; + if (command.opts.containsKey("raw")) { + rawData = (Integer) command.opts.get("raw")==1; + } + + if (!rawData) { + HashMap map; + try { + ResultsReaderXml resultsReader = new ResultsReaderXml(stream); + while ((map = resultsReader.getNextEvent()) != null) { + System.out.println("EVENT:********"); + System.out.println(" " + map); + } + resultsReader.close(); + } catch (IOException e) { + System.out.println("I/O exception: " + e); + } + } + else { + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + OutputStreamWriter writer = new OutputStreamWriter(System.out); + + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + } + + writer.write("\n"); + writer.close(); + reader.close(); + } + job.cancel(); + } +} diff --git a/java/src/main/java/com/splunk/examples/search_oneshot/Program.java b/java/src/main/java/com/splunk/examples/search_oneshot/Program.java new file mode 100644 index 0000000..de013d5 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search_oneshot/Program.java @@ -0,0 +1,152 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search_oneshot; + +import com.splunk.Args; +import com.splunk.HttpException; +import com.splunk.ResultsReaderXml; +import com.splunk.Service; +import com.splunk.Command; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.HashMap; + +// Note: not all search parameters are exposed to the CLI for this example. +public class Program { + + static String earliestTimeText = "Search earliest time"; + static String fieldListText = + "A comma-separated list of the fields to return"; + static String latestTimeText = "Search latest time"; + static String outputModeText = + "Search output format {csv, raw, json, xml} (default: xml)"; + static String rawText = "Set to 1 if raw events are displayed (default 1)"; + static String statusBucketsText = + "Number of status buckets to use for search (default: 0)"; + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws IOException { + Command command = Command.splunk("search"); + command.addRule("earliest_time", String.class, earliestTimeText); + command.addRule("field_list", String.class, fieldListText); + command.addRule("latest_time", String.class, latestTimeText); + command.addRule("output_mode", String.class, outputModeText); + command.addRule("raw", Integer.class, rawText); + command.addRule("status_buckets", Integer.class, statusBucketsText); + command.parse(args); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + String earliestTime = null; + if (command.opts.containsKey("earliest_time")) + earliestTime = (String)command.opts.get("earliest_time"); + + String fieldList = null; + if (command.opts.containsKey("field_list")) + fieldList = (String)command.opts.get("field_list"); + + String latestTime = null; + if (command.opts.containsKey("latest_time")) + latestTime = (String)command.opts.get("latest_time"); + + int statusBuckets = 0; + if (command.opts.containsKey("status_buckets")) + statusBuckets = (Integer)command.opts.get("status_buckets"); + + String outputMode = "xml"; + if (command.opts.containsKey("output_mode")) + outputMode = (String)command.opts.get("output_mode"); + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // Check the syntax of the query. + try { + Args parseArgs = new Args("parse_only", true); + service.parse(query, parseArgs); + } + catch (HttpException e) { + String detail = e.getDetail(); + Command.error("query '%s' is invalid: %s", query, detail); + } + + // Create the oneshot search query & query arguments. + Args queryArgs = new Args(); + if (earliestTime != null) + queryArgs.put("earliest_time", earliestTime); + if (fieldList != null) + queryArgs.put("field_list", fieldList); + if (latestTime != null) + queryArgs.put("latest_time", latestTime); + if (statusBuckets > 0) + queryArgs.put("status_buckets", statusBuckets); + queryArgs.put("output_mode", outputMode); + + // Execute the oneshot query, which returns the stream (i.e. there is + // no search job created, just a one time search) + InputStream stream = service.oneshotSearch(query, queryArgs); + + boolean rawData = true; + if (command.opts.containsKey("raw")) { + rawData = (Integer) command.opts.get("raw")==1; + } + + if (!rawData) { + HashMap map; + try { + ResultsReaderXml resultsReader = new ResultsReaderXml(stream); + while ((map = resultsReader.getNextEvent()) != null) { + System.out.println("EVENT:********"); + System.out.println(" " + map); + } + resultsReader.close(); + } catch (IOException e) { + System.out.println("I/O exception: " + e); + } + } + else { + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + OutputStreamWriter writer = new OutputStreamWriter(System.out); + + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + } + + writer.write("\n"); + writer.close(); + reader.close(); + } + } +} diff --git a/java/src/main/java/com/splunk/examples/search_realtime/Program.java b/java/src/main/java/com/splunk/examples/search_realtime/Program.java new file mode 100644 index 0000000..69d21aa --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search_realtime/Program.java @@ -0,0 +1,208 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search_realtime; + +import com.splunk.*; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.Arrays; +import java.util.HashMap; + +// Note: not all search parameters are exposed to the CLI for this example. +public class Program { + static String[] outputChoices = new String[] { + "events", "results", "preview", "searchlog", "summary", "timeline" + }; + + static String earliestTimeText = + "Search earliest time (default: 'rt-5m')"; + static String fieldListText = + "A comma-separated list of the fields to return"; + static String latestTimeText = + "Search latest time (default: 'rt' (i.e. now))"; + static String offset = + "The first result (inclusive) from which to begin returning data. " + + "(default: 0)"; + static String outputText = + "Which search results to output {events, results, preview, searchlog," + + " summary, timeline} (default: preview)"; + static String outputModeText = + "Search output format {csv, raw, json, xml} (default: xml)"; + static String rawText = "Set to 1 if raw events are displayed (default 1)"; + static String resultsCount = + "The maximum number of results to return (default: 100)"; + static String statusBucketsText = + "Number of status buckets to use for search (default: 0)"; + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws IOException { + Command command = Command.splunk("search"); + command.addRule("count", Integer.class, resultsCount); + command.addRule("earliest_time", String.class, earliestTimeText); + command.addRule("field_list", String.class, fieldListText); + command.addRule("latest_time", String.class, latestTimeText); + command.addRule("offset", Integer.class, offset); + command.addRule("output", String.class, outputText); + command.addRule("output_mode", String.class, outputModeText); + command.addRule("raw", Integer.class, rawText); + command.addRule("status_buckets", Integer.class, statusBucketsText); + command.parse(args); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + int resultsCount = 100; + if (command.opts.containsKey("count")) + resultsCount = (Integer)command.opts.get("count"); + + String earliestTime = "rt-5m"; + if (command.opts.containsKey("earliest_time")) + earliestTime = (String)command.opts.get("earliest_time"); + + String fieldList = null; + if (command.opts.containsKey("field_list")) + fieldList = (String)command.opts.get("field_list"); + + String latestTime = "rt"; + if (command.opts.containsKey("latest_time")) + latestTime = (String)command.opts.get("latest_time"); + + int offset = 0; + if (command.opts.containsKey("offset")) + offset = (Integer)command.opts.get("offset"); + + String output = "preview"; + if (command.opts.containsKey("output")) { + output = (String)command.opts.get("output"); + if (!Arrays.asList(outputChoices).contains(output)) + Command.error("Unsupported output: '%s'", output); + } + + String outputMode = "xml"; + if (command.opts.containsKey("output_mode")) + outputMode = (String)command.opts.get("output_mode"); + + int statusBuckets = 0; + if (command.opts.containsKey("status_buckets")) + statusBuckets = (Integer)command.opts.get("status_buckets"); + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // Check the syntax of the query. + try { + Args parseArgs = new Args("parse_only", true); + service.parse(query, parseArgs); + } + catch (HttpException e) { + String detail = e.getDetail(); + Command.error("query '%s' is invalid: %s", query, detail); + } + + // Create a search job for the given query & query arguments. + Args queryArgs = new Args(); + if (fieldList != null) + queryArgs.put("field_list", fieldList); + if (statusBuckets > 0) + queryArgs.put("status_buckets", statusBuckets); + + // Always set real time search mode + queryArgs.put("search_mode", "realtime"); + queryArgs.put("earliest_time", earliestTime); + queryArgs.put("latest_time", latestTime); + + Job job = service.getJobs().create(query, queryArgs); + + while (!job.isReady()) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // You shouldn't ever get here. + } + } + + InputStream stream = null; + + Args outputArgs = new Args(); + outputArgs.put("count", resultsCount); + outputArgs.put("offset", offset); + outputArgs.put("output_mode", outputMode); + + if (output.equals("results")) + stream = job.getResults(outputArgs); + else if (output.equals("events")) + stream = job.getEvents(outputArgs); + else if (output.equals("preview")) + stream = job.getResultsPreview(outputArgs); + else if (output.equals("searchlog")) + stream = job.getSearchLog(outputArgs); + else if (output.equals("summary")) + stream = job.getSummary(outputArgs); + else if (output.equals("timeline")) + stream = job.getTimeline(outputArgs); + else assert(false); + + boolean rawData = true; + if (command.opts.containsKey("raw")) { + rawData = (Integer) command.opts.get("raw")==1; + } + + if (!rawData) { + HashMap map; + try { + ResultsReaderXml resultsReader = new ResultsReaderXml(stream); + while ((map = resultsReader.getNextEvent()) != null) { + System.out.println("EVENT:********"); + System.out.println(" " + map); + } + resultsReader.close(); + } catch (IOException e) { + System.out.println("I/O exception: " + e); + } + } + else { + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + OutputStreamWriter writer = new OutputStreamWriter(System.out); + + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + } + + writer.write("\n"); + writer.close(); + reader.close(); + } + job.cancel(); + } +} diff --git a/java/src/main/java/com/splunk/examples/search_saved/Program.java b/java/src/main/java/com/splunk/examples/search_saved/Program.java new file mode 100644 index 0000000..59f928f --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search_saved/Program.java @@ -0,0 +1,68 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search_saved; + +import com.splunk.*; + +public class Program { + + static String countString = "How many saved searches to return"; + static String offsetString = "The offset into the collection"; + + private static void list(Service service, Args window) { + + EntityCollection searches; + + if (window == null) + searches = service.getSavedSearches(); + else + searches = service.getSavedSearches(window); + + for (SavedSearch entity: searches.values()) { + System.out.println( + entity.getTitle() + "\n" + + " (" + entity.getSearch()+ ")"); + } + } + + public static void main(String[] args) { + Command command = Command.splunk("search saved").parse(args); + command.addRule("count", String.class, countString); + command.addRule("offset", String.class, offsetString); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + if (command.args.length == 0) { + list(service, null); + return; + } + + Args window = new Args(); + for (String value: args) { + String [] parts = value.split("="); + if (parts.length != 2) { + Command.error("Arguments are of the form: name=value"); + } + if (!parts[0].equals("count") && !parts[0].equals("offset")) { + Command.error("Unknown key: " + parts[0]); + } + window.put(parts[0], parts[1]); + } + + list(service, window); + } +} diff --git a/java/src/main/java/com/splunk/examples/search_simple/Program.java b/java/src/main/java/com/splunk/examples/search_simple/Program.java new file mode 100644 index 0000000..ce920c8 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/search_simple/Program.java @@ -0,0 +1,89 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.search_simple; + +import com.splunk.Args; +import com.splunk.HttpException; +import com.splunk.Service; +import com.splunk.Command; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.OutputStreamWriter; + +// Note: not all search parameters are exposed to the CLI for this example. +public class Program { + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws IOException { + Command command = Command.splunk("search"); + command.parse(args); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + // Check the syntax of the query. + try { + Args parseArgs = new Args("parse_only", true); + service.parse(query, parseArgs); + } + catch (HttpException e) { + String detail = e.getDetail(); + Command.error("query '%s' is invalid: %s", query, detail); + } + + // This is the simplest form of searching splunk. Note that additional + // arguments are allowed, but they are not shown in this example. + InputStream stream = service.oneshotSearch(query); + + InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); + try { + OutputStreamWriter writer = new OutputStreamWriter(System.out); + try { + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + } + + writer.write("\n"); + } + finally { + writer.close(); + } + } + finally { + reader.close(); + } + } +} diff --git a/java/src/main/java/com/splunk/examples/spurl/Program.java b/java/src/main/java/com/splunk/examples/spurl/Program.java new file mode 100644 index 0000000..05e7f64 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/spurl/Program.java @@ -0,0 +1,58 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.spurl; + +import com.splunk.Service; +import com.splunk.ResponseMessage; +import com.splunk.Command; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; + +public class Program { + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] args) throws IOException { + Command command = Command.splunk("test").parse(args); + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + String path = command.args.length > 0 ? command.args[0] : "/"; + ResponseMessage response = service.get(path); + + int status = response.getStatus(); + System.out.println(String.format("=> %d", status)); + if (status != 200) return; + + BufferedReader reader = new BufferedReader( + new InputStreamReader(response.getContent(), "UTF-8")); + while (true) { + String line = reader.readLine(); + if (line == null) break; + System.out.println(line); + } + } +} diff --git a/java/src/main/java/com/splunk/examples/ssl_protocols/Program.java b/java/src/main/java/com/splunk/examples/ssl_protocols/Program.java new file mode 100644 index 0000000..1ef46df --- /dev/null +++ b/java/src/main/java/com/splunk/examples/ssl_protocols/Program.java @@ -0,0 +1,156 @@ +/* + * Copyright 2015 Splunk, 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. + */ + +/** + * This example will demonstrate how to use a specific SSL/TLS + * protocol to connect to Splunk. + * Additionally, there's a small code sample showing how to + * use a custom SSLSocketFactory to connect to Splunk. + */ + +package com.splunk.examples.ssl_protocols; + +import com.splunk.Command; +import com.splunk.SSLSecurityProtocol; +import com.splunk.Service; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; + + +public class Program { + + public static String getJavaVersion() { + return System.getProperty("java.version"); + } + + public static void main(String[] args) { + Command command = Command.splunk("info").parse(args); + Service.setValidateCertificates(false); + + System.out.println("Your Java version is: " + getJavaVersion()); + + // At this point, the default protocol is SSLv3. + // Possible values are TLSv1.2, TLSv1.1, TLSv1 & SSLv3 + // These are defined by the SSLSecurityProtocol enum + // Java 8 disables SSLv3 by default + System.out.println("Now trying to connect to Splunk using SSLv3"); + try { + Service.setSslSecurityProtocol(SSLSecurityProtocol.SSLv3); + Service serviceSSLv3 = Service.connect(command.opts); + serviceSSLv3.login(); + System.out.println("\t Success!"); + } catch (RuntimeException e) { + System.out.println("\t Failure! "); + } + + // TLSv1 is available by default in every modern version of Java + System.out.println("Now trying to connect to Splunk using TLSv1"); + try { + Service.setSslSecurityProtocol(SSLSecurityProtocol.TLSv1); + Service serviceTLSv1 = Service.connect(command.opts); + serviceTLSv1.login(); + System.out.println("\t Success!"); + } catch (RuntimeException e) { + System.out.println("\t Failure! "); + } + + + // TLSv1.1 is available by default in Java 7 and up + System.out.println("Now trying to connect to Splunk using TLSv1.1"); + try { + Service.setSslSecurityProtocol(SSLSecurityProtocol.TLSv1_1); + Service serviceTLSv1_1 = Service.connect(command.opts); + serviceTLSv1_1.login(); + System.out.println("\t Success!"); + } catch (RuntimeException e) { + System.out.println("\t Failure! "); + } + + // TLSv1.2 is available by default in Java 7 and up + System.out.println("Now trying to connect to Splunk using TLSv1.2"); + try { + Service.setSslSecurityProtocol(SSLSecurityProtocol.TLSv1_2); + Service serviceTLSv1_2 = Service.connect(command.opts); + serviceTLSv1_2.login(); + System.out.println("\t Success!"); + } catch (RuntimeException e) { + System.out.println("\t Failure! "); + } + + // You can also specify your own SSLSocketFactory, in this case any version of SSL + System.out.println("Now trying to connect to Splunk using a custom SSL only SSLSocketFactory"); + try { + // Create an SSLSocketFactory configured to use SSL only + SSLContext sslContext = SSLContext.getInstance("SSL"); + TrustManager[] byPassTrustManagers = new TrustManager[]{ + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + } + }; + sslContext.init(null, byPassTrustManagers, new SecureRandom()); + SSLSocketFactory SSLOnlySSLFactory = sslContext.getSocketFactory(); + Service.setSSLSocketFactory(SSLOnlySSLFactory); + + Service serviceCustomSSLFactory = Service.connect(command.opts); + serviceCustomSSLFactory.login(); + System.out.println("\t Success!"); + } catch (Exception e) { + System.out.println("\t Failure!"); + } + + // You can also specify your own SSLSocketFactory, in this case any version of TLS + System.out.println("Now trying to connect to Splunk using a custom TLS only SSLSocketFactory"); + try { + // Create an SSLSocketFactory configured to use TLS only + SSLContext sslContext = SSLContext.getInstance("TLS"); + TrustManager[] byPassTrustManagers = new TrustManager[]{ + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + } + }; + sslContext.init(null, byPassTrustManagers, new SecureRandom()); + SSLSocketFactory TLSOnlySSLFactory = sslContext.getSocketFactory(); + Service.setSSLSocketFactory(TLSOnlySSLFactory); + + Service serviceCustomSSLFactory = Service.connect(command.opts); + serviceCustomSSLFactory.login(); + System.out.println("\t Success!"); + } catch (Exception e) { + System.out.println("\t Failure!"); + } + } +} \ No newline at end of file diff --git a/java/src/main/java/com/splunk/examples/tail/Program.java b/java/src/main/java/com/splunk/examples/tail/Program.java new file mode 100644 index 0000000..f3c6104 --- /dev/null +++ b/java/src/main/java/com/splunk/examples/tail/Program.java @@ -0,0 +1,84 @@ +/* + * Copyright 2011 Splunk, 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.splunk.examples.tail; + +import com.splunk.*; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +/** + * Tail an index + */ + +public class Program { + + static String outputModeText = + "Search output format {csv, raw, json, xml} (default: xml)"; + + public static void main(String[] args) { + try { + run(args); + } + catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + + static void run(String[] argsIn) throws Exception { + + Command command = Command.splunk("tail"); + command.addRule("format", String.class, outputModeText); + command.parse(argsIn); + + if (command.args.length != 1) + Command.error("Search expression required"); + String query = command.args[0]; + + Service.setValidateCertificates(false); + Service service = Service.connect(command.opts); + + String outputMode = "csv"; + if (command.opts.containsKey("format")) + outputMode = (String)command.opts.get("format"); + Args args = new Args(); + + // search args + args.put("timeout", "60"); // Don't keep search around + args.put("output_mode", outputMode); // Output in specific format + args.put("earliest_time", "rt"); // Realtime + args.put("latest_time", "rt"); // Realtime + args.put("search_mode", "realtime"); // Realtime + + InputStream is = service.export(query, args); + + // Use UTF8 sensitive reader/writers + InputStreamReader reader = new InputStreamReader(is, "UTF-8"); + OutputStreamWriter writer = new OutputStreamWriter(System.out); + + int size = 1024; + char[] buffer = new char[size]; + while (true) { + int count = reader.read(buffer); + if (count == -1) break; + writer.write(buffer, 0, count); + writer.flush(); + } + } +} diff --git a/java/src/test/java/com/splunk/examples/TestExamples.java b/java/src/test/java/com/splunk/examples/TestExamples.java new file mode 100644 index 0000000..a6fa8f7 --- /dev/null +++ b/java/src/test/java/com/splunk/examples/TestExamples.java @@ -0,0 +1,339 @@ +package com.splunk.examples; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static junit.framework.TestCase.assertEquals; + +public class TestExamples { + + Runtime runtime; + + @Before + public void setUp(){ + runtime = Runtime.getRuntime(); + } + + @After + public void tearDown(){ + try { + runtime.exec("rm export.out"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void endpointInstantiationExampleTest(){ + try { + assertEquals(0,executeEndpointInstantiationExample()); + System.out.println("Endpoint Instantiation example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void exportExampleTest(){ + try { + assertEquals(0,executeExportExample()); + System.out.println("Export example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void fluentPivotExampleTest(){ + try { + assertEquals(0,executeFluentPivotExample()); + System.out.println("Fluent Pivot example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void geneventsExampleTest(){ + try { + assertEquals(0,executeGeneventsExample()); + System.out.println("Genevents example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void getJobExampleTest(){ + try { + assertEquals(0,executeGetJobExample()); + System.out.println("Get Job example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void indexExampleTest(){ + try { + assertEquals(0,executeIndexExample()); + System.out.println("Index example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void infoExampleTest(){ + try { + assertEquals(0,executeInfoExample()); + System.out.println("Info example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void inputExampleTest(){ + try { + assertEquals(0,executeInputExample()); + System.out.println("Input example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void pivotExampleTest(){ + try { + assertEquals(0,executePivotExample()); + System.out.println("Pivot example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchExampleTest(){ + try { + assertEquals(0,executeSearchExample()); + System.out.println("Search example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchBlockingExampleTest(){ + try { + assertEquals(0,executeSearchBlockingExample()); + System.out.println("Search Blocking example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchOneshotExampleTest(){ + try { + assertEquals(0,executeSearchOneshotExample()); + System.out.println("Search Oneshot example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchRealtimeExampleTest(){ + try { + assertEquals(0,executeSearchRealtimeExample()); + System.out.println("Search Realtime example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchSavedExampleTest(){ + try { + assertEquals(0,executeSearchSavedExample()); + System.out.println("Search Saved example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void searchSimpleExampleTest(){ + try { + assertEquals(0,executeSearchSimpleExample()); + System.out.println("Search Simple example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void spurlExampleTest(){ + try { + assertEquals(0,executeSpurlExample()); + System.out.println("Spurl example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void sslProtocolsExampleTest(){ + try { + assertEquals(0,executeSslProtocolsExample()); + System.out.println("Ssl Protocols example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Test + public void tailExampleTest(){ + try { + assertEquals(0,executeTailExample()); + System.out.println("Tail example test passed !!!"); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + + public int executeEndpointInstantiationExample() throws IOException, InterruptedException { + System.out.println("Running Endpoint Instantiation Example....."); + String[] cmd = {"make", "run", "TARGET=endpoint_instantiation"}; + return executeCommand(cmd); + } + + public int executeExportExample() throws IOException, InterruptedException { + System.out.println("Running Export Example....."); + String[] cmd = {"make", "run", "TARGET=export"}; + return executeCommand(cmd); + } + + public int executeFluentPivotExample() throws IOException, InterruptedException { + System.out.println("Running Fluent Pivot Example....."); + String[] cmd = {"make", "run", "TARGET=fluent_pivot"}; + return executeCommand(cmd); + } + + public int executeGeneventsExample() throws IOException, InterruptedException { + System.out.println("Running Genevents Example....."); + String[] cmd = {"make", "run", "TARGET=genevents"}; + return executeCommand(cmd); + } + + public int executeGetJobExample() throws IOException, InterruptedException { + System.out.println("Running Get Job Example....."); + String[] cmd = {"make", "run", "TARGET=get_job"}; + return executeCommand(cmd); + } + + public int executeIndexExample() throws IOException, InterruptedException { + System.out.println("Running Index Example....."); + String[] cmd = {"make", "run", "TARGET=index"}; + return executeCommand(cmd); + } + + public int executeInfoExample() throws IOException, InterruptedException { + System.out.println("Running Info Example....."); + String[] cmd = {"make", "run", "TARGET=info"}; + return executeCommand(cmd); + } + + public int executeInputExample() throws IOException, InterruptedException { + System.out.println("Running Input Example....."); + String[] cmd = {"make", "run", "TARGET=input"}; + return executeCommand(cmd); + } + + public int executePivotExample() throws IOException, InterruptedException { + System.out.println("Running Pivot Example....."); + String[] cmd = {"make", "run", "TARGET=pivot"}; + return executeCommand(cmd); + } + + public int executeSearchExample() throws IOException, InterruptedException { + System.out.println("Running Search Example....."); + String[] cmd = {"make", "run", "TARGET=search", "ARGUMENTS='search index=_audit source=audittrail'"}; + return executeCommand(cmd); + } + + public int executeSearchBlockingExample() throws IOException, InterruptedException { + System.out.println("Running Search Blocking Example....."); + String[] cmd = {"make", "run", "TARGET=search_blocking", "ARGUMENTS='search index=_audit source=audittrail' --raw=0"}; + return executeCommand(cmd); + } + + public int executeSearchOneshotExample() throws IOException, InterruptedException { + System.out.println("Running Search Oneshot Example....."); + String[] cmd = {"make", "run", "TARGET=search_oneshot", "ARGUMENTS='search index=_audit source=audittrail'"}; + return executeCommand(cmd); + } + + public int executeSearchRealtimeExample() throws IOException, InterruptedException { + System.out.println("Running Search Realtime Example....."); + String[] cmd = {"make", "run", "TARGET=search_realtime", "ARGUMENTS='search index=_audit source=audittrail' --raw=1"}; + return executeCommand(cmd); + } + + public int executeSearchSavedExample() throws IOException, InterruptedException { + System.out.println("Running Search Saved Example....."); + String[] cmd = {"make", "run", "TARGET=search_saved"}; + return executeCommand(cmd); + } + + public int executeSearchSimpleExample() throws IOException, InterruptedException { + System.out.println("Running Search Simple Example....."); + String[] cmd = {"make", "run", "TARGET=search_simple", "ARGUMENTS='search index=_audit source=audittrail'"}; + return executeCommand(cmd); + } + + public int executeSpurlExample() throws IOException, InterruptedException { + System.out.println("Running Spurl Example....."); + String[] cmd = {"make", "run", "TARGET=spurl"}; + return executeCommand(cmd); + } + + public int executeSslProtocolsExample() throws IOException, InterruptedException { + System.out.println("Running Ssl Protocols Example....."); + String[] cmd = {"make", "run", "TARGET=ssl_protocols"}; + return executeCommand(cmd); + } + + public int executeTailExample() throws IOException, InterruptedException { + System.out.println("Running Tail Example....."); + String[] cmd = {"make", "run", "TARGET=tail", "ARGUMENTS='search index=_audit source=audittrail | head 2'"}; + return executeCommand(cmd); + } + + public static void printResults(Process p) throws IOException { + BufferedReader is = + new BufferedReader(new InputStreamReader(p.getInputStream())); + + BufferedReader es = + new BufferedReader(new InputStreamReader(p.getErrorStream())); + String line; + + while ((line = is.readLine( )) != null) + System.out.println(line); + + while ((line = es.readLine( )) != null) + System.out.println(line); + } + + public int executeCommand(String[] cmd) throws IOException, InterruptedException { + Process process = runtime.exec(cmd); + printResults(process); + return process.waitFor(); + } +}