Is GlassFish Admin console (port 4848) secure? |
|
Метки: Is GlassFish Admin console (port 4848) secure? |
split variable from last slash - jquery |
var string = 'var1/var2/var3';
var result = string.split('/'); //Splits into an array
//var final = result[result.length -1]; //Grabs last value
//result.pop(); //Removes last value
var final = result.pop(); //Removes last value and grap the last value
var previous = result.join('/'); //Grabs the previous part
alert("Previous: " + previous + ", Final Part: " + final); //Alerts results
* This source code was highlighted with Source Code Highlighter.
|
Метки: split variable from last slash - jquery |
lookup |
|
Метки: lookup |
Без заголовка |
|
|
java Mapping Oracle XMLType on JPA (EclipseLink) |
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.xdb.DirectToXMLTypeMapping;
public class XMLDataCustomizer implements DescriptorCustomizer {
public void customize(final ClassDescriptor descriptor) throws Exception {
descriptor.removeMappingForAttributeName("xmlField");
DirectToXMLTypeMapping mapping = new DirectToXMLTypeMapping();
mapping.setAttributeName("xmlField"); //name of the atribute on the Entity Bean
mapping.setFieldName("XML_COLUMN"); //name of the data base column
descriptor.addMapping(mapping);
}
}
Then, all you have to do is use the @Customizer anotation on the entity, for the EntityManager to make use of it when handling the property called xmlField (as seen at the previous code snippet):
@Entity
@Table(name="TABLE_NAME")
@NamedQueries({ /* ... */})
@Customizer(XMLDataCustomizer.class)
public class DataEntity implements Serializable {
/* ... */
private String xmlField;
/* .... */
}
The xmlField attribute does not need @Column anotation, as it's mapping is defined at our DescriptorCustomizer implementation.
* This source code was highlighted with Source Code Highlighter.
|
Метки: Mapping Oracle XMLType on JPA (EclipseLink) |
Clob oracle java |
|
Метки: Clob oracle java |
JPA Criteria API by samples |
long category=200L;
Query query = entityManager.createQuery("select s from OrderItem s " +
"where s.product.category=:cat");
query.setParameter("cat", category);
List<OrderItem> list = query.getResultList();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<OrderItem> from = criteriaQuery.from(OrderItem.class);
Path<Object> path = from.join("product").get("category");
CriteriaQuery<Object> select = criteriaQuery.select(from);
select.where(criteriaBuilder.equal(path, category));
TypedQuery<Object> typedQuery = entityManager.createQuery(select);
List<Object> resultList = typedQuery.getResultList();
assertEqualsList(list, resultList);
|
Метки: JPA Criteria API by samples |
string to xml |
connection = ds.getConnection();
stmt = (OracleCallableStatement) connection.prepareCall("{? = call TEMPLATE.TEMPLATE_TEST() }");
stmt.registerOutParameter(1,OracleTypes.VARCHAR);
stmt.execute();
String xmlString = stmt.getString(1);
System.out.println(xmlString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Use String reader
Document document = builder.parse( new InputSource(new StringReader( xmlString ) ) );
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource( document );
Result dest = new StreamResult( new File( "xml/xmlFileName.xml" ) );
aTransformer.transform( src, dest );
|
Метки: java string to xml file |
Книги |
|
Метки: книги |
... |
|
|
linux How To Find Files by Content Under UNIX |
|
Метки: How To Find Files by Content Under UNIX |
INSERT ... SELECT |
insert into user_role
select "user".id as user_id, "role".id as roles_id from "user" CROSS JOIN "role"
WHERE "user".login = 'root'
and
"role"."name" in ('ROLE_ROOT' , 'ROLE_USER');
|
Метки: INSERT SELECT |
Calling Java from Database Triggers |
|
Метки: Database Triggers |
Хождение по ssh |
|
Метки: ssh |
virtualbox netbenas |
|
Метки: virtualbox netbenas |
netbeans AlternateUserdir |
|
Метки: netbeans |
File Writer |
import java.io.*;
public class Append1
{
public static void main(String[] args)
{
String filename="C:\\file.txt";
System.out.print("Use file : " + filename);
// 1 вариант
try{
FileWriter sw = new FileWriter(filename,true);
sw.write("Add this text to the end of datafile by FileWriter" + "\n");
sw.close();
}catch(Exception e){
System.out.print(e.getMessage());
}
// 2-ой вариант
try {
RandomAccessFile file = new RandomAccessFile(filename, "rw");
file.skipBytes((int)file.length()); //skip to the end of the file
file.writeBytes("Add this text to the end of datafile by RandomAccessFile\n");
file.close();
}catch(Exception e){
System.out.print(e.getMessage());
}
// 3-ий вариант
PrintStream out = null;
try {
out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream(filename, true)));
out.println("Add this text to the end of datafile by FileOutputStream");
} catch(IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: File Writer java |
log4j |
log4j.appender.LOGFILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOGFILE.File=log.file
log4j.appender.LOGFILE.Append=true
log4j.appender.bulk.datePattern='.'yyyy-MM-dd'.log'
log4j.appender.LOGFILE.Threshold=WARN
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
|
Метки: log4j |
Scoped |
|
Метки: Scoped CDI |
... |
|
Метки: NetBeans 7 Python |
бизнес идея |
|
Метки: бизнес идея |
Jetty-runner |
|
Метки: Jetty-runner |
postgres password |
|
Метки: postgres password |
ant delete folder |
`find . -name foo -exec rm {}`
* This source code was highlighted with Source Code Highlighter.
|
Метки: ant java |
regexp http |
Поиск тега A в HTML-коде с помощью регулярного выражения
Выражение:
(?i)<a([^>]+)>(.+?)</a>
Поиск ссылки в HTML-коде с помощью регулярного выражения
\s*(?i)href\s*=\s*(\"([^"]*\")|'[^']*'|([^'">\s]+));
* This source code was highlighted with Source Code Highlighter.package ru.topcode.skillbase.regexp;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HTMLLinkExtrator {
private Pattern patternTag, patternLink;
private Matcher matcherTag, matcherLink;
private static final String HTML_A_TAG_PATTERN = "(?i)<a([^>]+)>(.+?)</a>";
private static final String HTML_A_HREF_TAG_PATTERN = "\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))";
public HTMLLinkExtrator() {
patternTag = Pattern.compile(HTML_A_TAG_PATTERN);
patternLink = Pattern.compile(HTML_A_HREF_TAG_PATTERN);
}
/**
* Поиск ссылок с помощью регулярных выражений
*
* @param html
* html-код
* @return Список ссылок и текстов ссылок
*/
public ArrayList<HtmlLink> grabHTMLLinks(final String html) {
ArrayList<HtmlLink> result = new ArrayList<HtmlLink>();
matcherTag = patternTag.matcher(html);
while (matcherTag.find()) {
String href = matcherTag.group(1); // href
String linkText = matcherTag.group(2); // текст ссылки
matcherLink = patternLink.matcher(href);
while (matcherLink.find()) {
String link = matcherLink.group(1); // ссылка
result.add(new HtmlLink(link, linkText));
}
}
return result;
}
public class HtmlLink {
String link;
String linkText;
public HtmlLink(String link, String linkText) {
this.link = link;
this.linkText = linkText;
}
@Override
public String toString() {
return new StringBuffer("Ссылка : ").append(this.link).append(
" Текст ссылки : ").append(this.linkText).toString();
}
}
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: regexp http |
jetty |
Worker Role Implementation
To do this, basically just start with a new Cloud project in Visual Studio, and add one Worker Role (just the same as a “Hello World” Worker Role app). And below is the only code I added inside of the Run() method in the WorkerRole class (minus the tracing code which I removed from this view):
string response = "";
try
{
System.IO.StreamReader sr;
string port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpIn"].IPEndpoint.Port.ToString();
string roleRoot = Environment.GetEnvironmentVariable("RoleRoot");
string jettyHome = roleRoot + @"\approot\app\jetty7";
string jreHome = roleRoot + @"\approot\app\jre6";
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = String.Format("\"{0}\\bin\\java.exe\"", jreHome);
proc.StartInfo.Arguments = String.Format("-Djetty.port={0} -Djetty.home=\"{1}\" -jar \"{1}\\start.jar\"", port, jettyHome);
proc.EnableRaisingEvents = false;
proc.Start();
sr = proc.StandardOutput;
response = sr.ReadToEnd();
}
catch (Exception ex)
{
response = ex.Message;
Trace.TraceError(response);
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: jetty |
Как превратить браузер в notepad за 1 секунду |
Как превратить браузер в notepad за 1 секунду
Браузеры*, HTML*
Открыть новую закладку, скопировать в адресную строку
data:text/html, <html contenteditable>
и нажать Enter.
* This source code was highlighted with Source Code Highlighter.
|
Метки: notepad |
getRealAddress |
public static String getAddress(HttpServletRequest request) {
return request.getRemoteAddr();
}
public static String getRealAddress(HttpServletRequest request) {
String xFor = request.getHeader("X-Forwarded-For");
return xFor != null && xFor.trim().length() > 0 ? xFor : getAddress(request);
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: java getRealAddress |
Без заголовка |
|
Метки: бизнес идея |
Java jar war |
|
Метки: java jar war |
200 лучших книг по версии BBC |
|
Метки: 200 лучших книг по версии BBC |
facebook Cookie |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
<!--
var is_not_publish = true;
var data = new Object();
var del_add_text = "Delete application";//"Удалить приложение";
var timeline_on = "Timeline On";//"Хроника включена";
var timeline_off = "Timeline Off";//"Хроника выключена";
var delete_txt = "delete";//"удалить";
//var ntv_verb = getMeta("og:type");
//var ntv_objectType = "ntv_program";
var ntv_verb = 'ntvtimeline:ntv_live';
var ntv_objectType = 'peredacha';
var postId=0; // id - новости на facebook
var postIdTimer = null; // таймер для отправки просмотренного видео
var url = getMeta("og:url");
url = encodeURIComponent(url);
window.fbAsyncInit = function () {
FB.init({
appId: '398092463538505', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
oauth: true, // enable OAuth 2.0
xfbml: true // parse XFBML
});
//TODO возможно сюда перенести функции publish_news updateButton
// так было в примере !?
// run once with current status and whenever the status changes
//тут вызов два раза
FB.getLoginStatus(showUserPanel);
FB.Event.subscribe('auth.statusChange', showUserPanel);
};
function fbchecker(checked){
console.log(checked);
}
function getVerb(){
var result = 'ntvtimeline:ntvwatch?ntvvideo';
// result = 'ntvtimeline:ntv_live?peredacha';
//ntvtimeline:peredacha - ntvtimeline:ntv_live?peredacha=
//ntvtimeline:ntv_video - ntvtimeline:ntv_watch?ntv_video=
var type = getMeta("og:type");
if(type.length>0){
var verb = type.split(":");
if(verb != null && verb[1] == 'peredacha'){
result = 'ntvtimeline:ntv_live?peredacha';
}
if(verb != null && verb[1] == 'ntv_video'){
result = 'ntvtimeline:ntv_watch?ntv_video';
}
if(type!=null && type =="article" ){
result = 'news.reads?article';
}
if(type!=null && type =="video.other" ){
result = 'video.watches?video';
}
}
return result;
}
function getObjectType(){
//var ntv_objectType = 'ntv_video'; //'peredacha''
var result = 'ntv_video';
var type = getMeta("og:type");
if(type.length>0){
var verb = type.split(":");
if(verb != null && verb[1] == 'peredacha'){
result = 'peredacha';
}
if(verb != null && verb[1] == 'ntvvideo'){
result = 'ntvvideo';
}
if(type!=null && type =="article" ){
result = 'article';
}
if(type!=null && type =="video.other" ){
result = 'video';
}
}
return result;
}
function clckbtnaddnews(){
$('#btnaddnews').removeClass("add");
$('#btnaddnews').addClass("save");
$('#btnaddnews').html('I read this');
$('#btnaddnews').attr('disabled', 'disabled');
}
function publish_news(){
var isStat = isStatus();
// console.log(" is_not_publish = "+is_not_publish +"; isStatus = " + isStat);
if(is_not_publish && isStat){
is_not_publish = false;
clckbtnaddnews();
// var ntv_verb = 'ntvtimeline:ntv_watch';
// var ntv_objectType = 'ntv_video';
// var ntv_verb = 'ntvtimeline:watch_online';
// var ntv_objectType = 'ntv_program';
//console.log('/me/' + ntv_verb + '?' + ntv_objectType + '=' + url);
console.log('/me/' + getVerb() + '=' + url);
var mbody = getMeta("og:title");
FB.api('/me/' + getVerb() + '=' + url, 'post', {message: mbody},
function (result) {
postId = result.id;
console.log(result);
postTimer();
// console.log('published with id = ' + result.id);
showPopupWindow(result);
});
}
clckbtnaddnews();
btnLater();
}
// $(document).ready(function(){
// $(document).not('основной_элемент').click(function(){
// $('элемент').slideUp(); // клик был на странице вне элемента
// });
//
// $('основной_элемент').click(function(){
// $('элемент').slideDown(); // клик был на самом основном элементе
// return false;
// });
//
//});
function showPopupWindow(result){
$('#infowindow').fadeIn(4000, function (){
setTimeout(function(){
$('#infowindow').fadeOut(4000);
},3000);
});
}
// propname,propval, content
function getMeta(property) {
var metas = document.getElementsByTagName('META');
var i;
var url;
for (i = 0; i < metas.length; i++){
if (metas[i].getAttribute('property') == property){
url = metas[i].getAttribute('content');
return url
break;
}
}
// url = window.location.toString();
return url;
}
function showUserPanel(response) {
FB.getLoginStatus(function(response) {
showHelp(response.status);
if (response.status === 'connected') {
document.getElementById('login-panel-on').setAttribute('style','display:block;');
document.getElementById('login-panel-off').setAttribute('style','display:none;');
loadUserInfo(response);
}else{
document.getElementById('setting-dialog').setAttribute('style','display:none;');
document.getElementById('login-panel-on').setAttribute('style','display:none;');
document.getElementById('login-panel-off').setAttribute('style','display:block;');
if(response.status === 'not_authorized'){
// document.getElementById('helpcenter').style.display='';
}
}
});
}
function showHelp(resp){
var fb_source = false;
var fb_appcenter = false;
var access_token = "0";
//?fb_source=appcenter&fb_appcenter=1&code=AQB4cKbGiO
var search = document.location.search.substr(1);
var parts = search.split("&");
for (i=0; i<parts.length; i++) {
var curr = parts[i].split('=');
if(curr[0] == "fb_source" & curr[1] == "appcenter"){
fb_source = true;
}
if(curr[0] == "fb_appcenter" & curr[1] == "1"){
fb_appcenter = true;
}
if(curr[0] == "fb_action_ids" & curr[1] == "486575714693365"){
fb_source = true;
fb_appcenter = true;
}
}
if(fb_source && fb_appcenter || resp === 'not_authorized'){
document.getElementById('helpcenter').style.display='block';
document.getElementById('popup_overlay').style.display='block';
}
}
function btnLater(){
document.getElementById('helpcenter').style.display='none';
document.getElementById('popup_overlay').style.display='none';
}
var dx = [0,-650,-2*650,-1930, -2495 , -3130];
var pos = 0;
function step_left(){
console.log('step_left');
pos--;
if(pos<0) pos = 0;
var xpos = dx[pos];
if($.browser.safari){
$('#infolenta').animate({'background-position-x': xpos+'px'},'slow');
}else{
$('#infolenta').css("background-position", xpos+'px '+ '-64px');
}
}
function step_right(){
console.log('step_right');
pos++;
if(pos>(dx.length-1)) pos = 0;
var xpos = dx[pos];
if($.browser.safari){
$('#infolenta').animate({'background-position-x': xpos+'px'},'slow');
}else{
$('#infolenta').css("background-position", xpos+'px '+ '-64px');
}
}
function loadUserInfo(response){
//console.log("response.authResponse = "+response.authResponse);
if (response.authResponse) {
FB.api('/me', function(response) {
//console.log(response.id + " = " +response.name);
var userPicture = document.getElementById('user-picture');
userPicture.innerHTML = '<img src="https://graph.facebook.com/'+ response.id + '/picture">';
var userName = document.getElementById('user-name');
userName.innerHTML = '<a href=\"'+response.link+'\" target=\"_blank\">'+response.name+'</a>' ;
get_timeline_status();
setTimeout(publish_news,11000);
});
}
}
function showSettingPanel(){
document.getElementById('login-panel-on').setAttribute('style','display:none;');
document.getElementById('setting-dialog').setAttribute('style','display:block;');
hide();
FB.getLoginStatus(function(response) {
//console.log("response.authResponse = "+response.authResponse);
if (response.authResponse) {
FB.api('/me', function(response) {
var userPicture = document.getElementById('user-picture1');
userPicture.innerHTML = '<img src="https://graph.facebook.com/'+ response.id + '/picture">';
var userName = document.getElementById('user-name1');
userName.innerHTML = '<a href=\"'+response.link+'\" target=\"_blank\">'+response.name+'</a>' ;
});
}
});
}
function hideSettingPanel(){
document.getElementById('login-panel-on').setAttribute('style','display:block;');
document.getElementById('setting-dialog').setAttribute('style','display:none;');
}
// Load the SDK Asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);js.id = id;
js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1&appId=398092463538505";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
//(function (d) {
// var js, id = 'facebook-jssdk';
// if (d.getElementById(id)) {
// return;
// }
// js = d.createElement('script');
// js.id = id;
// js.async = true;
// js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1&appId=398092463538505";
// d.getElementsByTagName('head')[0].appendChild(js);
//} (document));
// устанавливаем cookie для того чтобы понять отключили ли мы ведение хроники или нет .
// name = timeline : value on | off
function set_cookie (name, value){
var cookie_string = name + "=" + encodeURIComponent ( value );
var expires = new Date();
expires.setFullYear(expires.getFullYear() + 1);
var path = "/";
var domain = 'ntv.ru';
var secure = false;
if (expires) cookie_string += '; expires=' + expires.toGMTString();
if (path) cookie_string += '; path=' + path;
if (domain) cookie_string += '; domain=' + domain;
if (secure) cookie_string += '; secure';
//console.log('set_cookie : ' + cookie_string);
document.cookie = cookie_string;
}
function get_cookie ( cookie_name ){
var pattern = "(?:; )?" + cookie_name + "=([^;]*);?";
var regexp = new RegExp(pattern);
if (regexp.test(document.cookie)){
return decodeURIComponent(RegExp["$1"]);
}
return false;
}
function isStatus(){
if ( ! get_cookie ( "timeline" ) ){
set_cookie ( "timeline", "on");
return true;
}else{
var status = get_cookie ( "timeline" );
if(status == 'on'){
return true;
}
}
return false;
}
function set_timeline_status(){
// если ее нет то выслявляем в off
var status = isStatus();
if(status) {
set_cookie ('timeline', 'off');
}
else{
set_cookie('timeline', 'on');
publish_news();
}
get_timeline_status();
}
// on | off
function get_timeline_status(){
// если ее нет то выслявляем в off
if ( ! get_cookie ( "timeline" ) ){
set_cookie ( "timeline", "on");
//console.log("timeline = off");
}
var isStatus = false;
var f = document.getElementById('timeline_btn');
var el = document.getElementById('timeline-status');
var status = get_cookie ( "timeline" );
//console.log( "status = " +status);
if(status == "off") {
f.style.marginTop='52px';
f.title = timeline_off;//'Хроника Выкл.';
el.style.backgroundImage = 'url(/i/fb/timeline_off.gif)';
} else
if(status == "on"){
f.style.marginTop='2px';
f.title = timeline_on;//'Хроника Вкл.';
el.style.backgroundImage = 'url(/i/fb/timeline_on.png)';
isStatus = true;
}
return isStatus;
}
// delete app
function delete_ntv_app(){
set_cookie('timeline', 'on');
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api("/me/permissions","DELETE",function(response){
//console.log(" DELETE app : "+response); //gives true on app delete success
document.location.reload();
});
}
});
}
function all_history_show(flag){
//console.log("all_history_show == "+ flag );
var id = document.getElementById('history-list');
var el = document.getElementById('history');
if(flag){
id.style.display="block";
el.style.display="block";
}else{
id.style.display="none";
el.style.display="none";
}
}
// всплывающее окно с прочитанными новостями
<!--
function show (evt, id) {
var evt = evt || window.event;
var f = document.getElementById('history-items');
f.opacityFilter = 0;
f.className = 'popup_active';
f.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (f.opacityFilter * 100) + ');';
f.style.opacity = f.opacityFilter;
f.style.display = 'block';
f.style.top = '0';
f.style.left = '410px';
window.setTimeout('animate()', 50);
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
return false;
}
function open_history(){
window.open("http://www.facebook.com/me/app_398092463538505", "", "");
}
function showHistory(){
var f = document.getElementById('history-items');
f.style.display = 'block';
//console.log('showHistory');
}
// формат времени
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
// является ли переменная числом
function isNum(v) {
return typeof v === 'number' && isFinite(v);
}
// загрузка локальной истории
function load_history(evt, id){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log(getVerb());
FB.api("/me/"+getVerb(),"GET",function(response){
// парсим ответ
if(!response.data || !response.data.length){return;}
var length = response.data.length;
if(length>0){
for(var i=0; i<length && i<7; i++) {
var news_id = response.data[i].id;
// var ntv_article_id = response.data[i].data.ntv_article.id;
var date = new Date(response.data[i].publish_time);
var y = date.getYear()+1900;
var m = date.getMonth();
var d = date.getDate();
var isNumder = false ;
var time = "";
isNumder = isNum(date.getHours()) && isNum(date.getMinutes());
if(isNumder){
var h = isNum(date.getHours()) ? checkTime(date.getHours()) : "12";
var mi =isNum(date.getMinutes()) ? checkTime(date.getMinutes()) : "00";
time = h +":"+mi+" ";
}
ntv_objectType = getObjectType();
console.log(response.data[i]);
if(response.data[i].data == undefined) continue;
var title = time + response.data[i].data[ntv_objectType].title;
var url = response.data[i].data[ntv_objectType].url;
//data.push(news_id,title);
if(data[news_id] == null){
data[news_id] = title;
//console.log( data[news_id] +" = "+ title);
append_news(news_id , title , url);
}
}
show (evt, id);
}
});
}
});
}
function delete_news(news_id){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api("/"+news_id,"DELETE",function(response){
//console.log("delete_news : " + response);
if(response == true){
var y = document.getElementById('id'+news_id);
var x = document.getElementById("history-items");
x.removeChild(y);
// скрыть окно если в нем больше ничего нет :
var size = $('#history-items').children().size();
//console.log("history-items.length : " + size);
if(size == 1){
hide();
}
}
});
}
});
}
// вставка новости в div истории
function append_news (news_id, title , url) {
var el = document.createElement('div');
el.setAttribute ('id', 'id'+news_id);
el.setAttribute ('style','display: block; top: 0px; left: 0px;width:400px; position: relative;');
el.setAttribute ('class','newli');
var text = title.substring(0,55)+'...';
text = "<a href=\""+ url+"\" class='ntv_decoration' >" + text + "</a>";
el.innerHTML=text + "<a class='close1 ntv_decoration' href=\"javascript:delete_news('"+news_id+"') ;\"><span>"+delete_txt+"</span></a>";
document.getElementById('history-items').appendChild(el);
}
function hide() {
var div = document.getElementById('history-items');
if (div != null) {
div.className = 'footnote_new';
div.style.display = 'none';
}
return false;
}
function animate() {
var f = document.getElementById('history-items');
f.opacityFilter += 0.05;
f.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (f.opacityFilter * 100) + ');';
f.style.opacity = f.opacityFilter;
if (f.opacityFilter<1) window.setTimeout('animate()', 50);
}
function getPosition(offsetTrail) {
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail) {
offsetLeft += offsetTrail.offsetLeft;
offsetTop += offsetTrail.offsetTop;
offsetTrail = offsetTrail.offsetParent;
}
return {left:offsetLeft, top:offsetTop}
}
// отсылка информации в facebook о том что мы смотрим видео
function postTimer(){
postIdTimer = setTimeout(function run() {
if(postId!= undefined && postId.length>1){
console.log(postId);
FB.api('/'+postId, 'post', {
expires_in : '5000'
} ,function(response){
resp1 = response;
console.log(response );
if(response.error && response.error.code==100){
clearTimeout(postIdTimer);
postIdTimer = null;
}
} );
}
if(postIdTimer!=null)
postIdTimer = setTimeout(run, 5000);
}, 5000);
}
var fb_timer = null;
function fb_play(){
console.log('fb_play');
fb_timer = setTimeout(publish_news,11000);
postTimer();
}
function fb_stop(){
console.log('fb_stop');
if (fb_timer!= null){
clearTimeout(fb_timer);
fb_timer = null;
clearTimeout(postIdTimer);
postIdTimer = null;
}
}
$(document).ready(function () {
if(true){
document.getElementById('login-txt1').innerHTML='Share with friends in Facebook information that you have read and looked at ntv.ru';
if(document.getElementById('login-txt2'))
document.getElementById('login-txt2').innerHTML='Log in to start';
document.getElementById('setting').setAttribute('title','Application settings');
document.getElementById('history-link').setAttribute('title','The history of your activity on the site НТВ.RU');
document.getElementById('history-link').innerHTML='your activity';
document.getElementById('all_history_link').innerHTML='The whole history of activity';
document.getElementById('all_history_link').setAttribute('title','The whole history of activity of the application on the site НТВ.RU');
document.getElementById('delete_app').innerHTML='Remove the application';
document.getElementById('delete_app').setAttribute('title','Remove the application and all the history of its activity');
document.getElementById('x_image').setAttribute('title','Close');
document.getElementById('history-header-txt').innerHTML='<b>History of activity:</b>';
}
});
//-->
* This source code was highlighted with Source Code Highlighter.
|
Метки: facebook api Cookie |
Example Basic Authentication |
1 создаем проект !
2. Прописываем ему web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>
Protected Site
</web-resource-name>
<!-- This would protect the entire site -->
<url-pattern> /* </url-pattern>
<!-- If you list http methods,
only those methods are protected -->
<http-method> DELETE </http-method>
<http-method> GET </http-method>
<http-method> POST </http-method>
<http-method> PUT </http-method>
</web-resource-collection>
<auth-constraint>
<!-- Roles that have access -->
<role-name> test </role-name>
</auth-constraint>
</security-constraint>
<!-- BASIC authentication -->
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> Example Basic Authentication </realm-name>
</login-config>
<!-- Define security roles -->
<security-role>
<description> Test role </description>
<role-name> test </role-name>
</security-role>
<filter>
<filter-name>NewFilter</filter-name>
<filter-class>com.isalnikov.NewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>NewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>com.isalnikov.NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
2. Tomcat - tomcat-users.xml
<tomcat-users>
<role rolename="test"/>
<user username="user" password="pass" roles="test"/>
</tomcat-users>
3. server.xml
<Engine>
...
<Realm className="org.apache.catalina.realm.MemoryRealm" />
...
</Engine>
4. logout (logout.jsp)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
session.invalidate();
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // HTTP 401
response.setHeader("WWW-<wbr>Authenticate", "Basic realm=\"xyzzy\"");
//response.sendRedirect("index.jsp");
%>
* This source code was highlighted with Source Code Highlighter.
|
|
Без заголовка |
|
Метки: бизнес идея |
Oracle Java 7 в Ubuntu 12.04 |
|
Метки: Oracle Java 7 в Ubuntu 12.04 |
Gnome Classic в Ubuntu 12.04 |
|
Метки: Gnome Ubuntu 12.04 |
Virtualbox auto mount Folder |
|
Метки: Virtualbox auto mount Folder |
Ubuntu boot error in VirtualBox |
|
Метки: Ubuntu VirtualBox |
Без заголовка |
package ru.zeroed.test.doublebrace;
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
List values = new ArrayList() {{
add("one");
add("two");
add("three");
}};
for (String value : values) {
System.out.println(value);
}
}
}
class Parent {
public Parent() {
System.out.println("Parent constructor");
}
{
System.out.println("Parent initialization block");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child constructor");
}
{
System.out.println("Child initialization block");
}
}
public class InitTest {
public static void main(String[] args) {
new Child();
}
}
Parent initialization block
Parent constructor
Child initialization block
Child constructor
class AnotherInnerTest {
private List values;
public AnotherInnerTest() {
System.out.println("AnotherInnerTest()");
values = new ArrayList();
}
public void addValue(String value) {
values.add(value);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (String value : values) {
builder.append(value);
}
return builder.toString();
}
}
public class User {
public static void main(String[] args) {
AnotherInnerTest test = new AnotherInnerTest(){{
System.out.println("Overrided");
addValue("hi!");
}};
System.out.println(test);
}
}
AnotherInnerTest()
Overrided
hi!
//Parent.java
public class Parent
{
public Parent(int x)
{
System.out.println("Parent ctor(int)");
}
{
System.out.println("Parent init");
}
}
//Child.java
public class Child extends Parent
{
public Child()
{
super(x());
System.out.println("Child ctor()");
}
{
System.out.println("Child init");
}
private static int x()
{
System.out.println("Child.x()");
return 0;
}
}
//Test.java
public class Test
{
public static void main(String[] args)
{
new Child();
}
}
Заметили super(x()) в конструкторе? А вывод на консоль будет таким:
Child.x()
Parent init
Parent ctor(int)
Child init
Child ctor()
|
Метки: Эффект «double brace» java |
Тэг Embed во Flash Develop |
|
Метки: Тэг Embed во Flash Develop |
SQL подсчет количества повторов |
SELECT mid, COUNT(mid) AS cnt FROM MESSAGE GROUP BY mid
|
|
jquery table select |
Есть таблица - берем из нее значения
jquery filter
<tr id="m_260">
<td attr_id="idx">3</td>
<td attr_id="pid">3</td>
<td attr_id="mtext">Новый год!!!</td>
<td attr_id="adate">20.12.2012 10:18</td>
<td attr_id="edate">27.12.2012 10:18</td>
<td attr_id="cdate">20.12.2012 10:55</td>
<td attr_id="aid" action_val="0">Добавлено</td>
<td attr_id="tid">0</td>
</tr>
//.filter('[attr_id=idx]')
var row_elem = $("#"+mid).children();
var prior = row_elem.filter('[attr_id=pid]').html();
var message_text = row_elem.filter('[attr_id=mtext]').html();
var activation_date = row_elem.filter('[attr_id=adate]').html();
var end_date = row_elem.filter('[attr_id=edate]').html();
* This source code was highlighted with Source Code Highlighter.
|
Метки: jquery table row data filter |
... |
|
Метки: flashdevelop |
Без заголовка |
package ru..term.util;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;
/**
*
* @author i.salnikov
*/
public class EclipseLinkSessionCustomizer implements SessionCustomizer{
@Override
public void customize(Session session) throws Exception {
JNDIConnector connector = (JNDIConnector) session.getLogin().getConnector();
connector.setLookupType(JNDIConnector.STRING_LOOKUP);
}
}
|
|