Java tutorial
/* * Copyright (c) <2013> <Jim Johnson jimj@jimj.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.jimj.automaton.commands; import net.jimj.automaton.events.BehaviorEvent; import net.jimj.automaton.events.ReplyEvent; import net.jimj.automaton.model.User; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpHead; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.UnknownHostException; public class HeadCommand extends Command { private static final Logger LOGGER = LoggerFactory.getLogger(HeadCommand.class); public HeadCommand() { } @Override public String getCommandName() { return "head"; } @Override public void execute(User user, String args) { if (!args.startsWith("http://") && !args.startsWith("https://")) { args = "http://" + args; } HttpHead headMethod = new HttpHead(args); try { HttpResponse response = HTTP_CLIENT.execute(headMethod); StatusLine status = response.getStatusLine(); addEvent(new ReplyEvent(user, status.getStatusCode() + " " + status.getReasonPhrase())); Header[] serverHeaders = response.getHeaders("Server"); if (serverHeaders != null) { addEvent(new ReplyEvent(user, "Server: " + serverHeaders[0].getValue())); } } catch (UnknownHostException uhe) { addEvent(new BehaviorEvent(user, BehaviorEvent.Behavior.SASSY)); } catch (Exception e) { addEvent(new BehaviorEvent(user, BehaviorEvent.Behavior.SORRY)); LOGGER.error("Error in HEAD", e); } finally { headMethod.releaseConnection(); } } @Override public void help(User user) { addEvent(new ReplyEvent(user, "head <url> - returns the HTTP status code and the 'Server' " + "header for the given URL.")); } }