Monthly Archives: 12月 2015

OpenIDのxrds文書処理クラスXrdsDocumentBuilder.java

Javaコード:

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
* @author J Steven Perry
* @author Makoto Consulting Group, Inc.
* @author Oscar Pearce – many thanks to Oscar for the guts of the code
* you see below to build the proper XRDS response document.
*
*/
public class XrdsDocumentBuilder {

private static final Logger log = Logger.getLogger(XrdsDocumentBuilder.class);

private Element baseElement;

private static final String MASTER_XRDS_NAMESPACE = “xri://$xrd*($v*2.0)”;

public XrdsDocumentBuilder() {
Namespace xrdNS = Namespace.getNamespace(MASTER_XRDS_NAMESPACE);
baseElement = new Element(“XRD”, xrdNS);
}

public void addServiceElement(String type, String uri, String priority) {
addServiceElement(type, uri, priority, null);
}

private void addServiceElement(String type, String uri, String priority, String delegate) {
log.trace(“addServiceElement() BEGIN…”);
log.debug(“Creating service element of type ‘” + type + “‘ for uri ‘” + uri + “‘ of priority ‘” + priority + “‘ with delegate ‘” + delegate + “‘”);
Namespace xrdNS = Namespace.getNamespace(MASTER_XRDS_NAMESPACE);
Namespace openidNS = Namespace.getNamespace(“openid”, “http://openid.net/xmlns/1.0”);
Element serviceElement = new Element(“Service”, xrdNS);
Element typeElement = new Element(“Type”, xrdNS);
typeElement.addContent(type);
Element uriElement = new Element(“URI”, xrdNS);
uriElement.addContent(uri);
serviceElement.addContent(typeElement);
serviceElement.addContent(uriElement);
if (StringUtils.isNotEmpty(delegate)) {
Element delegateElement = new Element(“Delegate”, openidNS);
delegateElement.addContent(delegate);
serviceElement.addContent(delegateElement);
}
if (StringUtils.isNotEmpty(priority)) {
serviceElement.setAttribute(“priority”, priority);
}
baseElement.addContent(serviceElement);
log.trace(“addServiceElement() END…”);
}

public String toXmlString() {
log.trace(“toXmlString() BEGIN…”);
Namespace xrdsNS = Namespace.getNamespace(“xrds”, “xri://$xrds”);
Element rootElement = new Element(“XRDS”, xrdsNS);
rootElement.addContent(baseElement);
Document doc = new Document(rootElement);
StringWriter w = new StringWriter();
XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
try {
o.output(doc, w);
w.close();
}
catch(IOException e) {
log.warn(“Caught an IOException while writing to StringWriter! This can’t be happening!”, e);
}
log.debug(“XRD Response = ” + w.toString());
log.trace(“toXmlString() END…”);
return w.toString();
}

}

Struts開発でOpenID Connectのユーザログイン情報取得の実現方法

Javaコード下記
public class OpenIdServiceAction extends BaseAction {
private ParameterList requestParameters;
private String returntoUrl;

private static final long serialVersionUID = xxx;

public String execute() throws Exception {
Map parameterMap = request.getParameterMap();
if (parameterMap.isEmpty()) {
// Processing empty request. Assuming discovery request…
OpenIdProviderService.sendDiscoveryResponse(response);
} else {
requestParameters = new ParameterList(request.getParameterMap());
OpenIdProviderService.logRequestParameters(requestParameters);
String mode = requestParameters.hasParameter(“openid.mode”) ? requestParameters
.getParameterValue(“openid.mode”) : null;
System.out.println(“Processing OpenID request ‘” + mode + “‘…”);
// Save off the return_to value so when the user logs in
// successfully,
// we can redirect the browser there…
// Crack the Request mode and process it accordingly…
if (“associate”.equals(mode)) {
OpenIdProviderService.processAssociationRequest(response,
requestParameters);
} else if (“checkid_immediate”.equals(mode)
|| “checkid_setup”.equals(mode)
|| “check_authentication”.equals(mode)) {
// Check Session. If information is there, we’re done. No need
// to login again.
// Create AuthResponse from session variables…

// セッションログインの判断
MakotoOpenIdAwareSession mysession = MakotoOpenIdAwareSession.getInstance(session);

// Check Session. If information is there, we’re done.
// No need to login again.
if (mysession.isLoggedIn() ) {
// Create AuthResponse from session variables…
System.out.println(“********************************”);
System.out.println(“* User is already logged in…..*”);
System.out.println(“********************************”);
returntoUrl = sendSuccessfulResponse(session);
System.out.println(“returntoUrl=====” + returntoUrl);
return “returnto”;
} else {
// login
mysession.setRequestParameters(requestParameters);
return “login”;
}
} else {
System.out.println(“Unknown request mode ‘” + mode
+ “‘… Forcing login…”);
}
}
return null;
}
public String openid() throws Exception {
Map parameterMap = request.getParameterMap();
// if (parameterMap.isEmpty()) {
System.out.println(“Processing empty request. Assuming discovery request…”);
OpenIdProviderService.sendDiscoveryResponse(response);
// }
return null;
}

/**
* Build an AuthResponse to send back to the requester. Use the
* OpenIdProviderService to encapsulate this logic.
*/
private String sendSuccessfulResponse(HttpSession session) {
//System.out.println(“sendSuccessfulResponse() BEGIN…”);
MakotoOpenIdAwareSession mysession = MakotoOpenIdAwareSession
.getInstance(session);
Message authResponse = OpenIdProviderService.buildAuthResponse(
requestParameters, mysession.getUserSelectedId(),
mysession.getUserSelectedClaimedId(),
mysession.getRegistrationModel());

//System.out.println(“sendSuccessfulResponse() END…”);
return authResponse.getDestinationUrl(true);
}
// ログイン情報の取得
public String login() throws Exception {
String userId = request.getParameter(“userId”);
String password = request.getParameter(“password”);
// Validate login.
boolean authenticatedAndApproved = validateLogin(userId, password);
// If invalid, display a message
if (!authenticatedAndApproved) {
System.out.println(“ログイン失敗”);
return ERROR;

} else {

MakotoOpenIdAwareSession mysession = MakotoOpenIdAwareSession
.getInstance(session);

if (mysession.getRequestParameters().hasParameter(“openid.realm”)) {
String realm = mysession.getRequestParameters()
.getParameterValue(“openid.realm”);
String domain = getDomainName(realm);
request.setAttribute(“domain”, domain);
}
return SUCCESS;
}
}

// ログイン許可
public String returnTo() throws Exception {
String userId = “changfatest”;
// 标识码
String userSelectedId = mapUserIdToUserSelectedId(userId);
//
String userSelectedClaimedId = mapSelectedIdToClaimedId(userId);
RegistrationModel registrationModel = getRegistrationModel(userSelectedId);
// create auth response and redirect
MakotoOpenIdAwareSession mysession = MakotoOpenIdAwareSession
.getInstance(session);

Message authResponse = OpenIdProviderService.buildAuthResponse(
mysession.getRequestParameters(), userSelectedId,
userSelectedClaimedId, registrationModel);

mysession.setLoggedIn(true);
mysession.setUserSelectedId(userSelectedId);
mysession.setUserSelectedClaimedId(userSelectedClaimedId);
mysession.setRegistrationModel(registrationModel);

returntoUrl = authResponse.getDestinationUrl(true);

System.out.println(“authResponse.getDestinationUrl(true)==== ”
+ returntoUrl);

return “returnto”;

}

protected RegistrationModel getRegistrationModel(String userSelectedId) {
//System.out.println(“getRegistrationModel() BEGIN…”);
// Ideally, you would read this from a DB. Hardcode for the sample
// app…
RegistrationModel ret = new RegistrationModel();
ret.setDateOfBirth(new YearMonthDay(1982, 9, 10).toDateMidnight()
.toDate());
ret.setEmailAddress(“sample@arkgame.com”);
ret.setFavoriteColor(“blue”);
ret.setFullName(“startnews24 study it skill”);
ret.setOpenId(OpenIdProviderService.getOpEndpointUrl());
ret.setZipCode(“xxx”);
return ret;
}
protected String mapUserIdToUserSelectedId(String userId) {
//System.out.println(“mapUserIdToUserSelectedId() BEGIN…”);
//System.out.println(“mapUserIdToUserSelectedId() END…”);
return getServerUrl() + “/openid/openid?id=xxx”;
}

protected String mapSelectedIdToClaimedId(String userId) {
//System.out.println(“mapSelectedIdToClaimedId() BEGIN…”);
// Ideally, you would read this from a DB, or LDAP, or somewhere,
// / but this is sample code… just return the userid passed in…
//System.out.println(“mapSelectedIdToClaimedId() END…”);
return getServerUrl() + “/openid/openid?id=xx”;
}

/**
* ユーザーの認証
*
* @param user
* @param password
* @return
*/
private boolean validateLogin(String user, String password) {
// TODO
return true;
}

public ParameterList getRequestParameters() {
return requestParameters;
}

public void setRequestParameters(ParameterList requestParameters) {
this.requestParameters = requestParameters;
}

public String getReturntoUrl() {
return returntoUrl;
}

public void setReturntoUrl(String returntoUrl) {
this.returntoUrl = returntoUrl;
}

}

JavaでSSL通信かどうか判断する方法

Javaコード:
private String getDomainName(String url){
if(url.startsWith(“http://”)){
url=url.substring(7);
}else if(url.startsWith(“https://”)){
url = url.substring(8);
}
String result = url.split(“/”)[0];
return result;
}

java入門でFilterインターフェースの作成、設定の方法

1.Filterの設定
@WebFilter(filterName=”authority”
, urlPatterns={“/*”}
, initParams={
@WebInitParam(name=”encoding”, value=”utf8″),
@WebInitParam(name=”loginPage”, value=”/login.jsp”),
@WebInitParam(name=”noLogin”, value=”/noLogin.jsp”)})
public class AuthorityFilter implements Filter
{
private FilterConfig config;
//初期化
public void init(FilterConfig config)
{
this.config = config;
}
public void destroy()
{
this.config = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException,ServletException
{
//Filterのパラメータの取得
String encoding = config.getInitParameter(“encoding”);
String loginPage = config.getInitParameter(“loginPage”);
String noLogin = config.getInitParameter(“noLogin”);
//requestのエンコード
request.setCharacterEncoding(encoding);
HttpServletRequest requ = (HttpServletRequest)request;
HttpSession session = requ.getSession(true);
//アクセスページ
String requestPath = requ.getServletPath();
if( session.getAttribute(“user”) == null
&& !requestPath.endsWith(loginPage)
&& !requestPath.endsWith(noLogin))
{
//forwardログイン画面
request.setAttribute(“tip” , “ログインしてない”);
request.getRequestDispatcher(loginPage)
.forward(request, response);
}
else
{
chain.doFilter(request, response);
}
}
}

2.web.xmlの設定
<filter>
<filter-name>authority</filter-name>
<filter-class>jbelial.Filter.Authority</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
<init-param>
<param-name>loginPage</param-name>
<param-value>/login.jsp</param-value>
</init-param>
<init-param>
<param-name>noLogin</param-name>
<param-value>/noLogin.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>authority</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

JavaでHttpSessionListenerを利用してオンライン人数統計の方法

1.web.xmlの設定
<listener>
<listener-class>com.startnews24.store.common.SessionListenerStartnews24</listener-class>
</listener>
<session-config>
<session-timeout>5</session-timeout>
</session-config>

2.javaコード下記
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListenerStartnews24 implements HttpSessionListener {
private long onlineCnt;
public void sessionCreated(HttpSessionEvent event) {
this.onlineCnt=this.onlineCnt+1;
event.getSession().getServletContext().setAttribute(“onlineCnt”, onlineCnt);
}
public void sessionDestroyed(HttpSessionEvent event) {
this.onlineCnt=this.onlineCnt-1;
event.getSession().getServletContext().setAttribute(“onlineCnt”, onlineCnt);
}

}

Javaで数値(int)から文字列(String)への変換方法

1.Stringからintへ変換
①int i = Integer.parseInt([String]);
i = Integer.parseInt([String],[int radix]);
②int i = Integer.valueOf(my_str).intValue()

2.intからStringへ変換
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = “” + i;

Javaでlistとmap変換するサンプルコード

1.List<V>をMap<K,V>へ変換
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

2.Map<K,V>をList<V>へ変換
Map<String, String> m = new HashMap<String, String>();
m.put(“welcome”, “programe”);
m.put(“tm”, “8”);
m.put(“its”, “Element”);
List<String> list = new ArrayList<String>(m.keySet());
List<String> list = new ArrayList<String>(m.values());

Java開発でjavaオブジェクトとjson文字列の相互変換サンプルコード

Javaコード:
import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {

private static JacksonUtil ju;
private static JsonFactory jf;
private static ObjectMapper mapper;
private JacksonUtil(){}

/**
* 单例初始化
* @Title: newInstance
* @Description: TODO
* @param @return
* @return JacksonUtil
* @throws
*/
public static JacksonUtil newInstance() {
if(ju==null) ju = new JacksonUtil();
return ju;
}

public static ObjectMapper getMapper() {
if(mapper==null) {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
return mapper;
}

public static JsonFactory getFactory() {
if(jf==null) jf = new JsonFactory();
return jf;
}
/**
*
* @Title: obj2json
* @Description: オブジェクト->json文字列
* @param @param obj
* @param @return
* @return String
* @throws
*/
public String obj2json(Object obj) {
if(null != obj){
JsonGenerator jg = null;
try {
jf = getFactory();
mapper = getMapper();
StringWriter out = new StringWriter();
jg = jf.createJsonGenerator(out);
mapper.writeValue(jg, obj);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(jg!=null) jg.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
*
* @Title: json2obj
* @Description: json文字列からjavaオブジェクトに変換
* @param @param json
* @param @param clz
* @param @return
* @return Object
* @throws
*/
public <E>E json2obj(String json,Class<E> clz) {
if(null != json && !””.equals(json.trim())){
try {
mapper = getMapper();
return mapper.readValue(json,clz);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

Struts2入門–入力された値をチェックするサンプルコード

サンプルコード

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE validators PUBLIC “-//Apache Struts//XWork Validator 1.0.3//EN”
“http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd”>
<validators>
<field name=”name”>
<field-validator type=”requiredstring”>
<param name=”trim”>true</param>
<message>ユーザ名前を入力してください</message>
</field-validator>
<field-validator type=”regex”>
<param name=”regex”><![CDATA[(\w{6,20})]]></param>
<message>ユーザ名前の長さは6~20位
</message>
</field-validator>
</field>
<field name=”pass”>
<field-validator type=”requiredstring”>
<param name=”trim”>true</param>
<message>パスワードを入力してください</message>
</field-validator>
<field-validator type=”regex”>
<param name=”regex”><![CDATA[(\w{6,20})]]></param>
<message>パスワードの長さは6~20位
</message>
</field-validator>
</field>
<field name=”age”>
<field-validator type=”int”>
<param name=”min”>1</param>
<param name=”max”>150</param>
<message>must between ${min} and ${max}</message>
</field-validator>
</field>
<field name=”birth”>
<field-validator type=”date”>
<param name=”min”>1960-01-01</param>
<param name=”max”>2040-02-21</param>
<message>must between ${min} and ${max}</message>
</field-validator>
</field>
</validators>

Struts2入門ファイルアップロードを実現するサンプルコード

1.Fileupload.java
public class Fileupload extends ActionSupport {
private File upload;
private String uploadContentType;
private String uploadFileName;
private String title;

private String savePath;

public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}

@Override
public String execute() throws Exception {
System.out.println(getSavePath());
FileOutputStream fos=new FileOutputStream(getSavePath()+”\\”+getUploadFileName());
FileInputStream fis=new FileInputStream(getUpload());
byte[] buffer=new byte[1024];
int len=0;
while((len=fis.read(buffer))>0)
{
fos.write(buffer,0,len);
}

// TODO Auto-generated method stub
return SUCCESS;
}

}

2.Formの定義
<s:form action=”startnews24/upload” enctype=”multipart/form-data” method=”post”>
<s:textfield name=”title” label=”title” />
<s:file name=”upload” label=”選択”/>
<s:submit value=”submit”/>
</s:form>

3.ファイルフィルタの定義
<interceptor-ref name=”fileUpload”>
<param name=”allowedTypes”>image/png.image/gif,image/jpeg</param>
<param name=”maximumSize”>3000</param>
</interceptor-ref>
<result name=”input”>/exception.jsp</result>
<interceptor-ref name=”defaultStack”/>

1 / 212